1602液晶显示计算器代码
时间: 2023-10-31 12:10:52 浏览: 131
下面是一个简单的基于Arduino的1602液晶显示计算器代码,可进行加减乘除四则运算:
```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int firstNum = 0;
int secondNum = 0;
char operatorSign = ' ';
bool isSecondNum = false;
void setup() {
lcd.begin(16, 2);
lcd.print("Calculator");
}
void loop() {
if (Serial.available() > 0) {
char input = Serial.read();
if (input >= '0' && input <= '9') {
if (!isSecondNum) {
firstNum = firstNum * 10 + (input - '0');
lcd.setCursor(0, 1);
lcd.print(firstNum);
} else {
secondNum = secondNum * 10 + (input - '0');
lcd.setCursor(0, 1);
lcd.print(secondNum);
}
} else if (input == '+' || input == '-' || input == '*' || input == '/') {
operatorSign = input;
isSecondNum = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(firstNum);
lcd.print(operatorSign);
} else if (input == '=') {
int result = 0;
switch (operatorSign) {
case '+':
result = firstNum + secondNum;
break;
case '-':
result = firstNum - secondNum;
break;
case '*':
result = firstNum * secondNum;
break;
case '/':
result = firstNum / secondNum;
break;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(result);
firstNum = result;
secondNum = 0;
operatorSign = ' ';
isSecondNum = false;
} else if (input == 'C') {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Calculator");
firstNum = 0;
secondNum = 0;
operatorSign = ' ';
isSecondNum = false;
}
}
}
```
该代码使用了Arduino的LiquidCrystal库来控制1602液晶屏幕,并通过串口接收输入。它使用了两个整数变量来存储第一个和第二个数字,以及一个字符变量来存储运算符。当接收到数字时,代码将数字附加到正确的变量中,并在屏幕上显示数字。当接收到运算符时,代码将设置运算符,并准备接收第二个数字。当接收到等号时,代码将执行所选运算,并在屏幕上显示结果。最后,当接收到C时,代码将清除所有变量并重置屏幕输出。
阅读全文