In this article, I outline my development of a smart thermostat using the Raspberry Pi single-board computer as the controller, along with a Pi Plate expansion board. The thermostat interface is web-based, allowing remote control from any device with a standard browser such as a computer, phone, or tablet. It can also be operated through external applications via TCP/IP messages.
Please note that I am only sharing my experience with the Raspberry Pi thermostat design as an educational project. This solution should not be copied verbatim, as it was not intended as a finished, commercial product. Readers are advised to take the ideas presented here to inform their own custom smart thermostat designs. As all may not fully understand the technical details, implementation is not recommended without a strong comprehension of the system. Safety should also be considered, as HVAC equipment requires caution. I cannot be held responsible for any issues resulting from adopting this prototype’s aspects. All attempts to recreate or modify this thermostat are undertaken solely at the user’s own risk.
BACKGROUND
The concept of having a high-tech thermostat to manage my house’s heating and cooling system has always been on my mind. Certainly, there are smart thermostats that can be purchased. However, they are costly and do not offer the features I desire. Moreover, where is the enjoyment in purchasing it?
The introduction of the Raspberry Pi board unlocked a fresh realm and enabled the creation of complex thermostat features through streamlined programming. It is possible to use any microcomputer platform such as PIC or Arduino, but developing an Ethernet stack, a web server, and plotting functions on this hardware is not a simple task. The Raspberry Pi, running Linux as a full computer, simplifies the development of the above task because it has built-in support for those features.
IMPLEMENTATION
The idea behind this smart thermostat project is to provide the same basic features as a regular programmable thermostat to begin with, namely:
- Present measurement and display of temperature and humidity.
- Seven-day schedule for both heating and cooling functions.
- Interface with 4 wires (Common, Heat, Cool, Blower),
- Manual program bypass (with automatic return to program).
- Clock that is included as part of a device or system.
This implementation adds the following nice features, which differentiate this from a regular thermostat:
- Web interface that is optimized for touchscreens, used for both control and programming rather than traditional LCD screens and buttons.
- Programming the blower to recirculate air at set times every day for a week.
- Displaying outdoor temperature using a query to the weather service’s RSS feed.
- Capability to regulate the thermostat by sending text commands through TCP/IP socket messages. I utilize this to manage my Asterisk PBX from my home phone.
- PhotoMOS solid-state relays are used in place of traditional dry mechanical relays.
- Authentication on the web involves the use of both a user ID and a password.
- Temperature and cycling on/off patterns are plotted daily in. PDF file or document. PNG file format, with a backlog of seven days.
- A discretionary Watchdog feature involving an independent autonomous PIC microcontroller. Prioritize safety above all else!
The Software Platform
I utilized Raspbian, a free operating system on the Pi, which is optimized for Raspberry Pi hardware and based on Debian. I chose to utilize Python 2.7 scripts for programming this thermostat. Most of the necessary Python libraries come pre-installed with the Raspbian Linux distribution. Here are the Python libraries I utilize to enhance the Python experience on Raspbian:
- Flask is utilized as the web server. It is less heavy than Apache and it smoothly integrates with Python. To set up Flask on the Pi, adhere to these guidelines.
- RPIO to control the Raspberry Pi General Purpose Input Output (GPIO) pins. It is an improved version of RPi.GPIO. It also allows to manage interrupts from I/O pins and TCP/IP Socket within Python with just a few commands. Follow these instructions to install RPIO on the Pi.
- Pychart to generate the temperature and activity plots. To me, this seems like the simplest yet quite flexible package for generating charts out of raw data. Type “sudo apt-get install python-pychart” to install Pychart.
- Feedparser as the RSS client engine. This is optional, but it allows to retrieval and display of weather data, such as outdoor temperature, sourced from reliable weather services. Follow these instructions to install Feedparser on the Pi.
The remaining coding is primarily in standard HTML, with some Javascript included as needed.
Below is the Python and HTML source code for my RasTherm project. I trust that it will inspire you with some great ideas!
The Hardware Platform
To build this smart thermostat project, you will need a Raspberry Pi single-board computer. I recommend the Raspberry Pi 3B or higher for its processing power and RAM (at least 256MB). An 8GB or larger microSD card (Class 10 or faster) is needed to hold the operating system and software. An enclosure protects the electronics, though the cheapest options around $5 will suffice. A 5V micro USB power supply and cable provide power to the Raspberry Pi.
For interfacing electronics to the Raspberry Pi, I used an add-on prototyping board called a Pi Plate, mounted directly above it. With its space, most small circuits will fit. Similar cheaper boards are available on eBay.
A Sensirion SHT10 temperature/humidity sensor measures conditions. It’s inexpensive, uses simple 2-wire communication, and works reliably over longer cable runs up to 9 meters in my tests. I mounted the small sensor on an adapter board for easier cabling connection.
As switching elements, I selected AQV21x solid-state relays instead of noisier mechanical relays. They require only 2-3mA to operate and are reliable alternatives to more power-hungry options.
The circuit prototyped on the Pi Plate board uses 0805-sized surface mount resistors and capacitors for their compact size. Red wire-wrap wire connects components, while yellow and black stranded wire connects to relay terminals.
An overview circuit diagram shows how all elements integrate on the Pi Plate extension board mounted atop the Raspberry Pi computer board to form this smart thermostat prototype.
The Watchdog
Additionally, included in the hardware is an optional firmware watchdog. If you are similar to me and do not fully trust the Pi, you may appreciate the concept of having a separate watchdog to reset the Pi if it crashes or freezes. Don’t forget, this thermostat can regulate a strong furnace… I employed the Microchip PIC12F683 microcontroller with 8 pins as the watchdog. I utilized BoostC for coding the PIC micro firmware to execute the watchdog functions. If any abnormalities are detected, a reset will be triggered on the Pi reset line (connector P6).
- The Raspberry Pi ceases to alternate the state of a GPIO pin every second, suggesting that either the software or the operating system has failed. The watchdog will be reset if there is no pulse activity for 120 seconds. This allows adequate time for the Pi to restart without causing an unnecessary hardware reset.
- Typically, the heat relay is not activated for over 120 minutes, as it is an uncommon occurrence.
- The heat and cool relays are activated at the same time, which is an unusual occurrence.
The watchdog circuit includes a red LED, which lights up to show when at least one Pi reset has been conducted. I have included a switch that can reset/disable the watchdog, clearing the lit LED and preventing the watchdog from activating. This is beneficial in turning off the watchdog while developing.
This zip file contains the source code file for the ANSI-C watchdog and the Intel Hex file for programming the PIC microcontroller.
Long Sensor Cable Length
It is essential to be able to place the temperature/humidity sensor at a distance greater than a few centimeters from the Raspberry Pi. Regrettably, the CMOS line drivers on both the SHT10 sensor and the Pi are not intended for driving long cables with low controlled impedance. However, I managed to effectively utilize the sensor located at the end of a 19-meter cable.
This is the way I accomplished it in the Python program. I set the clock speed to 1 millisecond, which means the data rate is quite sluggish. It could be even more sluggish and it would still be acceptable. What is the frequency at which we require a temperature measurement? Currently, temperature and humidity are being read every 4 seconds with a new update. I am utilizing the checksum function and refusing any incorrect data. The web page will display dashes for temperature and humidity readings if the data received is invalid, while still preserving the previous data.
Careful cabling is necessary for it to function properly. Keep in mind that while the data rate is low, it is important to also pay attention to the precise clock pulse edges.
Here is what you need to do.
- Utilize CAT5 or a superior Ethernet cable. This cable requires the twisted pair functionality.
- Use one twisted pair for the clock signal, with the other wire of the pair being grounded.
- Another set of wires can be used for the data and Vcc signals. These are not as crucial.
- Insert a 100nF decoupling capacitor at the sensor terminal, connecting Vcc and ground.
- Place a 1 Kilo-ohm resistor at the Raspberry Pi side in conjunction with the clock and data cables in a series. These resistors control the current in the CMOS drivers, causing the signal edges to be slowed down and reflections to be decreased. If the sensor does not have these series resistors, it will not function properly when connected to a long cable.
RasTherm website Access
By analyzing the Python code, the reader will understand the situation. Entering the specified Flask web server IP address and port (in this case: 192.168.0.20:8888) in your browser will result in a prompt for a user ID and password. By inputting the identical username and password specified in the Python code, the main window of RasTherm will appear. If you choose to, you can access the main control window by going straight to 192.168.0.20:8888/popup_main.html.
The website consists of three pages. I have programmed the main page to appear as a popup window. To my preference, this performed more efficiently on a desktop computer rather than having the interface in a tab similar to any other window. The other two pages include a Program change page, allowing adjustments to heat, cool, and fan settings based on day and time. The third page, in conclusion, is a debug page that can only be accessed with a unique password. This is the place where only the boss might choose to visit. Within that location, you can generate temperature graphs, restart or power off the Pi, and modify some control settings quickly.
Main Window Fields
The primary window is split into three sections. The status bar is located at the top. It provides updates on the system’s status through text. The middle band controls the temperature setting and shows the current temperature and humidity. Moving windmill symbols also indicate the current operation of the heater or air conditioner. The bottom row holds the navigation buttons. They feature a toggle function. Upon enlargement, they reveal that the function is operational. In this area, there is also a button for opening the thermostat program editing window. In the end, there is a debug button available to access the debug window, where temperature plots can be generated and a Raspberry Pi restart or shutdown can be initiated. The debug window requires a separate user ID and password for protection. That window should only be accessed by you, the developer.
Field Refresh Delay
The main window consists entirely of iframe fields that are refreshed at intervals defined in their HTML files. A short pause could occur between a system operation and the accompanying view on the primary screen. This is a fundamental aspect of HTML rendering refresh, initiated by the browser rather than the server. Put simply, the web server can update a field in response to user actions like pressing a button or selecting from a dropdown menu. However, if there is no activity, the only option is to automatically reload a simple HTML page at set intervals. The time can be adjusted, but an equilibrium between update delay and network congestion needs to be achieved.
30-Second Change Delay
A 30-second delay occurs when there is a change in the set temperature or mode (heat, cool). This is performed to safeguard the HVAC system in the event of a user making a mistake in their setting. This offers the user an opportunity to rectify the error before the system is updated.
Program Override
A brief explanation is required for the override state. When the system is following the temperature setting schedule in programmed mode, the user can easily change the current setting by entering a new temperature. The system will remain in a program-override mode and will maintain the manually set temperature until the next scheduled entry is reached. An instance of this is when you are feeling chilly and desire some extra warmth in the daytime. Once it gets dark, the system will align with the night program schedule and adjust the temperature to the next programmed level, turning off the override mode.
IP Socket Control
I have added the functionality to manage and ask questions to RasTherm through an IP link. The Socket module, which comes pre-installed in Python, is the most popular method for accomplishing this. Using the RPIO package makes handling socket interrupts easy. Every time data is received through a socket packet, certain Python code is executed. The function socket_callback() in my script accomplishes that. For instance, a different python script from a distance could send a text prompt like “get_current_temp” or “21.5”, with RasTherm then providing the present temperature or an acknowledgment that the command was received. I utilize this function to manage RasTherm using my home telephone system, specifically an Asterisk IP phone PBX. I have linked DTMF keypad inputs to different RasTherm actions. I utilize Text-To-Speech for reciting temperatures and statuses.
Adjustable Parameters
On the Debug page of the web interface, there are two parameters that can be adjusted. The terms are “Threshold for Temperature On/Off Cycle” and “Correction for Temperature Sensor”. The On/Off Threshold for temperature cycling is the difference between the set temperature that triggers the thermostat to turn on and off the HVAC system. One instance is when a fixed heating temperature of 21.0 °C and a margin of 0.5 are set, the HVAC system will initiate heating at 20.5 °C and cease at 21.5 °C. The Temperature Sensor Correction is another factor to consider. It is just a shift in temperature to be added to the temperature measurements. If the temperature sensor reading is 22.0 °C and the Temperature Sensor Correction is -1.0, the true ambient thermostat temperature will be 21.0 °C.
Launch RasTherm at Raspberry Pi Boot Up Time
In order to make RasTherm automatically launch when the Raspberry Pi boots up, you can add the following entries to the /etc/rc.local file, just below the header comments (the “&” character is important; it launches the script in the background):
# Launch RasTherm at startup
cd /home/pi/your_RasTherm_project_directory
sudo python therm_main.py &
- Features that were not developed, but could be easily added:
- Automated Heat-Cool transition function (I like to manually choose between A/C or furnace mode).
- Real-Time_Clock with battery backup can be found pre-assembled online (internet connection not necessary).
- A switch can be used to disconnect the +3.3V supply to the solid stare relays, preventing RasTherm from controlling the HVAC system while keeping the Raspberry Pi powered on. This is achievable by using an external switch. Simply disconnect the Common (C) wire to complete the task.
- Simple option to choose between Fahrenheit and Celsius temperature measurements. At the moment, Celsius is programmed in a fixed way.
- Support for websites in multiple languages. At present, only French is in place.
CLOSING COMMENTS
To increase system availability and robustness, I suggest you follow these recommendations.
- Utilize a UPS to power your Raspberry Pi’s AC adapter without any interruptions.
- Keep your old thermostat connected to RasTherm, but make sure it is turned off to avoid any interference with RasTherm. If RasTherm becomes unavailable for an extended period of time, you can switch back to your previous thermostat.
- Set up the ‘fake-hwclock’ script on the Pi. This gets the most recent date and time when the device was last switched on, avoiding the need to reset to 1970. Use the command “apt-get install fake-hwclock” to add the package.
- Carry out routine reboots for Raspberry Pi. To guarantee system stability, it is advisable to plan a regular Pi reboot, such as once weekly during nighttime. The Cron scheduling tool is already available in Linux to accomplish this task. Invoke the Cron editor by using the command “sudo crontab -e”. Add the following entry for a reboot every Wednesday at 3:00 am:
- 0 3 * * 3 /home/your_username/your_script_location/reboot.sh
The reboot.sh bash script invoked must exist at the provided location. The script will simply contain the reboot command - #!/bin/bash
sudo shutdown -r now
The source code and HTML code contains French web labels as my main language is French. Spend a few minutes of translation work in the source code and HTML pages and you will have an interface that speaks to you in your language…
For mroe detail: RasTherm – A Smart Thermostat built on the Raspberry Pi