Multiple temperature sensors on the ESP8266

The DS18b20 is a great temperature sensor. It seems to be fairly accurate, comes in a small package and uses a one-wire protocol which means you can daisy chain multiple sensors together.

There's plenty of information about the one-wire protocol and how to run them in parasite mode elsewhere on the internet, so I won't go into details here. What I couldn't find though was an Arduino sketch that allowed me to dynamically add extra sensors as I wanted.

My use-case was that I wanted to have my living room and fish tank temperatures reporting the temperature to different MQTT topics, but from the same ESP8266.

In my Arduino sketch I'm importing the DallasTemperature and OneWire libraries. Then at setup I count how many devices are connected to my designated GPIO pin like so:

  // Start up the library
  numSensors = sensors.getDeviceCount();

Then, once I know how many sensors there are, I can loop through them and query each device for the temperature and publish it to a MQTT Topic:

  sensors.requestTemperatures(); // Send the command to get temperatures
  for (int i = 0; i < numSensors; i++) {
    const char* topicHome = "hab/livingroom/temperature/";
    String sInstance = String(i);
    const char* instance = sInstance.c_str();
    char topic[100];
    strcpy(topic, topicHome);
    strcat(topic, instance);
    float fTemp = sensors.getTempCByIndex(i);
    char cTemp[5];

I'm also publishing the internal voltage of the ESP8266 to keep tabs on the battery when power isn't available, which you'll notice in the full code. This means three updates are published to the MQTT server every minute

The full sketch is attached below:

MQTT_DS18b20_Multi_Web.ino (2.28 kb)

Add comment