This post was last edited by lugl4313820 on 2022-5-23 07:07
[Preface] The example gives Python programs to control LED flashing and detect key presses, combining two case studies to synthesize a key control example.
[Analysis] The LED flashing light is maintained by a loop to detect whether to exit. I add a thread here to start it. The button program is detected by even. If another thread is added, the program will not be able to exit.
[Implementation ideas] Press the key test to determine whether the key is pressed, and then update the delay seconds to control the flashing speed of the LED light.
1. Initialize 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 flashing program:
""" 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. Key detection procedure:
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 to exit the program:
@classmethod
def stop(cls):
print "ctrl + c ..."
cls.quit_flag = True
sys.exit()
5. CTRL+C signal:
def sig_handle(signum, frame):
print "ctrl + c ..."
KeyDevice.stop()
sys.exit()
6. Startup:
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
[Experimental phenomenon] After the program is started, the three lights flash quickly. Press button 4 and the lights flash slower. When it is as slow as once every 2 seconds, press it again and the lights return to the original flashing frequency.
This experiment mainly learned python to detect GPIO input and output control.
[Summary] Python programming is relatively easy, but unfortunately events are only supported in Python 2.7. I'm used to Python 3, so it's a bit strange to go back to Python 2. Python pip doesn't support package installation, so I can't use it to my advantage. I hope the official will release a tutorial on how to add packages.