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:

1
2
3
// Start up the library
sensors.begin();
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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];
  dtostrf(fTemp,5,3,cTemp);    
  mosq.publish(topic,cTemp);
  Serial.println(cTemp);
}

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 code is available on my GitHub Page

Add a Comment

Your email address will not be published. Required fields are marked *