DS18B20 Sensor Interfacing with ESP32

Overview of DS18B20 Sensor

 

DS18B20 Sensor
  • DS18B20 is a Digital Temperature sensor which is developed by Maxim Integration.
  • This sensor measures temperature in the range of -55°C to 125°C.
  • It is a 3-terminal device that provides 9-bit to 10-bit Celsius temperature measurements.
  • This is a 1-Wire temperature sensor.

DS18B20 Waterproof Sensor Pinout

DS18B20 Pin Diagram

VCC: This is a supply pin that requires DC voltage in the range of 3.0V to 5.5V

DATA: This pin gives the output in digital format

GND: Connect to the supply ground

  • DS18B20 consumes the 1mA in active mode and 750nA in standby mode.
  • DS18B20 accuracy is ±0.5°C for the range of 10°C to the +85°C 
  • The DS18B20 is available in 8-Pin SO (150 mils), 8-Pin µSOP, and 3-Pin TO-92 Packages

Note: for the one wire communication we’ll need to add one 4.7k pull-up resistor between the DATA pin and VCC pin.

 

DS18B20 Interfacing Diagram with ESP32

DS18B20 Interfacing Diagram with ESP32

 

 

Measure Temperature using DS18B20 and ESP32

Let’s interface the DS18B20 temperature sensor to ESP32 and display the surrounding temperature on the webserver as well as on the serial monitor.

Here we are using DallasTemperature libraries for the above example. We need to install the DallasTemperature library using the Arduino Library Manager.

  • Open the Arduino IDE
  • Navigate to Sketch  Include Library  Manage Libraries…

 

  • The library Manager window will pop up. Now enter DS18B20 into the search box, and click Install on the DallasTemperature option to install version 3.9.0 or higher. As shown below image.

 

  • If you don’t have the OneWire library, then this pop-up will come then click on Install all.

 

  • Now open the simple example, to open it go to File Example DallasTemperature  Simple

 

  • Here we have modified the code as per the above example.

DS18B20 Serial Monitor Code for ESP32

// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2

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

/*
 * The setup function. We only start the sensors here
 */
void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

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

/*
 * Main function, get and show the temperature
 */
void loop(void)
{ 
  // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  Serial.print("Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  // After we got the temperatures, we can print them here.
  // We use the function ByIndex, and as an example get the temperature from the first sensor only.
  float tempC = sensors.getTempCByIndex(0);

  // Check if reading was successful
  if(tempC != DEVICE_DISCONNECTED_C) 
  {
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(tempC);
  } 
  else
  {
    Serial.println("Error: Could not read temperature data");
  }
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 9600 to see the output.

 

ESP32 serial monitor output for DS18B20

 

Let’s understand the code

The code begins with initializing the DallasTemperature and OneWire libraries.

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

Set the pin number 2 for DS1307 of ESP32

#define ONE_WIRE_BUS 2

Setup a oneWire instance to communicate with any OneWire devices 

OneWire oneWire(ONE_WIRE_BUS);

Pass oneWire reference to DallasTemperature

DallasTemperature sensors(&oneWire);

 

In setup function

We have initiated the serial communication with a 9600 Baud rate and initialized the dallasTemperature object using sensors.begin() function.

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

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

 

In loop function

Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

sensors.requestTemperatures(); // Send the command to get temperatures

After getting the temperature, we saved it on the tempC float variable.

Here we have connected only one temperature sensor if you have multiple sensors then add in ByIndex function.

float tempC = sensors.getTempCByIndex(0);

Now check the received temperature status reading and print on the serial monitor

// Check if reading was successful
if(tempC != DEVICE_DISCONNECTED_C) 
{
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(tempC);
} 
else
{
    Serial.println("Error: Could not read temperature data");
}

 

Measure Temperature using DS18B20 over ESP32 Web Server

ESP32 has oh-chip Wi-Fi, we can utilize it and monitor the readings over our smartphone, Laptop, or even smart TV. This can offer much more flexibility and real world applications.

We can use the ESP32 web server to monitor the Temperature.

 

Let’s display the same readings on the web server using the ESP32 and Arduino IDE.

Before uploading the code make sure you have added your SSID, and Password as follows.

const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/

Code  for Temperature Monitoring on the web server using DS18B20 and ESP32

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <WebServer.h>
#include "html.h"

#define DS18B20PIN 2                        /* Connect DS18B20 to Pin No D2 of ESP32*/
OneWire oneWire(DS18B20PIN);
DallasTemperature sensor(&oneWire);

WebServer server(80);
float _temperature;

const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/
 
void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send the code to the web server*/
}

