Using a temperature and humidity sensor to monitor a terrarium

Graphing

Lines 93-119, the graph function, starts by creating a font for the graph scale with pygame.font.SysFont, which is asks for a system font with a name matching the first argument. By passing an empty argument (""), I get the default system font. Then I draw a box over the graph area and the x and y axes.

Lines 99 and 100 create strings of the date and time for the first and last data points on the graph. Each entry in self.timestamps is a time object created when each reading was taken. Lines 102 and 103 render that text onto surfaces, then lines 104 and 105 plot those surfaces to the screen.

The next three for loops plot the graph scale and the temperature and humidity data points. In line 107, value is the data point currently being plotted. Then line 108 sets up a loop from 0 to 950 (the height of the graph in pixels) in steps of 86 pixels. For each trip around the loop, I render value (line 109), plot it to the screen (line 110), and if i > 0 (line 111), draw a guide line across the graph (line 112). After adding 10 to the value I'm plotting (line 113), I do it all over again until I reach the top of the graph.

The next two for loops plot the temperature (lines 114-116) and humidity (lines 117-119) data. On lines 115/118, I calculate where the point should go on the screen. The graph scale goes from 0 to 110, so first I divide the temperature or humidity value by 110 to get a proportion; then, I multiply that by the height of the graph (950) to find its vertical position. Lines 116/119 plot the points on the graph. I used pygame.draw.circle, so if I want to show fewer data points, it's easy to make the points larger.

Updating

The update function (lines 121-149) updates the entire system for one cycle. First, it reads the sensor (line 122), splits off the temperature and humidity readings separately if the read was succesful (lines 123-128), and updates the temperature and humidity minimums and maximums (lines 130-137). If the number of items exceeds 720, lines 139-141 truncate self.temperatureLog, self.humidityLog, and self.timestamps to the most recent 720 items. Lines 143 and 144 sum the temperature and humidity lists and divide by their size to get an average of the most recent stats. Finally, lines 146-149 call all of the plotting functions to redraw the rest of the display (Figure 5).

Figure 5: Data points being plotted on the graph, with the present temperature and humidity.

Buy this article as PDF

Express-Checkout as PDF

Pages: 7

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content