AI视觉小车基础--2.按键读取
一、实验准备
读取按键KEY1的按下状态。如下图所示,将舵机连接在接口上。
二、实验源码
# Import Raspbot library
from Raspbot_Lib import Raspbot
import time
import sys
sys.path.append('/home/pi/software/oled_yahboom/')
from yahboom_oled import *# Create the Raspbot object bot
bot = Raspbot()
# Create an oled object
oled = Yahboom_OLED(debug=False)key_down= False
try:oled.init_oled_process() # Initialize oled processoled.clear()oled.add_line('key pressed:', 1)oled.refresh()while True:data = bot.read_data_array(0x0d, 1)state=data[0]# Print only when the key is not pressed and becomes pressedif state == 1 and not key_down:print("key pressed", state)key_down = True oled.clear()key_str=f'{state:>10}'oled.add_line('key pressed:', 1)oled.add_line(key_str, 3)oled.refresh()if state == 0 and key_down:key_down = Falseoled.clear()key_str=f'{state:>10}'oled.add_line('key pressed:', 1)oled.add_line(key_str, 3)oled.refresh()# To avoid outputting too quickly, add a short delaytime.sleep(0.05) # except KeyboardInterrupt:# Restore basic data display on screenos.system("python3 /home/pi/software/oled_yahboom/yahboom_oled.py &")print("turned off.")#Release Object
del bot
三、核心代码解析
读取按键的按下状态我们通过读取0x0d地址的数据来判断:
read_data_array(0x0d, 1)
参数解释:读取按键的状态数据
- 0x0d:按键的地址,1:读取1个字节。
- 返回值:0:代表按键未按下,1:代表按键按下。
- 源码路径:project_demo/03.Basic_car_course
四、实验现象
程序运行后,按下小车上的KEY1按键,程序出现提示如下图。