void Temp() {
  String TempValue = String(_temperature);    //Convert it into string
  server.send(200, "text/plane", TempValue);  //Send updated temperature value to the web server
}

void setup(void){
  Serial.begin(115200);               /*Set the baudrate to 115200*/
  WiFi.mode(WIFI_STA);                /*Set the WiFi in STA Mode*/
  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  delay(1000);                       /*Wait for 1000mS*/
  while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("Your Local IP address is: ");
  Serial.println(WiFi.localIP());     /*Print the Local IP*/
  sensor.begin();

  server.on("/", MainPage);           /*Display the Web/HTML Page*/
  server.on("/readTemp", Temp);       /*Display the updated Temperature and Humidity value*/
  server.begin();                    /*Start Server*/
  delay(1000);                       /*Wait for 1000mS*/
}

void loop(void){
  sensor.requestTemperatures(); 
  _temperature = sensor.getTempCByIndex(0); /* Read the temperature */
  Serial.print("Temperature = ");
  Serial.print(_temperature);         /* Print Temperature on the serial window */
  Serial.println("ºC");
  server.handleClient(); 
  delay(1000);                       /* Wait for 1000mS */
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 then reset the ESP32 board and check the IP address as shown in the below image

 

 

  • Now open any mobile browser and type the IP address which is shown in the serial monitor and hit the enter button. 
  • If all are ok, then the web page will start the showing current temperature on the web server like in the below image.

Note: make sure your ESP32 and mobile are connected to the same router/server, if they are connected to the same router or server then only you will be able to visible the web page.

 

Final Output on the webserver

 

Let’s Understand the code

To understand this code, please refer the basics guide of “How to create the ESP32 Server”.

Once you get the basics of ESP32 server creation, it will be very simple to understand the code.

This code starts with important header files and libraries, In WiFi.h file contains all ESP32 WiFi related definitions, here we have used them for network connection purposes. 

The WebServer.h file supports handling the HTTP GET and POST requests as well as setting up a server. In the html.h file contains all the web page code, In one wire library contains the I2C related functions and then add the DallasTemperature.h library file.

#include <WiFi.h>
#include <WebServer.h>
#include "html.h"
#include <OneWire.h>
#include <DallasTemperature.h>

Define the pin number for DS18B20 temperature sensor

#define DS18B20PIN 2           /* Connect DS18B20 to Pin No D2 of ESP32*/

Let’s define HTTP port i.e., Port 80 as follows

WebServer server(80);

 

Setup Function

In setup function, first we set the WiFi as an STA mode and connect to the given SSID and password

WiFi.mode(WIFI_STA);          /*Set the WiFi in STA Mode*/
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
delay(1000);                  /*Wait for 1000mS*/
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}

After successfully connecting to the server print the local IP address on the serial window.

Serial.print("Your Local IP address is: ");
Serial.println(WiFi.localIP());     /*Print the Local IP*/

 

Handling Client Requests and Serving the Page

To handle the client request, we use server.on() function.

It takes two parameters, The first is requested URL path, and the second is the function name, which we want to execute.

As per the below code, when a client requests the root (/) path, the “MainPage()” function executes. 

Also, when a client requests the “/readTemp” path, The Temp() function will be called.

server.on("/", MainPage);    /*Client request handling: calls the function to serve HTML page */
server.on("/readTemp", Temp);/*Display the updated Temperature and Humidity value*/

