After messing around with the SenseHAT for the Raspberry Pi (a Model 3B in my case) and testing the LEDs and sensors, I wanted to try out the included joystick as well. Naively going after the "getting-started"-documents and API references, I tried the following (Python, of course):
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from time import sleep from sense_hat import SenseHat # SenseHAT API def stick_data(sense): text_col = [255, 127, 0] # Set local text colour (orange-ish) while True: # Main joystick event loop for event in sense.stick.get_events(): # event: Joystick "pressed" in any Direction if event.action == "pressed": # check which direction: if event.direction == "up": # get data, round it hum = round(sense.get_humidity(), 2) # scrolling message on SenseHat LED matrix sense.show_message("Humidity(%): " + \ str(hum), text_colour=text_col) elif event.direction == "down": prs = round(sense.get_pressure(), 2) sense.show_message("Pressure(mbar): " + \ str(prs), text_colour=text_col) elif event.direction == "left": temph = round(sense.get_temperature_from_humidity(), 2) sense.show_message("Temp.Hum.(C): " + \ str(temph), text_colour=text_col) elif event.direction == "right": tempp = round(sense.get_temperature_from_pressure(), 2) sense.show_message("Prs.Temp.(C): " + \ str(tempp), text_colour=text_col) elif event.direction == "middle": sense.show_message("Middle Joystick button pressed", \ text_colour=text_col) sleep(1) sense.clear() return
Now, this works just fine when called in a script. However, I was asking myself if this really HAS to draw near-100% cpu loads (when activated via threading, it's more like 130%-140%).
The main culprit is the infinite while-loop, of course(*), but I always assumed there would be some built-in throttling of such loops. But here, it seems the RPi just calls that loop as fast as it possibly can; therefore, some "manual" throttling seems to be required, I guess?
Could somebody kindly drop a hint on how to do such event-handling loop in an economic way? Any help is greatly appreciated!
(*) I monitored cpu load while testing the script and while the script was busy displaying the messages, CPU load dropped way down, so I'm fairly certain the infinte loop is the culprit.