51单片机计算器lcd1602代码
时间: 2023-10-06 12:14:08 浏览: 105
51 LDC1602驱动代码
以下是一个简单的基于51单片机和LCD1602的计算器代码:
```
#include <reg52.h>
#include <stdio.h>
#include <string.h>
#define LCD_DATA P0
sbit RS = P2^0;
sbit RW = P2^1;
sbit E = P2^2;
char buffer[17]; // 用于存储LCD上显示的字符串
char keypad_map[4][4] = {{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}};
char stack[17]; // 用于存储用户输入的数字
int stack_top = 0; // 栈顶指针
void delay(int i)
{
while(i--);
}
void lcd_write_cmd(unsigned char cmd)
{
LCD_DATA = cmd;
RS = 0;
RW = 0;
E = 1;
delay(50);
E = 0;
}
void lcd_write_data(unsigned char dat)
{
LCD_DATA = dat;
RS = 1;
RW = 0;
E = 1;
delay(50);
E = 0;
}
void lcd_init()
{
lcd_write_cmd(0x38); // function set
delay(500);
lcd_write_cmd(0x06); // entry mode set
delay(500);
lcd_write_cmd(0x0c); // display on/off control
delay(500);
lcd_write_cmd(0x01); // clear display
delay(500);
}
void lcd_display(char* str)
{
int len = strlen(str);
if (len <= 16) {
lcd_write_cmd(0x80); // set DDRAM address to 0x00
for (int i = 0; i < len; i++) {
lcd_write_data(str[i]);
}
for (int i = len; i < 16; i++) {
lcd_write_data(' ');
}
} else {
for (int i = 0; i < 16; i++) {
lcd_write_data(str[i]);
}
lcd_write_cmd(0xc0); // set DDRAM address to 0x40
for (int i = 16; i < len; i++) {
lcd_write_data(str[i]);
}
}
}
void push(char ch)
{
if (stack_top < 16) {
stack[stack_top++] = ch;
}
}
int pop()
{
if (stack_top > 0) {
return stack[--stack_top] - '0';
} else {
return 0;
}
}
void clear_stack()
{
stack_top = 0;
}
int calculate(char op)
{
int num2 = pop();
int num1 = pop();
switch(op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
void main()
{
lcd_init();
lcd_display(" Calculator");
delay(500);
lcd_write_cmd(0x01); // clear display
while(1) {
for (int i = 0; i < 4; i++) {
P1 = ~(1 << i);
for (int j = 0; j < 4; j++) {
if ((P1 & (1 << (j + 4))) == 0) { // 判断按键是否按下
if (keypad_map[i][j] == '=') {
int result = 0;
char str_result[17];
while (stack_top > 0) { // 计算栈内表达式
result = calculate(stack[--stack_top]);
}
sprintf(str_result, "Result: %d", result);
lcd_display(str_result);
clear_stack();
} else if (keypad_map[i][j] == 'C') {
clear_stack();
lcd_write_cmd(0x01); // clear display
} else if (keypad_map[i][j] == '+' ||
keypad_map[i][j] == '-' ||
keypad_map[i][j] == '*' ||
keypad_map[i][j] == '/') {
push(keypad_map[i][j]);
buffer[strlen(buffer)] = keypad_map[i][j];
lcd_display(buffer);
} else {
push(keypad_map[i][j]);
buffer[strlen(buffer)] = keypad_map[i][j];
lcd_display(buffer);
}
while ((P1 & (1 << (j + 4))) == 0); // 等待按键松开
}
}
}
}
}
```
该代码使用了一个简单的栈来实现计算器的功能,可以通过按下不同的键盘按钮输入数字和运算符,并在LCD上显示结果。
阅读全文