ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)

This is a in-depth guide for the DS18B20 temperature sensor with ESP8266 using Arduino IDE. We’ll cover how to wire the sensor, install the required libraries, and write the code to get the sensor readings from one and multiple sensors. Finally, we’ll build a simple web server to display the sensor readings.

ESP8266 with DS18B20 Temperature Sensor using Arduino IDE

Throughout this tutorial we’ll cover the following topics:

  1. Read temperature from one DS18B20 temperature sensor;
  2. Read temperature from multiple DS18B20 temperature sensors;
  3. Display DS18B20 sensor readings on a web server.

You might also like reading other DS18B20 guides:

Learn more about the ESP8266 with our course: Home Automation using ESP8266.

Introducing DS18B20 Temperature Sensor

The DS18B20 temperature sensor is a one-wire digital temperature sensor. This means that it just requires one data line (and GND) to communicate with your ESP8266.

It can be powered by an external power supply or it can derive power from the data line (called “parasite mode”), which eliminates the need for an external power supply.

DS18B20 Temperature Sensor Pinout Pins

Each DS18B20 temperature sensor has a unique 64-bit serial code. This allows you to wire multiple sensors to the same data wire. So, you can get temperature from multiple sensors using just one GPIO.

The DS18B20 temperature sensor is also available in waterproof version.

DS18B20 Temperature Sensor Waterproof version

Here’s a summary of the most relevant specs of the DS18B20 temperature sensor:

  • Communicates over one-wire bus
  • Power supply range: 3.0V to 5.5V
  • Operating temperature range: -55ÂșC to +125ÂșC
  • Accuracy +/-0.5 ÂșC (between the range -10ÂșC to 85ÂșC)

For more information consult the DS18B20 datasheet.

Parts Required

To complete this tutorial you need the following components:

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!

ESP8266 with DS18B20 Schematic Diagram

As mentioned previously, the DS18B20 temperature sensor can be powered through the VDD pin (normal mode), or it can derive its power from the data line (parasite mode). You can choose either modes.

Parasite Mode

DS18B20 Temperature Sensor with ESP8266 Parasite Mode Wiring Schematic Diagram

Normal Mode

DS18B20 Temperature Sensor with ESP8266 Normal Mode Wiring Schematic Diagram

Note: in this tutorial we’re connecting the DS18B20 data line to GPIO 4, but you can use any other suitable GPIO.

Read our ESP8266 GPIO Reference Guide to learn more about the ESP8266 GPIOs.

Note: if you’re using an ESP-01, GPIO 2 is the most suitable pin to connect to the DS18B20 data pin.

Preparing Your Arduino IDE

We’ll program the ESP8266 using Arduino IDE, so make sure you have the ESP8266 add-on installed before proceeding:

Installing Libraries for DS18B20

To interface with the DS18B20 temperature sensor, you need to install the One Wire library by Paul Stoffregen and the Dallas Temperature library. Follow the next steps to install those libraries.

1. Open your Arduino IDE and go to Sketch Include Library > Manage Libraries. The Library Manager should open.

2. Type “onewire” in the search box and install the OneWire library by Paul Stoffregen.

Install OneWire library by Paul Stoffregen in Arduino IDE

3. Then, search for “Dallas” and install the Dallas Temperature library by Miles Burton.

Install DallasTemperature library by Miles Burton in Arduino IDE

After installing the libraries, restart your Arduino IDE.


Code (Single DS18B20)

After installing the required libraries, you can upload the following code to the ESP8266. The code reads temperature from the DS18B20 temperature sensor and displays the readings on the Arduino IDE Serial Monitor.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com  
*********/

#include <OneWire.h>
#include <DallasTemperature.h>

// 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() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();
}

void loop() {
  sensors.requestTemperatures(); 
  float temperatureC = sensors.getTempCByIndex(0);
  float temperatureF = sensors.getTempFByIndex(0);
  Serial.print(temperatureC);
  Serial.println("ÂșC");
  Serial.print(temperatureF);
  Serial.println("ÂșF");
  delay(5000);
}

View raw code

There are many different ways to get the temperature from DS18B20 temperature sensors. However, if you’re using just one single sensor, this is one of the easiest and simplest ways.

DS18B20 Single OneWire Temperature Sensor with ESP32 and Arduino IDE on Breadboard

How the Code Works

Start by including the OneWire and the DallasTemperature libraries.

#include <OneWire.h>
#include <DallasTemperature.h>

Create the instances needed for the temperature sensor. The temperature sensor is connected to GPIO 4.

// 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);

In the setup(), initialize the Serial Monitor at a baud rate of 115200.

Serial.begin(115200);

Initialize the DS18B20 temperature sensor:

sensors.begin();

Before actually getting the temperature, you need to call the requestTemperatures() method.

sensors.requestTemperatures(); 

Then, get the temperature in Celsius by using the getTempCByIndex() method as shown below:

float temperatureC = sensors.getTempCByIndex(0);

Or use the getTempFByIndex() to get the temperature in Fahrenheit.

float temperatureF = sensors.getTempFByIndex(0);

The getTempCByIndex() and the getTempFByIndex() methods accept the index of the temperature sensor. Because we’re using just one sensor its index is 0. If you want to read more than one sensor, you use index 0 for one sensor, index 1 for other sensor and so on.

Finally, print the results in the Serial Monitor.

Serial.print(temperatureC);
Serial.println("ÂșC");
Serial.print(temperatureF);
Serial.println("ÂșF");

New temperature readings are requested every 5 seconds.

delay(5000);

Demonstration

After uploading the code, open the Arduino IDE Serial Monitor at a 115200 baud rate. You should get the temperature displayed in both Celsius and Fahrenheit:


Getting Temperature from Multiple DS18B20 Temperature Sensors

DS18B20 Multiple Temperature Sensors OneWire with ESP32 and Arduino IDE

The DS18B20 temperature sensor communicates using one-wire protocol and each sensor has a unique 64-bit serial code, so you can read the temperature from multiple sensors using just one single digital Pin.

Schematic

To read the temperature from multiple sensors, you just need to wire all data lines together as shown in the next schematic diagram:

DS18B20 Multiple Temperature Sensors with ESP32 Wiring Schematic Diagram

Code (Multiple DS18B20s)

Then, upload the following code. It scans for all devices on GPIO 4 and prints the temperature for each one. This sketch is based on the example provided by the DallasTemperature library.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com  
*********/

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged TO GPIO 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

// Number of temperature devices found
int numberOfDevices;

// We'll use this variable to store a found device address
DeviceAddress tempDeviceAddress; 

void setup(){
  // start serial port
  Serial.begin(115200);
  
  // Start up the library
  sensors.begin();
  
  // Grab a count of devices on the wire
  numberOfDevices = sensors.getDeviceCount();
  
  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(numberOfDevices, DEC);
  Serial.println(" devices.");

  // Loop through each device, print out address
  for(int i=0;i<numberOfDevices; i++){
    // Search the wire for address
    if(sensors.getAddress(tempDeviceAddress, i)){
      Serial.print("Found device ");
      Serial.print(i, DEC);
      Serial.print(" with address: ");
      printAddress(tempDeviceAddress);
      Serial.println();
    } else {
      Serial.print("Found ghost device at ");
      Serial.print(i, DEC);
      Serial.print(" but could not detect address. Check power and cabling");
    }
  }
}

