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)!

Figure 6: The finished installation. Jax the snake is hiding behind the sticks.


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.

The Author

Scott is an avid tinkerer who enjoys finding helpful Raspberry Pi projects for his friends. When he's not writing code for a Pi, he's probably in the Fort Worth Museum of Science and History's Noble Planetarium, where he is the Assistant Manager.

Buy this article as PDF

Express-Checkout as PDF

Pages: 7

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content