ESP32

ESP32/ESP8266 Thermostat Web Server – Control Output Based on Temperature

In this project, you’ll build an ESP32 / ESP8266 Thermostat Web Server with an input field to set a temperature threshold value. This allows you to automatically control an output based on the current temperature reading. The output will be set to on if the temperature is above or set to off if it’s below the threshold – this can be used to build a simple thermostat project.

ESP32 or ESP8266 Control Output Based on Temperature Threshold build a Thermostat Web Server

As an example, we’ll read the temperature using a DS18B20 temperature sensor. You can use any other temperature sensor like DHT11/DHT22, BME280 or LM35.

To better understand how this project works, we recommend reading these tutorials:

Project Overview

The following image shows a high-level overview of the project we’ll build.

ESP32 ESP8266 Web Server with Temperature Threshold Value Project Overview
  • The ESP32/ESP8266 hosts a web server that shows the latest temperature readings from a DS18B20 temperature sensor.
  • There’s an input field to set up a temperature threshold value. When the temperature goes above the threshold, an output will be automatically turned on. You can invert this logic depending on your project application.
  • When the temperature goes below the threshold, the output will be turned off.
  • The system can be activated or deactivated through the web server. If you choose to deactivate the system, the output will keep its state, no matter the temperature value.

The following image shows how the web server page looks like.

ESP32/ESP8266 Temperature Web Server with Threshold for Automatic Output Control

Prerequisites

Make sure you check each of the following prerequisites before proceeding with this project.

1. ESP32 or ESP8266 Add-on Arduino IDE

This project is compatible with both the ESP32 and ESP8266 boards. We’ll program these boards using Arduino IDE, so make sure you have the necessary add-ons installed:

2. Async Web Server Libraries

To build the web server you need to install the following libraries:

You can install those libraries in the Arduino IDE Library Manager. Go to Sketch Include Library > Manage Libraries and search for the libraries’ names.

3. Parts Required

ESP32 vs ESP8266 Development Boards

To follow this tutorial you need the following parts:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

header-200.png?w=828&quality=100&strip=all&ssl=1

Schematic Diagram

Before proceeding, wire the DS18B20 temperature sensor to your board.

ESP32 with DS18B20 and LED

If you’re using an ESP32, wire the DS18B20 temperature sensor as shown in the following schematic diagram, with the data pin connected to GPIO 4.

Wiring Schematic diagram with DS18B20 temperature sensor connected to ESP32 board

ESP8266 with DS18B20 and LED

If you’re using an ESP8266, wire the DS18B20 temperature sensor as shown in the following schematic diagram, with the data pin connected to GPIO 4 (D2).

Wiring Schematic diagram with DS18B20 temperature sensor connected to ESP8266 board (NodeMCU)

Code – Thermostat Web Server with Threshold Input

Copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you. You need to insert your network credentials and your default threshold value.

/*********
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-thermostat-web-server/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/

#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Default Threshold Temperature Value
String inputMessage = "25.0";
String lastTemperature;
String enableArmChecked = "checked";
String inputMessage2 = "true";

// HTML web page to handle 2 input fields (threshold_input, enable_arm_input)
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
  <title>Temperature Threshold Output Control</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  </head><body>
  <h2>DS18B20 Temperature</h2> 
  <h3>%TEMPERATURE% &deg;C</h3>
  <h2>ESP Arm Trigger</h2>
  <form action="/get">
    Temperature Threshold <input type="number" step="0.1" name="threshold_input" value="%THRESHOLD%" required><br>
    Arm Trigger <input type="checkbox" name="enable_arm_input" value="true" %ENABLE_ARM_INPUT%><br><br>
    <input type="submit" value="Submit">
  </form>
</body></html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

AsyncWebServer server(80);

// Replaces placeholder with DS18B20 values
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return lastTemperature;
  }
  else if(var == "THRESHOLD"){
    return inputMessage;
  }
  else if(var == "ENABLE_ARM_INPUT"){
    return enableArmChecked;
  }
  return String();
}

// Flag variable to keep track if triggers was activated or not
bool triggerActive = false;

const char* PARAM_INPUT_1 = "threshold_input";
const char* PARAM_INPUT_2 = "enable_arm_input";

// Interval between sensor readings. Learn more about ESP32 timers: https://RandomNerdTutorials.com/esp32-pir-motion-sensor-interrupts-timers/
unsigned long previousMillis = 0;     
const long interval = 5000;    

// GPIO where the output is connected to
const int output = 2;

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;     
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    return;
  }
  Serial.println();
  Serial.print("ESP IP Address: http://");
  Serial.println(WiFi.localIP());
  
  pinMode(output, OUTPUT);
  digitalWrite(output, LOW);
  
  // Start the DS18B20 sensor
  sensors.begin();
  
  // Send web page to client
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", index_html, processor);
  });

  // Receive an HTTP GET request at <ESP_IP>/get?threshold_input=<inputMessage>&enable_arm_input=<inputMessage2>
  server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
    // GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage>
    if (request->hasParam(PARAM_INPUT_1)) {
      inputMessage = request->getParam(PARAM_INPUT_1)->value();
      // GET enable_arm_input value on <ESP_IP>/get?enable_arm_input=<inputMessage2>
      if (request->hasParam(PARAM_INPUT_2)) {
        inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
        enableArmChecked = "checked";
      }
      else {
        inputMessage2 = "false";
        enableArmChecked = "";
      }
    }
    Serial.println(inputMessage);
    Serial.println(inputMessage2);
    request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
  });
  server.onNotFound(notFound);
  server.begin();
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    sensors.requestTemperatures();
    // Temperature in Celsius degrees 
    float temperature = sensors.getTempCByIndex(0);
    Serial.print(temperature);
    Serial.println(" *C");
    
    // Temperature in Fahrenheit degrees
    /*float temperature = sensors.getTempFByIndex(0);
    Serial.print(temperature);
    Serial.println(" *F");*/
    
    lastTemperature = String(temperature);
    
    // Check if temperature is above threshold and if it needs to trigger output
    if(temperature > inputMessage.toFloat() && inputMessage2 == "true" && !triggerActive){
      String message = String("Temperature above threshold. Current temperature: ") + 
                            String(temperature) + String("C");
      Serial.println(message);
      triggerActive = true;
      digitalWrite(output, HIGH);
    }
    // Check if temperature is below threshold and if it needs to trigger output
    else if((temperature < inputMessage.toFloat()) && inputMessage2 == "true" && triggerActive) {
      String message = String("Temperature below threshold. Current temperature: ") + 
                            String(temperature) + String(" C");
      Serial.println(message);
      triggerActive = false;
      digitalWrite(output, LOW);
    }
  }
}