void loop(){ 
  sensors.requestTemperatures(); // Send the command to get temperatures
  
  // Loop through each device, print out temperature data
  for(int i=0;i<numberOfDevices; i++){
    // Search the wire for address
    if(sensors.getAddress(tempDeviceAddress, i)){
      // Output the device ID
      Serial.print("Temperature for device: ");
      Serial.println(i,DEC);
      // Print the data
      float tempC = sensors.getTempC(tempDeviceAddress);
      Serial.print("Temp C: ");
      Serial.print(tempC);
      Serial.print(" Temp F: ");
      Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
    }
  }
  delay(5000);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress) {
  for (uint8_t i = 0; i < 8; i++){
    if (deviceAddress[i] < 16) Serial.print("0");
      Serial.print(deviceAddress[i], HEX);
  }
}

View raw code

How the code works

The code uses several useful methods to handle multiple DS18B20 sensors.

You use the getDeviceCount() method to get the number of DS18B20 sensors on the data line.

numberOfDevices = sensors.getDeviceCount();

The getAddress() method finds the sensors addresses:

if(sensors.getAddress(tempDeviceAddress, i)){

The address is unique for each sensor. So each sensor can be identified by its address.

Then, you use the getTempC() method that accepts as argument the device address. With this method, you can get the temperature from a specific sensor:

float tempC = sensors.getTempC(tempDeviceAddress);

To get the temperature in Fahrenheit degrees, you can use the getTempF(). Alternatively, you can convert the temperature in Celsius to Fahrenheit as follows:

DallasTemperature::toFahrenheit(tempC)

Demonstration

After uploading the code, open your Serial Monitor at a baud rate of 115200. You should get all your sensors readings displayed as shown below:

ESP8266 Multiple DS18B20 Temperature Sensors Serial Monitor Print readings

Display DS18B20 Temperature Readings in a Web Server

To build the web server we’ll use the ESPAsyncWebServer library that provides an easy way to build an asynchronous web server. Building an asynchronous web server has several advantages. We recommend taking a quick look at the library documentation on its GitHub page.

Installing the ESPAsyncWebServer library

The ESPAsyncWebServer library is not available to install in the Arduino IDE Library Manager. So, you need to install it manually.

Follow the next steps to install the ESPAsyncWebServer library:

  1. Click here to download the ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncWebServer-master folder
  3. Rename your folder from ESPAsyncWebServer-master to ESPAsyncWebServer
  4. Move the ESPAsyncWebServer folder to your Arduino IDE installation libraries folder

Installing the ESPAsync TCP Library

The ESPAsyncWebServer library requires the ESPAsyncTCP library to work. Follow the next steps to install that library:

  1. Click here to download the ESPAsyncTCP library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncTCP-master folder
  3. Rename your folder from ESPAsyncTCP-master to ESPAsyncTCP
  4. Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Code (DS18B20 Async Web Server)

Open your Arduino IDE and copy the following code.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com  
*********/

// Import required libraries
#ifdef ESP32
  #include <WiFi.h>
  #include <ESPAsyncWebServer.h>
#else
  #include <Arduino.h>
  #include <ESP8266WiFi.h>
  #include <Hash.h>
  #include <ESPAsyncTCP.h>
  #include <ESPAsyncWebServer.h>
#endif
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is connected to GPIO 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

// Variables to store temperature values
String temperatureF = "";
String temperatureC = "";

// Timer variables
unsigned long lastTime = 0;  
unsigned long timerDelay = 30000;

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String readDSTemperatureC() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures(); 
  float tempC = sensors.getTempCByIndex(0);

  if(tempC == -127.00) {
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Celsius: ");
    Serial.println(tempC); 
  }
  return String(tempC);
}

String readDSTemperatureF() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures(); 
  float tempF = sensors.getTempFByIndex(0);

  if(int(tempF) == -196){
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Fahrenheit: ");
    Serial.println(tempF);
  }
  return String(tempF);
}

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .ds-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP DS18B20 Server</h2>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="ds-labels">Temperature Celsius</span> 
    <span id="temperaturec">%TEMPERATUREC%</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="ds-labels">Temperature Fahrenheit</span>
    <span id="temperaturef">%TEMPERATUREF%</span>
    <sup class="units">&deg;F</sup>
  </p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperaturec").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperaturec", true);
  xhttp.send();
}, 10000) ;
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperaturef").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperaturef", true);
  xhttp.send();
}, 10000) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DS18B20 values
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATUREC"){
    return temperatureC;
  }
  else if(var == "TEMPERATUREF"){
    return temperatureF;
  }
  return String();
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);
  Serial.println();
  
  // Start up the DS18B20 library
  sensors.begin();

  temperatureC = readDSTemperatureC();
  temperatureF = readDSTemperatureF();

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  
  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", temperatureC.c_str());
  });
  server.on("/temperaturef", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", temperatureF.c_str());
  });
  // Start server
  server.begin();
}
 
void loop(){
  if ((millis() - lastTime) > timerDelay) {
    temperatureC = readDSTemperatureC();
    temperatureF = readDSTemperatureF();
    lastTime = millis();
  }  
}

View raw code

Insert your network credentials in the following variables, and the code will work straight away.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

How the Code Works

In the following paragraphs we’ll explain how the code works. Keep reading if you want to learn more or jump to the “Demonstration” section to see the final result.

Importing libraries

First, import the required libraries.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

Instantiate DS18B20 Sensor

Define the GPIO that the DS18B20 data pin is connected to. In this case, it’s connected to GPIO 4(D1).

#define ONE_WIRE_BUS 4

Instantiate the instances needed to initialize the sensor:

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

Create variables that will hold the temperature and humidity as String values:

String temperatureF = "";
String temperatureC = "";

We’ll get new sensor readings every 30 seconds. You can change that in the timerDelay variable.

unsigned long lastTime = 0;  
unsigned long timerDelay = 30000;

Setting your network credentials

Insert your network credentials in the following variables, so that the ESP8266 can connect to your local network.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Create an AsyncWebServer object on port 80.

AsyncWebServer server(80);

Read Temperature Functions

Then, we create two functions to read the temperature.

The readDSTemperatureC() function returns the readings in Celsius degrees.

String readDSTemperatureC() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures(); 
  float tempC = sensors.getTempCByIndex(0);

  if(tempC == -127.00){
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Celsius: ");
    Serial.println(tempC); 
  }
  return String(tempC);
}

In case the sensor is not able to get a valid reading, it returns -127. So, we have an if statement that returns two dashes (–-) in case the sensor fails to get the readings.

if(tempC == -127.00){
  Serial.println("Failed to read from DS18B20 sensor");
  return "--";

The reaDSTemperatureF() function works in a similar way but returns the readings in Fahrenheit degrees.

The readings are returned as string type. To convert a float to a string, use the String() function.

return String(tempC);

Building the Web Page

The next step is building the web page. The HTML and CSS needed to build the web page are saved on the index_html variable.

In the HTML text we have TEMPERATUREC and TEMPERATUREF between % signs. This is a placeholder for the temperature values.

This means that this %TEMPERATUREC% text is like a variable that will be replaced by the actual temperature value from the sensor. The placeholders on the HTML text should go between % signs.

We’ve explained in great detail how the HTML and CSS used in this web server works in a previous tutorial. So, if you want to learn more, refer to the next project:

Processor

Now, we need to create the processor() function, that will replace the placeholders in our HTML text with the actual temperature values.

// Replaces placeholder with DS18B20 values
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATUREC"){
    return temperatureC;
  }
  else if(var == "TEMPERATUREF"){
    return temperatureF;
  }
  return String();
}

When the web page is requested, we check if the HTML has any placeholders. If it finds the %TEMPERATUREC% placeholder, we return the temperature in Celsius by calling the readDSTemperatureC() function created previously.

if(var == "TEMPERATUREC"){
  return temperatureC;
}

