In this article, I’m going to build a simple temperature controller using the Raspberry Pi. This will use a DS18B20 temperature sensor to determine the current temperature and then use a relay to turn on/off a heater. With this set up, I should be able to keep the temperature in a room constant over a long period of time.
Background
Wine needs to be fermented at a fairly high temperature (72 degrees Fahrenheit) for a fairly long time (2-3 weeks). Since it is the middle of the winter and I like to keep my house fairly cold, the indoor temperature is not that high. So, I’m going to hook a heater up to the Raspberry Pi and hold one room of my house at the desired temperature.
Temperature Measurement
Measuring the temperature of the room with a DS18B20 temperature sensor is pretty easy, and there is already a great tutorial that covers how to do this in detail. So, if you haven’t read that, check it out. We’ll assume that you have and followed that to get a temperature sensor up and running on the Raspberry Pi.
Turning On/Off an Electrical Device
The next challenge is to turn on/off an electrical device with the Raspberry Pi. To do this, we use a relay. Since I’m a little scared of electricity, I prefer to cut an extension cord in half and wire the relay into the center. This makes the solution more reusable since I can plug anything into the extension cord and it helps with my nerves because it lets me plug the electrical device into an outlet like I’m used to.
When wiring up the relay use the circuit shown below.
I used GPIO port 11, but there are many others that will work.
Once that is wired up, you can practice turning on/off the electrical device with the following code:
This will turn on/off the relay every two seconds and print out a message to the screen stating that the device was turned on/off. Also, my relay is a bit bizarre in that sending it False turns the relay on and sending it True turns the relay off.
Putting It Together
Now all that is left is to tie the two parts of the application together into one python script:
The only new addition to that file is a small feature to turn off the heater when the program is exited. Other than that, it is a pretty straight forward merge of the two previous code snippets.
Top Comments