【Arduino】基于4*4键盘制作计算器

实验现象
在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

类似文章

发表回复