arduino代码设计电子算盘
时间: 2023-06-19 07:09:42 浏览: 195
arduino 代码
5星 · 资源好评率100%
以下是一个简单的Arduino代码示例,用于设计一个可以执行基本算术运算的电子算盘。该算盘具有一个LCD显示屏和一些按钮,用于输入数字和进行运算。该代码支持加法、减法、乘法和除法运算。
```
#include <LiquidCrystal.h>
//定义LCD连接引脚
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//定义按钮引脚
int btnAdd = 6;
int btnSub = 7;
int btnMul = 8;
int btnDiv = 9;
int btnEqual = 10;
int btnClear = 13;
//定义变量
float num1 = 0;
float num2 = 0;
float result = 0;
char op;
void setup() {
//初始化LCD
lcd.begin(16, 2);
//设置按钮引脚为输入模式
pinMode(btnAdd, INPUT);
pinMode(btnSub, INPUT);
pinMode(btnMul, INPUT);
pinMode(btnDiv, INPUT);
pinMode(btnEqual, INPUT);
pinMode(btnClear, INPUT);
//显示欢迎信息
lcd.print("Welcome to");
lcd.setCursor(0, 1);
lcd.print("Electronic Calc");
delay(2000);
lcd.clear();
}
void loop() {
//读取按钮状态
int btnAddState = digitalRead(btnAdd);
int btnSubState = digitalRead(btnSub);
int btnMulState = digitalRead(btnMul);
int btnDivState = digitalRead(btnDiv);
int btnEqualState = digitalRead(btnEqual);
int btnClearState = digitalRead(btnClear);
//读取第一个数字
if (Serial.available() > 0) {
num1 = Serial.parseFloat();
lcd.print(num1);
}
//读取运算符
if (btnAddState == HIGH) {
op = '+';
lcd.print(op);
}
else if (btnSubState == HIGH) {
op = '-';
lcd.print(op);
}
else if (btnMulState == HIGH) {
op = '*';
lcd.print(op);
}
else if (btnDivState == HIGH) {
op = '/';
lcd.print(op);
}
//读取第二个数字
if (Serial.available() > 0) {
num2 = Serial.parseFloat();
lcd.print(num2);
}
//计算结果
if (btnEqualState == HIGH) {
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
lcd.print('=');
lcd.print(result);
}
//清空屏幕
if (btnClearState == HIGH) {
lcd.clear();
}
}
```
注意,这只是一个简单的示例,实际的电子算盘可能需要更复杂的代码来处理更多的功能和错误情况。
阅读全文