上篇文章,使用BPI-Pico-RP2040 开发板,外接了4x4矩阵键盘,测试了各个按键值的显示。
本篇,来利用矩阵键盘,实现一个简易的计算器,并使用OLED作为显示屏。
最终效果如下:
简易计算器的按键功能包括:
一共是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;
#按照上次的运算符将两数的临时计算结果赋值给number1,并将number2清0
#如果是等号进来的,则计算结果在number1中
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
#输入数字后,又输入了运算符,则将number2的值给number1,并将number2清0
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
#初始数字先赋值给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)
演示视频
更多回帖