If the placeholder is %TEMPERATUREF%, we return the temperature in Fahrenheit.

else if(var == "TEMPERATUREF"){
  return temperatureF;
}

setup()

In the setup(), initialize the Serial Monitor for debugging purposes.

Serial.begin(115200);

Initialize the DS18B20 temperature sensor.

sensors.begin();

Get the current temperature values:

temperatureC = readDSTemperatureC();
temperatureF = readDSTemperatureF();

Connect to your local network and print the ESP8266 IP address.

WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println();
  
// Print ESP8266 Local IP Address
Serial.println(WiFi.localIP());

Finally, add the next lines of code to handle the web server.

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

When we make a request on the root URL, we send the HTML text that is stored in the index_html variable. We also need to pass the processor function, that will replace all the placeholders with the right values.

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

We need to add two additional handlers to update the temperature readings. When we receive a request on the /temperaturec URL, we simply need to send the updated temperature value. It is plain text, and it should be sent as a char, so, we use the c_str() method.

server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", temperatureC.c_str());
});

The same process is repeated for the temperature in Fahrenheit.

server.on("/temperaturef", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", temperatureF.c_str());
});

Lastly, we can start the server.

server.begin();

In the loop(), update the temperature values every 30 seconds (timerDelay variable).

void loop(){
  if ((millis() - lastTime) > timerDelay) {
    temperatureC = readDSTemperatureC();
    temperatureF = readDSTemperatureF();
    lastTime = millis();
  }  
}

That’s pretty much how the code works.

Demonstration

After uploading the code, open the Arduino IDE Serial Monitor at a baud rate of 115200. After a few seconds your IP address should show up.

In your local network, open a browser and type the ESP8266 IP address.

Now you can see temperature in Celsius and Fahrenheit in your web server. The sensor readings update automatically without the need to refresh the web page.

ESP8266 Web Server with DS18B20 OneWire Temperature Sensor Arduino IDE

Wrapping Up

This was an in-depth guide on how to use the DS18B20 temperature sensor with the ESP8266 and display the readings on a web server.

The DS18B20 communicates via one-wire protocol and each sensor has a unique 64-bit serial code, which means you can read many sensors on the same data pin.

We hope you’ve found this tutorial useful. We have other tutorials with the ESP8266 that you may also like:

Learn more about the ESP8266 with Home Automation using ESP8266 (eBook + Video Course).

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

