|
了解如何使用Ardunio UNO、4x4键盘和LCD显示屏制作自己的计算器!
在本篇文章中,您将学习如何使用4X4键盘和Arduino Uno制作Arduino计算器。该计算器将能够执行简单的数学运算,如加法、减法、乘法和除法。它也可以支持带小数点运算。
所需的组件 ● Arduino UNO开发板 ● 4x4键盘 ● 16x2 I2C LCD显示器 ● 跳线 ● Arduino IDE
电路图和说明 4X4键盘有8个引脚需要连接到从D2到D9的Arduino引脚,如下所示:
然后,按如下方式将LCD与Arduino连接:
除数字按钮外,其他按钮的作用如下: ● 'A'用于加法 ● 'B'用于减法 ● 'C'用于清零 ● 'D'用于除法 ● '*'用于乘法
完整的电路图如下。
Arduino计算器连接图。
代码解释 让我们来看看这个项目所需的代码以及每个代码段的作用。完整代码可在本文结尾处找到。
首先,您需要为键盘和I2C LCD显示添加库。使用的LCD显示屏通过I2C通信与UNO配合使用,因此使用允许Arduino上的I2C通信的wire库。然后,按照4X4键盘的引脚连接以及键盘按钮执行操作的说明进行操作。 - #include<Keypad.h>
- #include<LiquidCrystal_I2C.h>
- #include<Wire.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};
复制代码
在setup()函数中,显示屏将显示“Arduino calculator”。 - lcd.begin();
- lcd.setCursor(0, 0);
- lcd.print("Arduino Calculator");
- delay(1000);
- scrollDisplay();
- clr();
复制代码
在loop()函数中,我们首先得到按下的键然后我们需要检查按下的键是否是数字键。如果是数字,则它将存储在firstNum字符串中。 - 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 = firstNum + newKey;
- lcd.print(newKey);
- }
- else {
- secondNum = secondNum + newKey;
- lcd.print(newKey);
- }
复制代码
如果按下的键不是数字,请检查它是'+'、' - '、'/'、'*'(在键盘上,这些键是'A'、'B'、'D'、'*' )。如果它来自这些键,我们将存储稍后将使用的值。它还会将firstNum设置为false,这意味着我们现在将得到第二个数字。 现在,其他数值将存储在secondNum字符串中。 - if (newKey != NO_KEY && (newKey == '+' || newKey == '-' || newKey == '*' || newKey == '/')) {
- if (firstNumState == true) {
- operatr = newKey;
- firstNumState = false;
- lcd.setCursor(15, 0);
- lcd.print(operatr);
- lcd.setCursor(5, 1);
- }
- }
复制代码
最后,我们将其设置为如果按下的键不是来自操作键,它将检查它是否为'='。如果是这个键,那么它将对第一个和第二个数字执行存储操作并输出结果。
设置完代码后,计算器将能够执行方程式。
- 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();
- }
- lcd.clear();
- lcd.setCursor(0, 0);
- lcd.print(firstNum);
- lcd.print(operatr);
- lcd.print(secondNum);
- lcd.setCursor(0, 1);
- lcd.print("=");
- lcd.print(result);
- firstNumState = true;
- }
- And if the key will be 'C', then it will clear the display screen.
- if (newKey != NO_KEY && newKey == 'C') {
- clr();
- }
复制代码
本文使用的完整代码如下:
main.rar
(995 Bytes, 下载次数: 1011)
|