#include <reg51.h> #include "oLED.h" #include "key.h" #include "stdio.h" #include "stdlib.h" #include "string.h" // ¼ÆËãÆ÷Ö÷³ÌÐò void calculator(){ char buffer[16]; char operation = '\0'; int operand1 = 0; int operand2 = 0; int result = 0; int x_position=0; int y_position=2; unsigned char position = 0; while(1){ char key = ReadKey(); OLED_ShowString(0, 0, "Calculator"); // ´¦ÀíÊý×Ö°´¼ü if(key>='0' && key<='9'){ buffer[position]=key; buffer[position+1]='\0'; position++; OLED_ShowChar(x_position,y_position, key); x_position+=10; } // ´¦ÀíÔËËã·û°´¼ü if(key=='+' || key=='-' || key=='*' || key=='/'){ operation = key; operand1 = atoi(buffer); memset(buffer, 0, sizeof(buffer)); position = 0; y_position+=1; x_position=0; OLED_ShowChar(x_position,y_position, key); y_position+=1; } // ´¦ÀíµÈºÅ°´¼ü if (key == '=') { y_position+=1; x_position=0; OLED_ShowChar(x_position,y_position, key); y_position+=1; operand2 = atoi(buffer); memset(buffer, 0, sizeof(buffer)); switch (operation) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '*': result = operand1 * operand2; break; case '/': result = operand1 / operand2; break; } sprintf(buffer, "%d", result); OLED_ShowString(x_position, y_position, buffer); position = strlen(buffer); } // ´¦ÀíÇå³ý°´¼ü if (key == 'C') { memset(buffer, 0, sizeof(buffer)); OLED_Clear(); position = 0; x_position=0; y_position=2; } delay(100); // ÑÓʱһ¶Îʱ¼äÒÔ±ÜÃâ°´¼üÖظ´ÊäÈë } } void main() { OLED_Init(); // oLED³õʼ»¯ OLED_Clear(); calculator(); }
时间: 2024-01-28 10:04:06 浏览: 228
这段代码是一个基于51单片机的计算器程序。它包括了键盘读取、OLED显示、加减乘除四则运算、清除等功能。程序通过读取键盘输入的数字和运算符,根据运算符进行相应的运算,并将结果显示在OLED上。这个程序还包括一些错误处理,比如当输入的数字或运算符不合法时,程序会清空缓存并重新开始输入。整个程序比较简单,适合初学者进行学习和实践。
阅读全文