arduino计算器代码
时间: 2023-11-28 18:42:31 浏览: 149
```C++
//定义变量
int num1, num2, answer, correct, wrong;
unsigned long startTime, endTime;
void setup() {
//初始化串口
Serial.begin(9600);
//初始化LED灯
pinMode(13, OUTPUT);
//初始化随机数种子
randomSeed(analogRead(0));
}
void loop() {
//欢迎界面
Serial.println("Welcome to the calculator!");
Serial.println("Press A to start answering questions.");
//等待用户按下A键
while (true) {
if (Serial.available() > 0) {
if (Serial.read() == 'A') {
break;
}
}
}
//开始答题
for (int i = 0; i < 10; i++) {
//生成两个随机数
num1 = random(0, 101);
num2 = random(0, 101);
//输出题目
Serial.print(num1);
Serial.print(" + ");
Serial.print(num2);
Serial.print(" = ");
//等待用户输入答案
while (true) {
if (Serial.available() > 0) {
answer = Serial.parseInt();
if (Serial.read() == 'D') {
break;
}
}
}
//判断答案是否正确
if (answer == num1 + num2) {
//正确
digitalWrite(13, HIGH);
Serial.println("Great!");
delay(2000);
digitalWrite(13, LOW);
correct++;
} else {
//错误
digitalWrite(13, HIGH);
Serial.println("Losing");
delay(2000);
digitalWrite(13, LOW);
wrong++;
}
}
//本轮回答结束,显示结果
Serial.print("Correct: ");
Serial.println(correct);
Serial.print("Wrong: ");
Serial.println(wrong);
Serial.print("Time: ");
endTime = millis();
Serial.println((endTime - startTime) / 1000);
Serial.println("Press A to start the next round.");
//等待用户按下A键
while (true) {
if (Serial.available() > 0) {
if (Serial.read() == 'A') {
break;
}
}
}
}
```
阅读全文