View raw code

How the Code Works

Continue reading to learn how the code works, or skip to the Demonstration section.

Libraries

Start by importing the required libraries. The WiFi (or ESP8266WiFi), AsyncTCP (or ESPAsyncTCP) and ESPAsyncWebServer are required to build the web server.

The OneWire and DallasTemperature are required to interface with the DS18B20.

The code automatically imports the right libraries accordingly to the selected board (ESP32 or ESP8266).

#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>

Network Credentials

Insert your network credentials in the following lines:

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Default Temperature Threshold Value

In the inputMessage variable insert your default temperature threshold value. We’re setting it to 25.0, but you can set it yo any other value.

String inputMessage = "25.0";

Auxiliar Variables

The lastTemperature variable will hold the latest temperature reading to be compared with the threshold value.

String lastTemperature;

The enableArmChecked variable will tell us whether the checkbox to automatically control the output is checked or not.

String enableArmChecked = "checked";

In case it’s checked, the value saved on the inputMessage2 should be set to true.

String inputMessage2 = "true";

HTML Text

Then, we have some basic HTML text to build a page with two input fields: a temperature threshold input field and a checkbox to enable or disable automatically controlling the output.

The web page also displays the latest temperature reading from the DS18B20 temperature sensor.

The following lines display the temperature:

<h2>DS18B20 Temperature</h2> 
<h3>%TEMPERATURE% &deg;C</h3>

The %TEMPERATURE% is a placeholder that will be replaced by the actual temperature value when the ESP32/ESP8266 serves the page.

Then, we have a form with two input fields and a “Submit” button. When the user types some data and clicks the “Submit” button, those values are sent to the ESP to update the variables.

<form action="/get">
  Temperature Threshold <input type="number" step="0.1" name="threshold_input" value="%THRESHOLD%" required><br>
  Arm Trigger <input type="checkbox" name="enable_arm_input" value="true" %ENABLE_ARM_INPUT%><br><br>
  <input type="submit" value="Submit">
</form>

The first input field is of type number and the second input field is a checkbox. To learn more about input fields, we recommend taking a look at following resources of the w3schools website:

The action attribute of the form specifies where to send the data inserted on the form after pressing submit. In this case, it makes an HTTP GET request to:

/get?threshold_input=value&enable_arm_input=value

The value refers to the text you enter in each of the input fields. To learn more about handling input fields with the ESP32/ESP8266, read: Input Data on HTML Form ESP32/ESP8266 Web Server using Arduino IDE.

processor()

The processor() function replaces all placeholders in the HTML text with the actual values.

  • %TEMPERATURE% » lastTemperature
  • %THRESHOLD% » inputMessage
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return lastTemperature;
  }
  else if(var == "THRESHOLD"){
    return inputMessage;
  }
  else if(var == "ENABLE_ARM_INPUT"){
    return enableArmChecked;
  }
  return String();
}

Input Field Parameters

The following variables will be used to check whether we’ve received an HTTP GET request from those input fields and save the values into variables accordingly.

const char* PARAM_INPUT_1 = "threshold_input";
const char* PARAM_INPUT_2 = "enable_arm_input";

Interval Between Readings

Every 5000 milliseconds (5 seconds), we’ll get a new temperature reading from the DS18B20 temperature sensor and compare it with the threshold value. To keep track of the time, we use timers.

Change the interval variable if you want to change the time between each sensor reading.

