我试图从键盘读取两个用户输入的数字到发现板上。我有代码用于读取第一个数字,但出于某种原因它遇到相同的键盘();函数第二次它似乎没有调用函数允许输入而不是它跳过扫描并打印它下面的行,如果你按下按钮重新开始它是程序选择的随机,可能导致这种情况的任何想法。我在mbeds在线编译Ide。下面是代码。
#include <iostream>
#include "mbed.h"
DigitalIn columns[3] = {PB_6, PB_7, PD_0}; // Columns for digital input
DigitalOut rows[4] = {PA_5, PA_1, PA_2, PA_3}; // rows for digital output
DigitalIn startButton(USER_BUTTON);
DigitalOut led1(LED1); // reference LED
int numpad[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {-2, 0, -1}}; // keypad
int Total();
int Keypad();
int c = 0;
int Read;
int Num1 = 0;
int SelectOp();
int Oper;
int main() {
while (1) {
if (startButton == 1) {
printf("%s\n\rInput First Number\n\r");
wait(.5);
Keypad();
int First = Num1;
Num1 = 0;
printf("%s\n\r Your first number is ");
printf("%i", First);
printf("%s\n\r Input your second number\n\r");
wait(.5);
Keypad(); // this seems to be getting skipped
int Second = Num1;
Num1 = 0;
printf("%s\n\r Your Second number is ");
printf("%i", Second);
printf("%s\n\rSelect Operator: 1(+), 2(-), 3(*), 4(/)");
Keypad();
Oper = Num1;
}
}
}
int Keypad() {
columns[0].mode(PullUp);
columns[1].mode(PullUp);
columns[2].mode(PullUp);
while (1) {
if (Read == -1) {
return Num1;
}
for (int i = 0; i < 4; i++) {
rows[0] = 1;
rows[1] = 1;
rows[2] = 1;
rows[3] = 1;
rows[i] = 0;
wait(0.01);
for (int j = 0; j < 3; j++) {
if (columns[j] == 0) {
Read = numpad[i][j];
Total();
c++;
if (c == 5) {
c = 0;
}
wait(0.005);
while (columns[j] == 0)
;
}
}
}
}
}
int Total() {
if (Read >= 0) {
Num1 *= 10;
Num1 += Read;
printf("%i\n\r", Num1);
} else {
return Num1;
}
return Num1;
}
当Read
在通过Keypad()的第一个循环中设置为-1时,当你再次输入Keypad()
时它仍为-1,因此立即返回。
使用一些空间来回应@Scheff根据预期生命周期确定变量范围的重要性,从而尽可能地减少全局变量。