DS18B20 Temperature Sensor with ESP32 or ESP8266 for Alexa (also MAX31820, DS1822)

In this section we’ll walk through creating a Temperature Sensor using ESP32, ESP8266 and then view the temperature via Alexa, Google Home or SmartThings.

Prerequisites :

  1. ESP32, ESP8266 x 1.
  2. DS18B20 or DS1822, DS1820, MAX31820, MAX31850 x 1.
  3. 4.7k Ohm resistor x 1
  4. Jumper Wires.

Quick introduction to Temperature Sensor

The DS18B20 is a digital temperature sensor that communicates over a 1-Wire bus. It is a popular choice for many applications, including home automation, environmental monitoring, and industrial automation. The DS18B20 works by measuring the resistance of a thermistor. The thermistor is a semiconductor device whose resistance changes with temperature. The DS18B20 has a built-in 12-bit ADC that converts the thermistor’s resistance to a digital value.

MAX31820, DS1822, DS1820 and MAX31850: are they compatible with the DS18B20?

Yes. These sensors all use the same 1-Wire protocol and the same DallasTemperature library, so the wiring and the code in this tutorial work without changes. The library detects the sensor model from its 1-Wire family code.

Sensor Family code Resolution Supply voltage Notes
DS18B20 0x28 9 to 12 bit 3.0 V to 5.5 V ±0.5 °C from −10 °C to +85 °C
MAX31820 0x28 9 to 12 bit 3.0 V to 3.7 V ±0.5 °C from +10 °C to +45 °C. Same family code as the DS18B20
DS1822 0x22 9 to 12 bit 3.0 V to 5.5 V Lower-cost version, ±2 °C
DS1820 / DS18S20 0x10 9 bit 3.0 V to 5.5 V Fixed resolution
MAX31850 0x3B 14 bit 3.0 V to 3.7 V Thermocouple (K-type) converter with a 1-Wire interface

MAX31820 and MAX31850: use 3.3V only. Their maximum supply voltage is 3.7 V, so connect VDD to the 3.3V pin of the ESP32 or ESP8266, not to 5V.

Wiring

Sinric Pro esp8266 DS18B20 wiring

If you are using the DS18B20, ground pins 1 and 3. The centre pin is the data line ‘1-wire’.

MCU GPIO Pin
ESP32 16
ESP8266 14 (D5)

Let’s verify that temperature is wired correctly and working.

#if defined(ESP8266)
  #define DS18B20_PIN    D5
#elif defined(ESP32)
  #define DS18B20_PIN    16
#endif

#include <OneWire.h>
#include <DallasTemperature.h> // Supports DS18B20 or DS1822, DS1820, MAX31820, MAX31850
 
OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);

void setup() {
  Serial.begin(115200);
  
  Serial.print("DallasTemperature Library version: ");
  Serial.println(DALLASTEMPLIBVERSION);

  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(2000);
}

View this code on GitHub Gist

Arduino IDE Serial Monitor will show the current temperature like this

Sinric Pro DS18B20 Temperature Sensor

Step 1 : Create a new device in Sinric Pro

Sinric Pro create device alexa

Sinric Pro temperature sensor device notifications

You can set the threshold here to receive a push notification via the Sinric Pro app when the temperature goes below or above a certain temperature. Use the Retrigger Time to set the delay between notifications.

Sinric Pro copy device id

Step 2 : Connect to Sinric Pro

Step 2.1 Install Sinric Pro Library

Sinric Pro install SinricPro library

You can generate the code using Zero Code feature or write it by your self. If you do not have programming experice, we recommend to use Zero Code feature in the Portal to generate the code, download and flash.

2.2 Complete Code

#ifdef ENABLE_DEBUG
  #define DEBUG_ESP_PORT Serial
  #define NODEBUG_WEBSOCKETS
  #define NDEBUG
#endif 

#include <Arduino.h>
#if defined(ESP8266)
  #include <ESP8266WiFi.h>
#elif defined(ESP32)
  #include <WiFi.h>
#endif

#if defined(ESP8266)
  #define DS18B20_PIN    D5
#elif defined(ESP32)
  #define DS18B20_PIN    16
#endif

#include "SinricPro.h"
#include "SinricProTemperaturesensor.h"
#include <OneWire.h>
#include <DallasTemperature.h> // https://github.com/milesburton/Arduino-Temperature-Control-Library

#define WIFI_SSID         ""   // Your WiFI SSID name 
#define WIFI_PASS         ""   // Your WiFi Password.
#define APP_KEY           ""   // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx" (Get it from Portal -> Secrets)
#define APP_SECRET        ""   // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx" (Get it from Portal -> Secrets)
#define TEMP_SENSOR_ID    ""   // Should look like "5dc1564130xxxxxxxxxxxxxx" (Get it from Portal -> Devices)
#define BAUD_RATE         115200              // Change baudrate to your need (used for serial monitor)
#define EVENT_WAIT_TIME   60000               // send event every 60 seconds

OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);

float temperature;                            // actual temperature
float humidity;                               // actual humidity
float lastTemperature;                        // last known temperature (for compare)
   
void handleTemperaturesensor() {
  if (SinricPro.isConnected() == false) {
    Serial.printf("Not connected to Sinric Pro...!\r\n");
    return; 
  }

  static unsigned long last_millis;
  unsigned long        current_millis = millis();
  if (last_millis && current_millis - last_millis < EVENT_WAIT_TIME) return;
  last_millis = current_millis;
  
  sensors.requestTemperatures(); 
  temperature = sensors.getTempCByIndex(0);
  //temperature = sensors.getTempFByIndex(0); // in °F

  Serial.printf("Temperature: %2.1f °C\r\n", temperature);

  if (isnan(temperature)) { // reading failed... 
    Serial.printf("DS18B20 reading failed!\r\n");  // print error message
    return;                                    // try again next time
  } 

  if (temperature == lastTemperature) {
    Serial.printf("Temperature did not changed. do nothing...!\r\n");
    return; 
  }

  SinricProTemperaturesensor &mySensor = SinricPro[TEMP_SENSOR_ID];  // get temperaturesensor device
  bool success = mySensor.sendTemperatureEvent(temperature, -1); // send event
  if (success) {  
    Serial.printf("Sent!\r\n");
  } else {
    Serial.printf("Something went wrong...could not send Event to server!\r\n"); // Enable ENABLE_DEBUG to see why
  }

  lastTemperature = temperature;  // save actual temperature for next compare  
}


// setup function for WiFi connection
void setupWiFi() {
  Serial.printf("\r\n[Wifi]: Connecting");

  #if defined(ESP8266)
    WiFi.setSleepMode(WIFI_NONE_SLEEP); 
    WiFi.setAutoReconnect(true);
  #elif defined(ESP32)
    WiFi.setSleep(false); 
    WiFi.setAutoReconnect(true);
  #endif

  WiFi.begin(WIFI_SSID, WIFI_PASS); 

  while (WiFi.status() != WL_CONNECTED) {
    Serial.printf(".");
    delay(250);
  }
  IPAddress localIP = WiFi.localIP();
  Serial.printf("connected!\r\n[WiFi]: IP-Address is %d.%d.%d.%d\r\n", localIP[0], localIP[1], localIP[2], localIP[3]);
}

bool onPowerState(const String &deviceId, bool &state) {
  return true; // request handled properly
}

// setup function for SinricPro
void setupSinricPro() {
  // add device to SinricPro
  SinricProTemperaturesensor &mySensor = SinricPro[TEMP_SENSOR_ID];
  mySensor.onPowerState(onPowerState);
  
  // setup SinricPro
  SinricPro.onConnected([](){ Serial.printf("Connected to SinricPro\r\n"); }); 
  SinricPro.onDisconnected([](){ Serial.printf("Disconnected from SinricPro\r\n"); });
  //SinricPro.restoreDeviceStates(true); // Uncomment to restore the last known state from the server.
  SinricPro.begin(APP_KEY, APP_SECRET);  
}

// main setup function
void setup() {
  Serial.begin(BAUD_RATE); Serial.printf("\r\n\r\n");
  
  Serial.print("DallasTemperature Library version: ");
  Serial.println(DALLASTEMPLIBVERSION);
  sensors.begin();

  setupWiFi();
  setupSinricPro();
}

void loop() {
  SinricPro.handle();
  handleTemperaturesensor();
}

View this code on GitHub Gist

Now you should be able to view the temperature via Sinric Pro App

Sinric Pro App Temperature Sensor

Please note that Google Home App shows the temperature sensor as a Thermostat due to Google Home limitations.

Troubleshooting

  1. error: DallasTemperature.h: No such file or directory

    Solution: Please make sure correct temperature library is installed. https://github.com/milesburton/Arduino-Temperature-Control-Library

  2. Reading invalid values like -127.00C, -196.60F, -127.00C, -196.60F

    Solution: Make sure you have wired correcrly or you do not have loose connection.

    -127 is the value of DEVICE_DISCONNECTED_C in the DallasTemperature library. getTempCByIndex() returns it when no sensor answers on the 1-Wire bus. Check that:

    • the 4.7k Ohm pull-up resistor is connected between the data line and 3.3V
    • the data line is on the GPIO defined in the sketch
    • VDD and GND are not swapped
    • a MAX31820 or MAX31850 is powered from 3.3V, not 5V

Sinric Pro App Temperature Sensor

  1. Please refer to our Troubleshooting page for more details.

This document is open source. See a typo? Please create an issue