實驗現象
在4 * 4鍵盤輸入簡單的數學運算,如加法、減法、乘法和除法,實時在串口監視器顯示答案。
實驗準備
arduino主板-1
麪包板-1
數據線-1
4 * 4鍵盤-1
跳線若干
連接電路
圖1 44鍵盤8個引腳連接arduino板
除數字按鈕外,其他按鈕的作用如下:
'A’用於加法
'B’用於減法
'C’用於清零
'D’用於除法
''用於乘法
實物連接圖
實驗完整代碼–>由於部分代碼顯示不出來,我只能分開寫了
#include<Keypad.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', 'C'},
{'*', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
// Created instances
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
boolean firstNumState = true;
String firstNum = "";
String secondNum = "";
float result = 0.0;
char operatr = ' ';
void setup() {
Serial.begin(9600);//設置串口波特率爲9600
clr();
}
void loop() {
char newKey = myKeypad.getKey();
if (newKey != NO_KEY && (newKey == '1' || newKey == '2' || newKey == '3' || newKey == '4' || newKey == '5' || newKey == '6' || newKey == '7' || newKey == '8' || newKey == '9' || newKey == '0')) {
if (firstNumState == true) {
firstNum = newKey;
Serial.print(firstNum);
}
else {
secondNum = newKey;
Serial.print(secondNum);
}
}
if (newKey != NO_KEY && (newKey == '+' || newKey == '-' || newKey == '*' || newKey == '/')) {
if (firstNumState == true) {
operatr = newKey;
firstNumState = false;
Serial.print(operatr);
}
}
if (newKey != NO_KEY && newKey == '=') {
if (operatr == '+') {
result = firstNum.toFloat() + secondNum.toFloat();
}
if (operatr == '-') {
result = firstNum.toFloat() - secondNum.toFloat();
}
if (operatr == '*') {
result = firstNum.toFloat() * secondNum.toFloat();
}
if (operatr == '/') {
result = firstNum.toFloat() / secondNum.toFloat();
}
Serial.print("=");
Serial.println(result);
firstNumState = true;
}
if (newKey != NO_KEY && newKey == 'C') {
clr();
}
}
void clr() {
firstNum = "";
secondNum = "";
result = 0;
operatr = ' ';
}
本實驗僅侷限於一位數的的簡單運算,您可與根據需求去設置多位數的運算。
int num=newKey-48;
firstNumber=firstNumber*10+num;//多位數
如下圖
實驗效果
Keypad庫文件分享
鏈接: https://pan.baidu.com/s/1oETI5uRCBW0U2204RY5mDA 提取碼: dcqw