上篇文章,使用BPI-Pico-RP2040 开发板,外接了4x4矩阵键盘,测试了各个按键值的显示。
本篇,来利用矩阵键盘,实现一个简易的计算器,并使用OLED作为显示屏。
最终效果如下:
简易计算器的按键功能包括:
- 数字键:0~9
- 运算符:+、-、*、/
- 求结果:=
- 清除:#
一共是16个按键,没有小数点按键。在上篇矩阵键盘程序的基础上,增加计算器相关的代码,如下:
number1 = 0.0;
number2 = 0.0;
optr = "=";
showStr = "";
def floatNumIsZero(num):
if num > -0.0001 and num < 0.0001:
return True
else:
return False
def acceptInput(key):
global number1
global number2
global optr
global showStr
if key == "0" or key == "1" or key == "2" or key == "3" or key == "4" or key == "5" or key == "6" or key == "7" or key == "8" or key == "9":
concatNumbers(key)
elif key == "+" or key == "-" or key == "*" or key == "/":
function(key)
elif key == "=":
calculate(key)
elif key == "#":
number1 = 0
number2 = 0
showStr = ""
optr = "="
else:
Serial.println("Invalid Input")
def calculate(op):
global number1
global number2
global optr
calcVal = 0.0;
if (optr == "+"):
calcVal = (number1 + number2)
elif (optr == "-"):
calcVal = (number1 - number2)
elif (optr == "*"):
calcVal = (number1 * number2)
elif (optr == "/"):
calcVal = (number1 / number2)
number1 = calcVal
number2 = 0;
print(calcVal)
def function(e):
global number1
global number2
global optr
if (floatNumIsZero(number1)):
print("num1<-num2, and num2=0")
number1 = number2
number2 = 0
elif (not floatNumIsZero(number1) and not floatNumIsZero(number2)):
print("calc mid res")
calculate(e)
optr = e
def concatNumbers(num):
global number2
if (floatNumIsZero(number2)):
number2 = eval(num)
else:
number2 = number2 * 10 + eval(num)
def do_calc(key):
global number1
global number2
global optr
global showStr
print(key)
acceptInput(key)
if (key != "#"):
showStr += key
oled.fill(0)
oled.text(showStr,1,15,20)
oled.show()
if (key == "="):
oled.text(str(number1),1,31,20)
oled.show()
并修改主函数,在检测到按键按下后,调用do_calc函数
while True:
for i, row in enumerate(row_list):
for temp in row_list:
temp.value(0)
row.value(1)
time.sleep_ms(10)
for j, col in enumerate(col_list):
if col.value() == 1:
print("按键: {} 被按下".format(names[i][j]))
do_calc(names[i][j])
time.sleep(0.1)
演示视频
BPI-Pico-RP2040-简易计算器
|