Using a temperature and humidity sensor to monitor a terrarium
PyGame Event Loop
The loop
function (lines 151-185) implements PyGame's event loop, which handles timing events, processes keypresses, and draws all of the graphics. Line 152 starts a timer and makes pygame.USEREVENT
appear in the event queue every 5,000 milliseconds (five seconds). Line 153 sets looping
to True
; the loop starts on line 154 and runs until looping
is set to False
, which happens when the user quits the program.
All events in the PyGame queue are fetched (line 155), and each is processed. If the five-second time has gone off (line 156), it's time to update everything (line 157). Then the display is flipped so all of the new data is visible (line 158).
Line 159 checks to see if the event is a key press. Pressing Q quits the program by shutting down PyGame with pygame.quit()
and then sets looping
to False
so the loop exits (lines 160-162). Pressing S (reset stats), G (reset graph), or A (reset all) initializes different variables and calls self.update()
then pygame.display.flip
to show everything again.
The last five lines now start the program coded in all the lines above. Line 188 initializes PyGame, then line 189 gets the screen surface on which to draw. Line 191 creates an instance of the logger
class and passes screen
, sensor
, and pin
, giving the logger
class everything it needs to run. Finally, log.loop()
starts the event loop to get everything going (Figure 6)!
Conclusion
In this project I used an external library to talk to a commercially available sensor. This type of integration makes including other manufacturers' hardware fast and easy. I especially thank Adafruit for allowing me to reference their library and tutorial in today's article.
Infos
- The DHTxx series on Adafruit: https://learn.adafruit.com/dht
- The Adafruit temperature/humidity sensor tutorial: https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/software-install-updated
- Code for this article: ftp://ftp.linux-magazine.com/pub/listings/raspberry-pi-geek.com/14
« Previous 1 2 3 4 Next »
Buy this article as PDF
Pages: 7
(incl. VAT)