Now start the server using server.begin() function.

server.begin();                     /*Start Server*/

 

Functions for Serving HTML

We have defined the complete HTML page in file named “html.h” and added it in header file. With following function, we are sending complete page to client via server.send() function.

While sending, we are passing the first parameter “200” which is the status response code as OK (Standard response for successful HTTP requests). 

The second parameter is content type as “text/html”, and the third parameter is html page code.

void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send HTM page to Client*/
}

Now in the below function only we are sending the updated temperature values to the web page.

void Temp() {
  String TempValue = String(_temperature);    //Convert it into string
  server.send(200, "text/plane", TempValue);  //Send updated temperature value to the web server
}

 

Loop Function

Now to handle the incoming client requests and serve the relevant HTML page, we can use handleClient() function. It executing relevant server.on() as a callback function although it is defined in void setup()

So, it continuously serves the client requests.

server.handleClient();

 

HTML Web Page Code

This is a code for the web page that shows the measured temperature using a DS18B20 temperature sensor and ESP32.

/*
  ESP32 HTML WebServer Page Code
 http:://www.electronicwings.com
*/

const char html_page[] PROGMEM = R"rawSrting(
<!DOCTYPE html>
<html>
  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>
 
<body>
  <h1>DS18B20 Temperature Monitoring With ESP32</h1><br>
  <p>Temperature: <span id="TempValue">0</span>&degC</p><br>

  <script>
    setInterval(function() {
      var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         document.getElementById("TempValue").innerHTML = this.responseText;
        }
      };
     xhttp.open("GET", "readTemp", true);
      xhttp.send();
    },50);
  </script>
</body>
</html>
)rawSrting";

 

Let’s understand the code step by step

All html pages start with the <!DOCTYPE html> declaration, it is just information to the browser about what type of document is expected.

<!DOCTYPE html>

The html tag is the container of the complete html page which represents on the top of the html code.

<html>

Now here we are defining the style information for a web page using the <style> tag. Inside the style tag we have defined the font name, size, color, and test alignment. 

  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>

 

Inside the body, we are defining the document body, in below we have used headings, and paragraphs if you want you can add images, hyperlinks, tables, lists, etc. also.

On the web page, we are displaying the heading of the page, and inside a paragraph temperature values.

Now temperature value updates under the span id which is manipulated with JavaScript using the id attribute.

<body>
  <h1>DS18B20 Temperature Monitoring With ESP32</h1><br>
  <p>Temperature: <span id="TempValue">0</span>&degC</p><br>

Now, this is the javascript that comes under the <script> tag, this is also called a client-side script.

<script>

In setInterval() method we are calling the function at every 50mS intervals.

setInterval(function() {},50);

Here we are creating the html XMLHttpRequest object

var xhttp = new XMLHttpRequest();

 

The xhttp.onreadystatechange event is triggered every time the readyState changes and the readyState holds the status of the XMLHttpRequest.

Now in the below code, the ready state is 4 means the request finished and response is ready and the status is 200 which means OK.

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const myArr = JSON.parse(this.responseText);

Now here is the main thing, we are updating the temperature values in html page using TempValue id.

document.getElementById("TempValue").innerHTML = this.responseText;

 

Here we used the AJAX method to send the updated values to the server without refreshing the page.

In the below function we have used the GET method and sent the readTemp function which we defined in the main code asynchronously. 

xhttp.open("GET", "readTemp", true);

Send the request to the server using xhttp.send(); function.

xhttp.send();

 

Close the script

</script>

Close the body

</body>

Close the html.

</html>

Components Used

DS18B20 Waterproof temperature sensor
DS18B20 Waterproof temperature sensor
1
ESP32 WROOM
WiFi Development Tools - 802.11 ESP32 General Development Kit, embeds ESP32-WROOM-32E, 4MB flash.
1

Downloads

ESP32_DS18B20_Serial_Monitoring Download
ESP32_DS18B20_web_server_monitoring Download
Ad