Arduino code for esp8266-based hvac

As mentioned in the previous post, I chose to use the esp8266 for developing the hvac controller. The esp8266 is super cheap and relatively easy to use: perfect for IoT prototyping. There are a number of ways to write software for it, but I opted to use the Arduino IDE because the documentation, libraries, and community are pretty helpful. The board definitions for the esp just had to be added to the environment before any code could be uploaded to the esp. Instructions on how to do that are here:

The hvac software isn’t terribly complicated. It can be found at Basically, the esp8266 retrieves it’s state from a Rest HTTP api in json format, and turns on/off the associated pins for heater/ac/fan as dictated by the state. Every so often, it should retrieve its state again (based on the update_period variable). There are four possible states for the hvac controller to be in:

Heating (heater and fan on)
Cooling (ac and fan on)
Ventilating (fan on)
Idle (nothing on)

The heater and ac should never be on at the same time, so the software should ensure that the web api never provides an invalid state. Here is a summary of what the code does:

  1. Connect to WiFi
  2. Retrieve state from web api
  3. Verify state
  4. Execute state by turning on/off the pins for heater/ac/fan
  5. Repeat from step 2 after waiting a short period

Currently the WiFi ssid and password, as well as api url, have to be hard coded before uploading the image to the esp. In the future I intend on adding a feature access point mode. Access point mode is where the esp device hosts its own mini wifi network that the user can join from their phone or computer. Inside this network, the esp hosts a web server with a form for configuring parameters like wifi and api url. I’ll probably end up using this Arduino library somebody created called Wifi Manager:

Categories: BYU IoT Lab


Leave a Reply

Your email address will not be published. Required fields are marked *