本帖最后由 lugl4313820 于 2022-5-23 07:07 编辑
【前言】例程给了Python控制LED闪烁、检测按键的程序,结合两个案例学习综合一个按键控制例子。
【分析】LED闪灯,是循环检测是否退出的标志来维护的,我这里加入thread线程来开启。按键程序是even来检测的,如果再加入线程就会出现不能退出的现象。
【实现思路】按测键检来判断按键是否按下,然后更新延时秒数来控制LED灯闪烁的快慢。
1、初始化LED:
def __init__(self):
self.led_path = "/sys/class/leds/" # Led path
self.leds = [] # Save the led found
self.enumerate_led()
self.led_time = 0.1
self.key_sta = 1
""" enumerate all led """
def enumerate_led(self):
led_name = "user-led"
""" find led """
for filename in os.listdir(self.led_path):
if led_name in filename:
self.leds.append(os.path.join(self.led_path, filename))
if len(self.leds) == 0:
return False
"""
led sort, e.g.
/sys/class/leds/user-led0
/sys/class/leds/user-led1
/sys/class/leds/user-led2
"""
self.leds.sort()
print "find leds:"
for led in self.leds:
print led
return True
2、LED闪烁程序:
""" control led flash """
def flash_led(self):
led_num = len(self.leds)
while not KeyDevice.quit_flag:
""" Turn on leds """
for i in range(led_num):
""" Set the led brightness value to 1 to turn on the led """
ret = os.system("echo 1 > %s/brightness" % (self.leds))
if ret != 0:
print "Error: Failed to turn on %s" % self.leds
""" Keep the leds on for 500 ms """
time.sleep(self.led_time*self.key_sta)
for i in range(led_num):
""" Set the led brightness value to 0 to turn off the LED """
os.system("echo 0 > %s/brightness" % (self.leds))
""" Keep the leds off for 500 ms """
time.sleep(self.led_time*self.key_sta)
3、按键检测程序:
def open_device(self, key_dev):
try:
""" open key device, if success, return True"""
self.key_dev = evdev.InputDevice(key_dev)
return True
except Exception as e:
print e
return False
def listen_key_pressed(self):
try:
print "Please press the key to test.\n"
"""
Listen for the button to be pressed
event.value: 1: pressed; 0: released
"""
for event in self.key_dev.read_loop():
if event.type == evdev.ecodes.EV_KEY:
if event.code == evdev.ecodes.KEY_PROG1 and event.value == 1:
print "User key0 pressed!\n"
self.key_sta = 1
elif event.code == evdev.ecodes.KEY_PROG2 and event.value == 1:
print "User key1 pressed!\n"
self.key_sta = self.key_sta + 1
if self.key_sta >20:
self.key_sta = 1
except Exception as e:
if not KeyDevice.quit_flag:
print e
4、CTRL+C退出程序:
@classmethod
def stop(cls):
print "ctrl + c ..."
cls.quit_flag = True
sys.exit()
5、CTRL+C信号:
def sig_handle(signum, frame):
print "ctrl + c ..."
KeyDevice.stop()
sys.exit()
6、启动:
if __name__ == '__main__':
key_dev = "/dev/input/event0" # key deivce path
try:
""" Ctrl+c handler """
signal.signal(signal.SIGINT, sig_handle)
key_device = KeyDevice()
""" open key device """
res = key_device.open_device(key_dev)
if not res:
print "open %s failed!" % key_dev
exit(3)
t1 = threading.Thread(target=key_device.flash_led)
t1.start()
""" Listen for the button to be pressed """
key_device.listen_key_pressed()
except Exception, exc:
print exc
【实验现象】程序启动后,三个灯快速闪烁,按下按键4,灯闪得慢下来,慢到2秒一次时,再按一下又回到原来的闪烁频率。
本次实验主要学习了python 检测GPIO的输入输出控制。
【总结】python编程还是相对容易的,但是遗憾的就是event只在python2.7中支持,现象已经用习惯了python3,突然回到python2还有点不习惯,python中pip也不支持安装包,所以发挥不出来。希望官方出个如何添加包的教程。