205 thoughts on “ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)”

  1. Cool item, like to see more of this 🙂 and if I may,… some more articles with ESP modules in low power/power save mode (where the whole solution is powered by 1 18650 battery…

    Reply
  2. Hi, thanks for the neat project, it looks very useful, and I may well build one of these for outdoor temp while we are living in our motor home this winter. Question though, could one add another sensor of the same kind for outdoor and use one for indoor?? Thus two Dallas temp sensors? Also could one also add a LCD display to display the temps locally as well as on the network?

    Reply
  3. Hi, if I try to compile this code on my IDE I get this error:

    Temperature_Sensor:17: error: ‘D1’ was not declared in this scope

    #define ONE_WIRE_BUS D1

    It seems that D1 is not recognize. What do you think about?

    Reply
  4. Hi. Great tutorial as usual. I have a suggestion for another ESP tutorial and that is to be able to pass data to a MySQL db. I have one set up on one of my RasPi’s and it receives data from my other RasPis but I also have ESP modules that I would like to collect data from but can’t figure out how to do that. I think this would be a great general interest topic to cover…if it can be done. 🙂
    Thanks,
    Bruce

    Reply
  5. Hi Rui,

    I want to try this with ESP8266-01, GPIO2, so what should I use instead of “D1” ?

    Thanks in advance

    Reply
  6. Hoi Rui

    Would you please explain to me what to change in the sketch so that the web-page is refreshing every x seconds ?

    regards Ton.

    Reply
  7. Another great tutorial Rui, Thanks! I usually use an ESP07 or ESP12 in projects. Can you tell me how the GPIO numbers relate to the “Dn” numbering of the Nodemcu 1.0 Module. Thanks.

    Reply
  8. Hello Rui, I built your project with the esp and DS1820B and it works fine with my mobile device but when I use Chrome or Firefox I don’t get a response. The ESP sees the connect but the browser just sits there. Any ideas?

    Reply
  9. Yes !!!…as always…good job!!!!
    I am waiting for a light in the path from you to write a tutorial about FTP and this ESP8266 Node MCU, if you have time, one day maybe?

    Reply
  10. bonsoir
    j’ai lu avec attention votre tuto
    peut on le mettre en place avec un réseau adhoc
    cordialement
    pierre

    Reply
  11. Realy nice and informative thank you somuch for your kindness to freely over flow the knowldge. It is help to poors who cannot spend money for learning. God will take care of you. Thanks for shearing.

    Reply
  12. I have just created an account for your home automation server and have set up a led and its working perfectly – Thank you.

    I also wanted to monitor room temperature, but cant see how to do this on the home automation server – is this possible?

    Reply
  13. Great tutorial !!
    Btw, I have a question, how can I update the temparature data, when it changes, to the webserver without reloading the page ??
    Thank you for reading !

    Reply
    • You can either assign a fixed IP address in your router to your ESP’s MAC address.
      Or simply Google ESP8266 Arduino IDE fixed IP address and you’ll find a snippet of code that you can use

      Reply
  14. Many thanks for posting the article and code. Works like a charm on my basic ESP2866 and the DS18B20 board that I had from a Pi project. My first couple of days with the ESP8266, what an amazing piece of kit!

    Reply
  15. Hi Rui, Merry Christmas.

    First of all, thanks for another great tutorial.

    I built the project with the esp and DS1820B and it works fine.

    Now I’m building another project, reads the data with ESP, and displays in serial terminal, showing like in the browser, but I see trash.
    How do I translate the view, it would be like in the browser?
    And how I present data also in LCD?
    Can you give me some aimed please?

    Thanks a lot.

    Reply
  16. Hi Rui, Thank you for your comment.
    The Baud rate is OK.
    I see that the results of the measurement, but it probably displays HTML with a lot of other data.
    I would like to isolate the data of temperature, how do I do it?

    Thanks.

    Reply
  17. Hello Rui
    i use fdti, esp8266-01, ds18b20
    I modified the line
    #define ONE_WIRE_BUS 5
    to
    #define ONE_WIRE_BUS 2 (gpio2)
    It worked once until “New client”
    Without being able to access the web
    Since the script stops after the ip address
    why ?
    Best regards
    Pierre

    Reply
  18. As I am typing this reply the browser is still trying to connect to the ESP-12. It’s now more then 5 minutes. The serial monitor gives an IP and as soon as I type in the IP it shows: New client but nothing happens. As a matter of fact, It is (the browser) still trying to connect.

    Reply
    • It looks like you’re not entering the right IP address in your web browser or your ESP is not establishing a Wi-Fi connection with your router.
      Make sure you double-check the serial monitor and it prints the IP address that you’re using to access in your web browser.

      Reply
      • Dear Rui,
        ESP is connected to wifi, I know IP address but WWW page isn’t available, also serial moitor shows nothing. Any ideas what could be the problem ?

        Thx
        Marcin

        Reply
  19. @marc and @marcin

    Try using an other pin for the ds18B20 sensor. I had to connect to D5 instead of D1. The page loaded instantly when connected to the right port.

    Reply
  20. Hello!

    I’ve did this project but now i want to learn something new. For example i want to add an LED which indicates readings from ds18b20, how to do that?

    Regards,
    Hrvoje

    Reply
  21. Hi,
    Thank you for your tutorial.
    Will the same code work in all the development board for ESP8266?
    If not what changes do we need to make?

    Thanking you in advance.
    GK

    Reply
    • Hi.
      This code works for ESP8266.
      It should work in all models.
      The only thing you may need to change is the pin that the sensor is connected to.
      In our example it is connected to D1(GPIO 5). You may need to connect to another pin, in case your specific development board doesn’t have that pin available.
      I hope this answers your question.
      Regards,
      Sara

      Reply
  22. Hi and thanks a lot for your toutorials, I’m trying to get connected with web server, I’m using an ESP01, and there is no way to do it.
    I found now in my nettwork list “ESP_89ED249” network, I’m connected to this and by ipconfig I know the IP address (192.168.4.1), if I type this on my Chrome I’m able to see the web server…
    Please tell me what is going wrong.
    Another issue I’m don’t able to get data from DHT11 sensor, any suggestion for this?

    Reply
  23. Thanks for your tutorials and cord work, these days i,m work on another job. After that I’l go throw and inform you.

    Reply
  24. Hi,
    Thank you very much for your tutorials.
    One question: is it possible to use second ESP8266 (with LCD for example) in this system to display measured temperature on LCD? I’d like to measure water temperature in a pool and display the result on both side: on PC and LCD. Thank you for your answer.
    Darko

    Reply
  25. My ESP 8266 would only connect to my wifi if I added delay(10); after
    Serial.begin(115200);
    Not to sure why but works perfectly now.
    Thanks for code. Also, enjoying your ESP 32 book

    Reply
    • Thank you for sharing that. It may be useful for our readers.
      I’m glad you’re enjoying our ESP32 course.
      Regards,
      Sara

      Reply
  26. hey, thanks for the tutorial, but i want to ask about the use of ds18b20 with esp board, i heard that digital pin of esp has input range 0 to 3,3 and analog pin 0 to 1. So does it save using a ds18b20 modul for esp ?
    thanks in advance

    Reply
  27. Hi Sara/Rui,
    I have an Arduino Mega running an established Aquaponics garden. What project do you offer that I can purchase to make the senors visible online, not just on my local network?

    Reply
  28. I am using the same sketch with addition to displaying the values on an OLED screen, but the values are getting distorted on the display as soon as i connect more than one sensor, could someone help me with this i am using OLED in I2C interface.

    Reply
    • Hi.
      With those details, it is very difficult to find out what can be wrong.
      You can read our OLED guide with the ESP8266 and see if it helps find out what might be wrong.
      Regards,
      Sara

      Reply
  29. ok. im sorry to type again, but with the full code i only can read one sensor and i need several, but i dont know coding, im not a programe, just curious, can yoy give some help for the complete code with server, thanks and sorry to ask again.

    Reply
  30. Hello Sara and Rui! Thank you so much for your tutorials! I have a question about this one. Ds18b20 web server is working perfectly on my computer, but…i cant see it on my Android phone, which is in the same wifi network. Can you tell me what can be a reason?

    Reply
      • Im using Chrome on my Android phone. When i log into my home network i cant see server page on my phone, just on my computer. But i noticed that ESP create his own network,and after i connect with phone to it i can see server page on phone. Is this the way it should works?

        Reply
        • Hi.
          That’s not the way it should work.
          Add this line

          WiFi.mode(WIFI_STA);

          Before initializing Wi-fi:
          WiFi.begin(ssid, password);

          It should solve the problem.
          Regards,
          Sara

          Reply
  31. Hello and congratulations.
    I am struggling with a network consisting of 15 ds18b20 sensors, where I monitor the temperature of the home.
    I connected most of the sensors with individual telephone cables ( 5 to 20 meters long each).
    In 3 cases I connected 2 sensors to a single cable.
    I tried to monitor them through the wemos d1 version 3 and connected all according to the rule, gnd to gnd, vcc to the 3v3 of the wemos and the data to the pin d7 of the wemos with resistance from 4k7 between data and 3v3.
    I can read up to 6/7 sensors at the same time, if I connect further ones, it returns -127 on all of them. I also tried to lower the resistance value to 1k given the length of the sections but I do not solve.
    I measured the current that supplies the wemos and it is 3.27v.
    How can I solve it?

    Reply
  32. op’s I could not edit my post to add that when the one-wire sends a signal the length of the wire can come into play. if a close one returns a value before a far one even gets the request, then the collision causes problems.
    One way is to have all the sensor wires the same length and connect as some place.
    if you have the D1 in in the basement and some sensors in the basement and some on the 2nd floor, you could run a wire from the basement to the first floor, then all the basement wires would run to a point on the first floor and all the 2nd floor sensors would run to that same point. a STAR configuration.

    Reply
  33. Hi Rui,
    Ken jou tel me of it is possible to get more then oneDS18B20 sensors on one ESP8266.
    Like this DS18B20 Multiple Temperature Sensors OneWire with ESP32 and Arduino IDE
    best regards Ronald.

    Reply
  34. Thank you Rui for tutorial and Sara for post suport on issues!!!

    The project run very well except for one issue here, it only recognize two sensors (i made with four intalled). I already change the place of the sensors and just two sensors have output in serial monitor. Do you have any idea of what is happening? Thanks!

    Reply
  35. Very nice article, Rui. Just a couple things: It looks like the DeviceAddress type is an array of 8-bit unsigned integers “typedef uint8_t DeviceAddress[8];”, so I think the address of the sensors are an 8-bit serial code, not 64. Also, I don’t know why the getTempCByIndex and getTempFByIndex functions are considered “slow”. I think I’d rather use those than than dealing with the DeviceAddress. In DallasTemperature.cpp, indeed, these functions wrap calls using the DeviceAddress type:

    float DallasTemperature::getTempCByIndex(uint8_t deviceIndex) {

    DeviceAddress deviceAddress;
    if (!getAddress(deviceAddress, deviceIndex)) {
    return DEVICE_DISCONNECTED_C;
    }
    return getTempC((uint8_t*) deviceAddress);

    }

    Reply
  36. HEllo Rui and Sara

    I built the DS18B20 appli with ESP32 version and it’s work
    _ temperature displayed on monitor and also with webserver
    thanks ! your tutorial are very easy to follow and detailled !

    now I want to use a ESP-01 to read a DS18B20 temperature senor
    I built this projet, it work with serial monitor
    but for webserver, I have a error during execution (after download and reset):
    Exception (3):
    epc1=0x40100818 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4006f1b9 depc=0x00000000

    stack>>> (stack displayed)

    during compilation I had this message:
    Executable segment sizes:
    IROM : 268020 – code in flash (default or ICACHE_FLASH_ATTR)
    IRAM : 27324 / 32768 – code in IRAM (ICACHE_RAM_ATTR, ISRs…)
    DATA : 1260 ) – initialized variables (global, static) in RAM/HEAP
    RODATA : 2536 ) / 81920 – constants (global, static) in RAM/HEAP
    BSS : 25320 ) – zeroed variables (global, static) in RAM/HEAP

    this ESP-01 was OK in the past with older version of IDE and old librarie
    I could use webserver to send SMS for example.
    why not working now?
    I search on web but it’s not easy to understand …

    thanks for advice!

    Mike

    Reply
  37. Really nice and thank you Rui & Sara, works very well. Can you by any chance tell me what code I need to add to push the data of the 2 sensors (in my case) to an Influx database?

    Reply
    • Hi.
      Thanks for your comment.
      Unfortunately, at the moment, we don’t have any tutorials about influx db.
      Regards,
      Sara

      Reply
    • Hi.
      After uploading the code, press the ESP8266 RST button, so that it starts running the code and print the IP address.
      Regards,
      Sara

      Reply
  38. If using NodeMCU, use either pin D3/GPIO0 or D4/GPIO2 you don’t need pullup of 4.7K, the board already has 12K pullup on those pins.
    I build 3 boards using D4/GPIO2 without 4.7K and they work perfectly.

    It is a bit tricky because I found those pullup while reading the schematic of NodeMCU.

    The same about A0 pin for ADC, there is existing voltage divider with 220K and 100K res.

    Good article you wrote!

    Reply
  39. First Rui thank you I have just discovered this. Unfortunately I am not having success with the web server display code. as soon as a browser hits the esp8266 12E server the console monitor shows continuous resets. I’m not sure where to start with the trouble shooting. I have taken these steps
    reflashed multiple esp8266 12e boards multiple times with different flash tools including NodeMCU Flasher. The previous section without the web server works well.

    Reply
  40. I’m not having any success with the web page coming up, its not bringing up anything, not even with serial monitor other than a stack error:

    Panic C:\Users\Steve\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266\core_esp8266_main.cpp:98 __yield

    ctx: sys
    sp: 3ffff9f0 end: 3fffffb0 offset: 01b0

    stack>>>
    3ffffba0: 00000000 00000001 00000100 40207340
    3ffffbb0: 00000000 00006d2b 3ffeee74 40208cd5
    3ffffbc0: 3fff2147 3ffeee74 3ffeee74 40207883
    3ffffbd0: 3fff2147 3ffeee74 3ffeee74 402078c4
    3ffffbe0: 3fff00e4 00000404 3ffffc44 40202131
    3ffffbf0: 3fff2147 3ffffc50 3ffffc44 40202288
    <<<stack<<<

    ets Jan 8 2013,rst cause:2, boot mode:(3,7)

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v3de0c112
    ~ld
    xCâžźConnecting to WiFi

    I did the single test 1st And it came out fine on the serial monitor with temperatures every 5 seconds displaying a reading, its something in the Web server but I dont know what ? I’ve copied & pasted the code ? Im using Huzzah 8266 AI Thinker Mod chip

    Reply
  41. HEllo
    for my side (see previous post in this file) , I have reflashed the SDK with last version and it works now!
    allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/

    I don’t know what is this date “ets Jan 8 2013” ? but old SDK ??

    best regards

    Mike

    Reply
    • Thank you for this post. It gives me the first clue as to what might be going on. I’m not looking forward to the work involved, though. I wonder how I can buy an ESP8266 and insure it has firmware that will work already installed. At this point, I’ve already put a huge amount of time into getting this to work.

      Reply
  42. Hi. Thanks for what you do. I am having a similar problem to others in the comments above. Working my way through the tutorial everything works as expected until I get to the Async web server section. My issue is the same as Stephen Castle. I ran nmap and found the address displayed for the lan in the serial monitor is correct. But when I try to connect to it I get a dump of hex numbers same as Mr. Castle. It continues to refresh until I close the browser window. That seems like a pretty big hint as to what is going wrong. Any ideas of how to fix this.

    Reply
  43. I am having similar problem on error trying to load the website. The error is as below. Can anyone please help. thanks.
    ets Jan 8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 3584, room 16
    tail 0
    chksum 0xb0
    csum 0xb0
    v2843a5ac
    ~ld

    Connecting to WiFi
    …..
    192.168.1.5

    Reply
      • I’m thinking that it’s time for the developers of this project to load it onto an ESP8266 board and come up with a solution for this problem. I’m not sure where the problem is and I’m not good enough at programming to figure it out.

        Reply
  44. Hello,

    First of all thank you for such a great site! I have purchased your Home Automation Course. And am really pleased.
    I have run and tested my circuit and all works well. I have it wired exactly as your multi-sensor example.

    I have copied and pasted the Web server code there were no issues upon upload it connects it connects with my network and provides me with an IP address. The problem is that when i copy that IP address in to a browser it will not connect via WiFi? I even tried to un-plug my Serial Port connection to the ESP8266 board, and then power it independently. Still am not getting a connection. All of your other code has been perfect, I must be doing something mechanically incorrect ?

    Reply
    • I checked Windows diagnostics and this was the message ”

      The remote device or resource won’t accept the connection Detected Detected

      The device or resource (wpad.Home) is not set up to accept connections on port “The World Wide Web service (HTTP)”.

      Reply
      • Hi Dave.
        That’s weird.
        I’ve never faced that problem.
        What browser are you using?
        I’ve found this: appuals.com/fix-remote-device-resource-wont-accept-connection/
        Take a look and see if it helps.
        If this doesn’t work, since your are a RNT costumer, please post your issue in the RNTLAB forum: https://rntlab.com/forum/
        I can follow your issue closer there.
        Regards,
        Sara

        Reply
        • Sara,
          Thanks for the reply I wanted to let you know that this is the first time this has happened for me as well. I am able to join other IP addresses from RNT tutorials. i.e. BME680 async server works perfectly.

          I have tried three browsers, Vivaldi, Chrome, Explorer, with the same result.
          I erased the memory on my 8266 NodeMCU board and reflashed it. I also reactivated the Wifi chip on the board via MicroPython.

          I have only rarely been able to get webrepl to talk to these boards so I am wondering if there is a common issue with the firmware. Perhaps this is an issue with some of these boards I have three from the same vendor?

          I will see if there is something incorrect in my laptops network settings? I don’t want to fix something that is not broken as I am able to connect to other similar devices. I did want to say before I go that I can’t access this ip address on my Android phone either?

          I will report any findings to https://rntlab.com/forum/.

          Thank you again,

          Dave

          Reply
          • Hi Sara and Dave,

            First of all I would also like to thank you for assembling this material. It gives a good head start!

            Though I also experienced, that the example is not quite working for me, when I copied the example code for the web server scenario. Today, I finally managed to figure out why that was.

            This example uses async web server (me-no-dev /
            ESPAsyncWebServer). In the readme of the server implementation the following is stated:
            “Important things to remember

            You can not use yield or delay or any function that uses them inside the callbacks”

            So when you open the website, the web server callbacks contact the temperature sensor (through dallas and onewire) and tries to read out data, but it does that with adding some delay, and on top of that if you use dallas in blocking mode (which is by default, you can change by: sensors.setWaitForConversion(false);, but in this case you have to manage some timing aspect), than it also calls yield (see DallasTemperature::blockTillConversionComplete), which eventually causes the application to crash.

            I verified my theory by adding yield or delay calls to the callbacks. It made the application instantly fail, when it hit the yield function. It seemed, that it is more forgiving with delay. However, neither of yield or delay is recommended as stated above.

            I would rather execute periodic temperature reading in the loop(), and from the callback only get the already determined values making the callbacks simple and fast.

            I used the newest of everything: arduino core, dallas, onewire, async web server.

            Cheers!

  45. This looks like a pretty cool project, I just wish I could get it to work on the ESP8266. I’ve confirmed that the ESP and everything else works and that the problem would seem to be related to this code. The board connects to the WiFi and has a valid IP until I try access the WebServer from any Web Browser. As soon as I do that the WiFi disconnects, the Serial monitor dumps a bunch of hex numbers and then the WiFi reestablishes link to my router. I truly don’t understand a lot of his code so would anyone have any suggestions as to how this could be fixed. Thanks

    Reply
    • There is a problem with the Dallas Temperature Library and the ESPAsyncTCP lib. You’ll find an explanation on Reddit. This code works fine on ESP32 because then the ESPAsyncTCP lib is not used.
      Regards
      Richard

      Reply
      • Is this the explanation you’re referring to:

        reddit.com/r/esp8266/comments/iofuxy/esp8266_crashes_anytime_i_connect_to_the_ip/g4dn2es/?utm_source=reddit&utm_medium=web2x&context=3

        Why is this an error now, but worked fine for users back in 2016 when this tutorial was first published?

        Reply
  46. Wow .. That is the Best and simple explanation of the code .. I hope everyone use this method ,it will become so easy for beginners to learn. Thanks alot again for this.

    Reply
  47. Thanks for great tutorial!

    Like a few others, unfortunately my serial monitor just throws a list of hex errors after I connect to the IP it establishes via my browser:

    “ctx: sys
    sp: 3fffead0 end: 3fffffb0 offset: 0000
    3fffead0: 3fffeb00 3fffec80 00000000 40100ab1
    3fffeae0: 000000fe 00000000 00000000 00000000
    etc”

    Any way around this?

    Reply
    • // Route for root / web page
      server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){
      request->send_P(200, “text/html”, index_html, processor);
      });
      server.on(“/temperaturec”, HTTP_GET, [](AsyncWebServerRequest *request){
      request->send_P(200, “text/plain”, String(sensors.getTempCByIndex(0)-3).c_str());
      });
      server.on(“/temperaturef”, HTTP_GET, [](AsyncWebServerRequest *request){
      request->send_P(200, “text/plain”, String(sensors.getTempFByIndex(0)-5.4).c_str());
      });

      and

      // Replaces placeholder with DHT values
      String processor(const String& var){
      //Serial.println(var);
      if(var == “TEMPERATUREC”){
      return String(sensors.getTempCByIndex(0)-3);
      }
      else if(var == “TEMPERATUREF”){
      return String(sensors.getTempFByIndex(0)-5.4);
      }
      return String();
      }

      Reply
      • Thank you for the code Wojciech, this does help – the hex error codes in the serial monitor are gone, the webpage now displays when I connect to the IP from my browser (iPhone).

        However the temps displayed are not correct- they start at negative temps, then slowly climb to 0C and 32F, which is curious.

        In your lines “if(var == “TEMPERATUREC”){return String(sensors.getTempCByIndex(0)-3);”
        and
        “else if(var == “TEMPERATUREF”){return String(sensors.getTempFByIndex(0)-5.4);}

        what is the purpose of the “-3” and “-5.4” terms? Are they correction factors? I have tried removing them, but the temps displayed are still incorrect.

        Reply
  48. Following code works for ESP8266 with Arduino IDE V1.8.13:

    /*********
    Rui Santos
    Complete project details at https://RandomNerdTutorials.com

    modified for ESP8266 by Richard 2021-01-21 and working on WeMosD1mini V1.0.0
    (Arduino IDE Boards WeMosD1R1)
    avoiding callback problems according to Rockfunster
    *********/

    // Import required libraries
    #ifdef ESP32
    #include <WiFi.h>
    #include <ESPAsyncWebServer.h>
    #define ONE_WIRE_BUS 15 // ESP32
    #else
    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <Hash.h>
    #include <ESPAsyncTCP.h>
    #include <ESPAsyncWebServer.h>
    #define ONE_WIRE_BUS 4 // D2
    #endif
    #include <OneWire.h>
    #include <DallasTemperature.h>

    // Setup a oneWire instance to communicate with any OneWire devices
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature sensor
    DallasTemperature sensors(&oneWire);

    // Replace with your network credentials
    const char* ssid = “mps3_2”;
    const char* password = “TJsvDwdTdgvi”;

    String StrTempC;
    String StrTempF;

    // Create AsyncWebServer object on port 80
    AsyncWebServer server(80);

    String readDSTemperatureC() {
    // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
    sensors.requestTemperatures();
    float tempC = sensors.getTempCByIndex(0);

    if(tempC == -127.00) {
    Serial.println(“Failed to read from DS18B20 sensor”);
    return “–“;
    } else {
    Serial.print(“Temperature Celsius: “);
    Serial.println(tempC);
    }
    return String(tempC);
    }

    String readDSTemperatureF() {
    // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
    sensors.requestTemperatures();
    float tempF = sensors.getTempFByIndex(0);

    if(int(tempF) == -196){
    Serial.println(“Failed to read from DS18B20 sensor”);
    return “–“;
    } else {
    Serial.print(“Temperature Fahrenheit: “);
    Serial.println(tempF);
    }
    return String(tempF);
    }

    const char index_html[] PROGMEM = R”rawliteral(

    html {
    font-family: Arial;
    display: inline-block;
    margin: 0px auto;
    text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .ds-labels{
    font-size: 1.5rem;
    vertical-align:middle;
    padding-bottom: 15px;
    }

    ESP DS18B20 Server


    Temperature Celsius
    %TEMPERATUREC%
    °C


    Temperature Fahrenheit
    %TEMPERATUREF%
    °F

    setInterval(function ( ) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById(“temperaturec”).innerHTML = this.responseText;
    }
    };
    xhttp.open(“GET”, “/temperaturec”, true);
    xhttp.send();
    }, 10000) ;
    setInterval(function ( ) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById(“temperaturef”).innerHTML = this.responseText;
    }
    };
    xhttp.open(“GET”, “/temperaturef”, true);
    xhttp.send();
    }, 10000) ;

    )rawliteral”;

    // Replaces placeholder with DHT values
    String processor(const String& var){
    //Serial.println(var);
    if(var == “TEMPERATUREC”){
    //return String(sensors.getTempCByIndex(0));
    return StrTempC;
    }
    else if(var == “TEMPERATUREF”){
    //return String(sensors.getTempFByIndex(0));
    return StrTempF;
    }
    return String();
    }

    void setup(){
    // Serial port for debugging purposes
    Serial.begin(115200);
    Serial.println();

    // Start up the DS18B20 library
    sensors.begin();

    // Connect to Wi-Fi
    WiFi.begin(ssid, password);
    Serial.println(“Connecting to WiFi”);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }
    Serial.println();

    // Print ESP Local IP Address
    Serial.println(WiFi.localIP());

    // Route for root / web page
    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, “text/html”, index_html, processor);
    });
    server.on(“/temperaturec”, HTTP_GET, [](AsyncWebServerRequest *request){
    //request->send_P(200, “text/plain”, (sensors.getTempCByIndex(0)).c_str());
    request->send_P(200, “text/plain”, String(StrTempC).c_str());
    });
    server.on(“/temperaturef”, HTTP_GET, [](AsyncWebServerRequest *request){
    //request->send_P(200, “text/plain”, String(sensors.getTempFByIndex(0)).c_str());
    request->send_P(200, “text/plain”, String(StrTempF).c_str());
    });
    // Start server
    server.begin();
    }

    void loop(){
    StrTempC = readDSTemperatureC();
    Serial.print(StrTempC);
    Serial.print(” “);
    StrTempF = readDSTemperatureF();
    Serial.println(StrTempF);
    }

    Reply
    • I would Suggest a delay between reads. 1wire does not like constant polling of one device, other than serial number checks.
      Nice catch by the way.
      I had an issue with the other code I wrote for another application. Seems a call back just likes you to get in a get out. I found that if a second call back occurs while i am still inside one, I was getting crashes.

      Reply
  49. I was having the same problem trying to get this to work on a NodeMCU ESP8266.

    Same crash, stack dump each time, and then a processor reboot.

    Finally tracked it down to readDSTemperatureC( ) and readDSTemperatureF( ).

    They crash trying to poll the 1-wire hardware when called from these call-backs
    request->send_P(200, “text/plain”, readDSTemperatureC().c_str());
    and
    request->send_P(200, “text/plain”, readDSTemperatureF().c_str());

    Moving the 1-wire polling code to the main loop( ) function and having it store temperature values in a global variable, which the readDSTemperatureC() and readDSTemperatureF() can then read and display, “fixed” the problem.

    Some sort of issue with calling the 1-wire function from the server callbacks? Not-reentrant maybe?

    Reply
  50. Richard, thank you. I’ve been tearing my hair out trying to solve this problem & your solution worked (well, after I’d removed the different character codes inserted by copying from the web page text). It obviously used to work OK so I wonder what has changed? Maybe the latest version of <ESPAsyncWebServer.h> is different in the way it reacts to the callback issue.

    Reply
  51. Hi Guys,
    How would I modify the webserver code to show multiple DS18B20 readings?
    I only need degrees C so I have room but cant figure out where to pull the seperate data from each device into the programme.
    Love these tutorials and the challenges they present.
    Thanks Mark

    Reply
  52. Delete from functions:
    //readDSTemperatureC()
    sensors.requestTemperatures();
    float tempC = sensors.getTempCByIndex(0);
    //readDSTemperatureF()
    sensors.requestTemperatures();
    float tempF = sensors.getTempFByIndex(0);

    ADD global variables:
    float tempC;
    float tempF;

    ADD function on top:
    void radDSTemperatures(){
    sensors.requestTemperatures();
    tempC = sensors.getTempCByIndex(0);
    tempF = sensors.getTempFByIndex(0);
    }

    ADD in loop() function:

    void loop(){
    delay(1000);
    radDSTemperatures();
    }

    Reply
  53. Hello

    Than You for great tutorial.
    I want to make temperature and smoke measurement using DS18B20 and MQ2.I changed the code for my need. Do It possible to turn of server?
    I want to measure temperature and smoke – when will be above some level programme gives signal which turn off relay. This relay turn off the 220V device. But when temperature is fall programme is still running because the server is running.
    Thank you

    Reply
  54. Hello everyone. I have a problem with my “wireless temperature” project.

    I’m uploading my project to my esp. I go step by step and record.
    Now I copy the IP address and put it in the internet browser and then it tells me that the page does not exist and arduiono serial monitor writes me this

    https://ctrlv.cz/Y3M2

    https://ctrlv.cz/6svZ

    Reply
  55. Thank you very much for this detailed article. It helped me a lot and made some of my projects much easier. There are now remote engine monitoring modules in railway vehicles all over germany, my heating system is running on those ds18b20 sensors and even the plant watering system in the greenhouse is relying on some of them. I always use three or more sensors in parallel because they are so cheap and it makes the whole system much more reliable. The code includes a remote warning function in case one of the sensors outputs a value out of the range of the others. And all the information for these projects are available in one article. Great work!

    Reply
  56. Fantastic tutorial! Needed to set up a remote temperature monitor for my attic and it took less than an hour. I went through the entire tutorial step by step and everything worked great. I used Arduino 1.8.13 on Linux, but I took a short cut: instead of manually unzipping and copying the EspAsyncWebServer-master.zip and EspAsyncTCP-master.zip, I simply used Sketch->Include Library->Add .ZIP library from the Arduino IDE. Thank you.

    Reply
  57. Did somebody have used two ds18b20 sensors with the onewire protocol and was able to compare the two values? I am trying this for quite some time but i cannot get the hang of it…
    thanks in advance! if my code is desired, please let me know.

    Reply
  58. Hello,
    I have this working on a board that I made up a couple of years ago. I want to change the wifi name and password so I have downloaded the arduino 1.8.1.5 and installed the libraries and esp board in arduino. I have added your script and changed the wifi name and password. Every time I compile I get the following error message, despite manually confirming that the ESP Libari is in the arduino folder and is correctly named

    Arduino: 1.8.15 (Mac OS X), Board: “NodeMCU 0.9 (ESP-12 Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    (…)
    -> candidates: [[email protected]]
    /Users/duncanlovett/Library/Arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.0-newlib4.0.0-gnu23-48f7b08/bin/xtensa-lx106-elf-g++ -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/sdk/include -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/sdk/lwip2/include -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/tools/sdk/libc/xtensa-lx106-elf/include -I/var/folders/lw/pdmsk9dn48x971w_n13kv2_40000gn/T/arduino_build_27253/core -c -w -Os -g -free -fipa-pta -mlongcalls -mtext-section-literals -fno-rtti -falign-functions=4 -std=gnu++17 -ffunction-sections -fdata-sections -fno-exceptions -DMMU_IRAM_SIZE=0x8000 -DMMU_ICACHE_SIZE=0x8000 -w -x c++ -E -CC -DNONOSDK22x_190703=1 -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DLWIP_FEATURES=1 -DLWIP_IPV6=0 -DARDUINO=10815 -DARDUINO_ESP8266_NODEMCU_ESP12 -DARDUINO_ARCH_ESP8266 “-DARDUINO_BOARD=\”ESP8266_NODEMCU_ESP12\”” -DFLASHMODE_QIO -DESP8266 -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/cores/esp8266 -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/variants/nodemcu -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/libraries/ESP8266WiFi/src -I/Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/libraries/Hash/src -I/Users/duncanlovett/Documents/Arduino/libraries/ESPAsyncTCP/src /var/folders/lw/pdmsk9dn48x971w_n13kv2_40000gn/T/arduino_build_27253/sketch/NodeMCU_Temp_Sensor.ino.cpp -o /dev/null
    Alternatives for ESPAsyncWebServer.h>: []NodeMCU_Temp_Sensor:15:12: fatal error: ESPAsyncWebServer.h>: No such file or directory

    ResolveLibrary(ESPAsyncWebServer.h>) 15 | #include <ESPAsyncWebServer.h>S

    -> candidates: [] | ^~~~~~~~~~~~~~~~~~~~~~

    compilation terminated.
    Using library ESP8266WiFi at version 1.0 in folder: /Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/libraries/ESP8266WiFi
    Using library Hash at version 1.0 in folder: /Users/duncanlovett/Library/Arduino15/packages/esp8266/hardware/esp8266/3.0.0/libraries/Hash
    Using library ESPAsyncTCP at version 1.2.2 in folder: /Users/duncanlovett/Documents/Arduino/libraries/ESPAsyncTCP
    exit status 1
    ESPAsyncWebServer.h>: No such file or directory

    Any suggestions on what to try?

    Many thanks for a great tutorial.

    Reply
    • Hi.
      The problem is with the ESPAsyncWebServer library.
      Or it is not installed or it is not properly installed.
      That’s what the error is about.
      Regards,
      Sara

      Reply
      • Sure Sara, its’ installed as per your instructions, I can see it correctly named in the correct folder on my mac and shows as a library in the ardiuno app.

        Any suggestions?

        Thanks

        Duncan

        Reply
        • Have a look at the github library, as quite a few changes have been made due to the boardmanager changes to the ESP core.
          For library issues, that is a good place to get library helo.

          Reply
        • Hi.
          Check that you only have one arduino IDE installation and that it is not conflicting with other files.
          Otherwise, I don’t know what can be causing the issue.
          Regards,
          Sara

          Reply
    • Hi. I gladly joined and made this website. Thank you very much.
      I answer Duncan Lovett. I was the same.
      I found a small error in the code.
      In place:
      #include <ESPAsyncWebServer.h> S
      You need to write:
      #include <ESPAsyncWebServer.h>
      That’s it. With respect.

      Reply
  59. Hi
    Thx for this great tutorial !
    I am using DS18B20 with esp8622E-12
    I am getting a minus value for the temperature and I don’t know why exactly

    Anyone can help ?

    Reply
    • Hi.
      That usually happens when the sensor is not wired properly or it doesn’t have enough power.
      Regards,
      Sara

      Reply
  60. Hi really nice tutorial, i could replicate it quite easily, now i have problem/doubt, i’d put 3 dallas sensors that should read in three different positions, but web server shod me just one temperature (F and C) value, how to get the
    sowed all reading just in celsius?
    Thanks for help

    Reply
  61. Hi nice tutorial, i tried the web server example and perfectly work, then i’d connected 3Dallas sensor in serei (as per example) with web server code, unfortunately it shows only 1 temperature. How to modify the code for get show 3 different temperature (one for sensor) just in C? thanks

    Reply
  62. Hi Sara,
    hi Rui,
    thank you for that very helpful tutorial I’ve learned a lot from.
    I wonder if and how to can enhanche the code for requesting date/time from a NTP-time server. Maybe you have already an example and share the code.
    Thank you

    Reply
  63. Hi,
    Thank you for the tutorial
    I used it for a project that uses 3 pcs ds18b20. I only use degrees Celsius. I changed the temperature display to degrees F for sensor 2 and added another sensor. I tried to make the changes so that the web page would refresh itself for all 3 values, but only the first two are updated. What exactly needs to be changed?

    Reply
  64. Hi, greetings from Italy, I wanted to know if it is possible to modify the sketch to get 4 or more DS18B20 sensors only in Celsus and on the web page, in the same way as your sketch that I tried and it works only with 1 sensor even if I have connected them 4.
    I would add that I am not a very trained programmer.
    I can modify existing sketches a little.
    Thank you.

    Reply
  65. Thanks for this great tutorial. To make the website work, I had a compile error at first but installing the AsyncTCP library from github resolved it.

    Reply
  66. Hi Sara, great tutorial!
    After many tests I realized that the ESP8266 tends to heat up a lot (it absorbs 70mA) I deactivated the “soft AP” mode but it continues to heat up a lot, if I try with other codes that always act as a web server towards the ESP8266 always reading the temperature of the DS18b20, I notice that the absorption drops to about 30mA with the ESP8266 lukewarm.
    I preferred to use your code because it is nicer also in terms of graphics of the web page …
    Is it possible to make it heat less?
    Thanks in advance

    Reply
  67. This worked fine for me – I have a Linux Mint 20.3 installation, and it also worked on an Android smartphone., but a friend built the same thing, and it will not talk to a Windows10 installation. The SSID/Password is correct, and the IP address is OK. Could this be the WIndows Firewall stopping it – and how does he need to change the firewall.

    Reply
  68. hi, sorry to pester you… I’m stuck and no amount of google is helping me

    I’m trying the webpage with temp sensors… I have this error when trying to compile

    Arduino: 1.8.19 (Windows 10), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    sketch_jul11a:15:12: fatal error: C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2/tools/sdk/include/ESPAsyncWebServer.h>: Invalid argument

    Multiple libraries were found for “ESPAsyncTCP.h”

    15 | #include <ESPAsyncWebServer.h>S

    Used: C:\Program Files (x86)\Arduino\libraries\ESPAsyncTCP

    | ^~~~~~~~~~~~~~~~~~~~~~

    Not used: C:\Users\USER\Documents\Arduino\libraries\ESPAsyncTCP-master

    compilation terminated.

    exit status 1

    C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2/tools/sdk/include/ESPAsyncWebServer.h>: Invalid argument

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    any ideas?

    Reply
  69. awesome tutorial, got it working in minutes. my only question is how to display this on an android phone. I try typing the isp address into my phone browser like on my pc but it won’t load an isp address.

    Reply
  70. Hello,

    Great tutorial as always!

    I have a question about the identification of multiple DS18B20 sensors.

    You wrote:
    “The address is unique for each sensor. So each sensor can be identified by its address.”

    Does it mean that the sensors get uniqe address every time you reset the microcontroller or the addresses are always the same?

    I need constant address (to refer) to store correctly the tempsensors in database and if it gets always different address that will be a mess.

    Thanks for your answer in advance!

    Cheers!

    Reply
  71. slightly off topic…. but

    I’m having problems with interference with long wires, setup in a star system

    I run multiple ~10m cat5 cables with 4x ds18b20 on the end of each… each cat 5cable runs back to a patch panel which the esp8266 is plugged into with a short wire

    I’ve googled and found adding a capacitor to the end of each run might help, so I’ll do that

    but I’m also thinking I could run each wire back to a different data pin on the board, so each data pin will have 4 temp sensors on the end of it

    will this work ok? any hints/tips?

    thanks

    Alan

    Reply
  72. Hello, quick question regarding pull-up: if I activate internal pull-up in ESP, can I get rid of resistor?
    Thanks for the tutorial.
    Stefano

    Reply
  73. Hello!!!
    Can something be added to the code or somehow made to have some kind of alarm or email notification when a set minimum or maximum temperature is reached???
    Thanks!!!

    Reply
  74. Hello!!!
    I’m using this board ESP32 Development Board TYPE-C USB CH340C ESP-WROOM and I don’t know where the error is. The code was uploaded and the board connected to the network, but in my serial monitor it says: “Failed to read from DS18B20 sensor”.
    Am I connecting to the wrong pin or is the temperature sensor defective??? I have left it as it is by default in the code
    (// Data wire is connected to GPIO 4
    #define ONE_WIRE_BUS 4)
    but I am not sure if it is valid for my board???
    I would be very grateful if you could help me.
    Thank you in advance!!!
    P.S. This is my board:
    https://www.aliexpress.com/item/1005004480331940.html?spm=a2g0o.order_list.0.0.76401802nzLP17

    Reply
  75. Hi,
    Thank you very much for your tutorials.
    One question: is it possible to use second ESP8266 (with LCD for example) in this system to display measured temperature on SSD1306? I’d like to measure water temperature and display the result on both side: on PC and display SSD1306. Thank you for your answer.
    Tom

    Reply
  76. I am using a DS18B20 with esp8622. I need a two-wire connection but the Parasite Mode output in a serial monitor is always -127 C. When using the Normal Mode the measurements are correct.

    Reply
  77. I was able to make the ESP8266 an access point and was able to see temperature readings from web server. However, the code I have for another ESP8266 acting as a client to retrieve temperature readings isn’t working properly. Can you assist?

    Reply
  78. Very good subject and good description.
    I have modified it so that it handles 10 Temp. sensors.
    I only have 1 problem.
    When I call a function in the loop() and that function is described under the loop, I get a compile error that it cannot find that function.
    If I put that function above the setup() then everything works fine.
    I found that the problem is in the line that begins <link rel=”stylesheet”.
    If I omit this line, the compiler gives no error.
    What is going on here?

    Reply
  79. Nice tutorial. Works fine after finding out that there is a little flaw in the description.
    Reading the text in the section “Demonstration” it says:
    “open the Arduino IDE Serial Monitor at a 9600 baud rate”

    Correct setting is 115200 baud – as the source code says and also the screenshot below.

    Reply
  80. Hi Rudi or Sara.
    Thank you very much for your excellent tutorials.
    I am trying to change the Temperature text to red below +10 degrees.
    How should I do?
    Greetings.
    Peter

    Reply
  81. Hi there,
    many thanks for your work, whis is always a reference for me!

    So please let me donate the missing ‘p’ here:
    “To get the temperature in Fahrenheit degrees, you can use the getTemF().”

    ‘getTempF()’

    Best
    Stefan

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.