unsigned long previousMillis = 0;
const long interval = 5000;

GPIO Output

In this example, we’ll control GPIO 2. This GPIO is connected to the ESP32 and ESP8266 built-in LED, so it allows us to easily check if the project is working as expected. You can control any other output and for many applications you’ll want to control a relay module.

// GPIO where the output is connected to
const int output = 2;

DS18B20 Temperature Sensor Init

Initialize the DS18B20 temperature sensor.

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

To learn more about interfacing the DS18B20 temperature sensor with the ESP board, read:

setup()

In the setup(), connect to Wi-Fi in station mode and print the ESP IP address:

Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
  Serial.println("WiFi Failed!");
  return;
}
Serial.println();
Serial.print("ESP IP Address: http://");
Serial.println(WiFi.localIP());

Set GPIO 2 as an output and set it to LOW when the ESP first starts.

pinMode(output, OUTPUT);
digitalWrite(output, LOW);

Initialize the DS18B20 temperature sensor:

sensors.begin();

Handle Web Server

Then, define what happens when the ESP32 or ESP8266 receives HTTP requests. When we get a request on the root / url, send the HTML text with the processor (so that the placeholders are replaced with the latest values).

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/html", index_html, processor);
});

When, a form is submitted, the ESP receives a request on the following URL:

<ESP_IP>/get?threshold_input=<inputMessage>&enable_arm_input=<inputMessage2>

So, we check whether the request contains input parameters, and save those parameters into variables:

server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
  // GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage>
  if (request->hasParam(PARAM_INPUT_1)) {
    inputMessage = request->getParam(PARAM_INPUT_1)->value();
    // GET enable_arm_input value on <ESP_IP>/get?enable_arm_input=<inputMessage2>
    if (request->hasParam(PARAM_INPUT_2)) {
      inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
      enableArmChecked = "checked";
    }
    else {
      inputMessage2 = "false";
      enableArmChecked = "";
    }
  }

This is the part of the code where the variables will be replaced with the values submitted on the form. The inputMessage variable saves the temperature threshold value and the inputMessage2 saves whether the checkbox is ticked or not (if we should control the GPIO or not).

After submitting the values on the form, it displays a new page saying the request was successfully sent to your board an with a link to return to the homepage.

request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
});

Finally, start the server:

server.begin();

loop()

In the loop(), we use timers to get new temperature readings every 5 seconds.

unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
  previousMillis = currentMillis;
  sensors.requestTemperatures();
  // Temperature in Celsius degrees 
  float temperature = sensors.getTempCByIndex(0);
  Serial.print(temperature);
  Serial.println(" *C");
    
  // Temperature in Fahrenheit degrees
  /*float temperature = sensors.getTempFByIndex(0);
  Serial.print(temperature);
  Serial.println(" *F");*/
  
  lastTemperature = String(temperature);

After getting a new temperature reading, we check whether it is above or below the threshold and turn the output on or off accordingly.

In this example, we set the output state to HIGH, if all these conditions are met:

  • The current temperature is above the threshold;
  • Automatic output control is enabled (the checkbox is ticked on the web page);
  • If the output hasn’t been triggered yet.
// Check if temperature is above threshold and if it needs to trigger output
if(temperature > inputMessage.toFloat() && inputMessage2 == "true" && !triggerActive){
  String message = String("Temperature above threshold. Current temperature: ") 
                   + String(temperature) + String("C");
  Serial.println(message);
  triggerActive = true;
  digitalWrite(output, HIGH);
}

Then, if the temperature goes below the threshold, set the output to LOW.

else if((temperature < inputMessage.toFloat()) && inputMessage2 == "true" && triggerActive) {
  String message = String("Temperature below threshold. Current temperature: ") 
                   + String(temperature) + String(" C");
  Serial.println(message);
  triggerActive = false;
  digitalWrite(output, LOW);
}

Depending on your application, you may want to change the output to LOW, when the temperature is above the threshold and to HIGH when the output is below the threshold.

Demonstration – ESP Thermostat

Upload the code to your ESP board (with the DS18B20 wired to your ESP32 or ESP8266 board).

Open the Serial Monitor at a baud rate of 115200 and press the on-board RST/EN button. The ESP will print its IP address and it will start displaying new temperature values every 5 seconds.

ESP32 ESP8266 Temperature threshold Arduino IDE Serial Monitor

Open a browser and type the ESP IP address. A similar web page should load with the default values (defined in your code):

ESP32 ESP8266 Temperature threshold trigger web server Arduino IDE

If the arm trigger is enabled (checkbox ticked) and if the temperature goes above the threshold, the LED should turn on (output is set to HIGH).

ESP32 ESP8266 Control Output when Temperature is above threshold web server

After that, if the temperature goes below the threshold, the output will turn off.

ESP32 ESP8266 Control Output when Temperature is below threshold web server

You can use the web page input fields to change the threshold value or to arm and disarm controlling the output. For any change to take effect, you just need to press the “Submit” button.

At the same time, you should get the new input fields in the Serial Monitor.

ESP32 ESP8266 Change temperature threshold on web server

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now