Ubidots Community

ESP32 arduino mutiple ds18b20

Hi

I got this sketch for two DS18B20 sensors for esp32-wroom-32ue. It deliver temperatures from all sensors in terminal window, it compilies with no errors but i can’t figure out why both sensors do not publish temperatures to ubidots.com

// INCLUDE LIBRARIES
#include <DallasTemperature.h>
#include <OneWire.h>
#include <WiFi.h>
#include <PubSubClient.h>

#define WIFISSID "Flat 9"
#define PASSWORD "CxDkE9VGQScP"
#define TOKEN "xxxxxxxxxxxxxxxxxxxx" // Ubidots Token

// DEFINe CONSTANTS
#define MQTT_CLIENT_NAME "AmroKhalifa2020"
#define Pin D4int temp;
#define ONE_WIRE_BUS 4 // set pin GPIO 4 as sensors

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

const char * VARIABLE_LABEL_1 = "Temp1"; // Assing the variable label
const char * VARIABLE_LABEL_2 = "Temp2"; // Assign the variable label
const char * DEVICE_LABEL = "Temperature Project"; // Assig the device label

char mqttBroker[]  = "industrial.ubidots.com/app/dashboards/603e6ac41d84727f27164411";
char payload[300];
char topic[150];

char str_Temp1[10];
char str_Temp2[10];

WiFiClient ubidots;
PubSubClient client(ubidots);

void callback(char* topic, byte* payload, unsigned int length) {
  char p[length + 1];
  memcpy(p, payload, length);
  p[length] = NULL;
  String message(p);
  Serial.write(payload, length);
  Serial.println(topic);
}

void reconnect() {
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");

// Attempt to connect
    if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
      Serial.println("Connected");
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 2 seconds");
      delay(2000); //wait 2 seconds before retrying
    }
  }
}

void setup() {
  Serial.begin(115200);
  sensors.begin();

  WiFi.begin(WIFISSID, PASSWORD);
  Serial.println();
  Serial.print("Wait for WiFi...");

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi Connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  client.setServer(mqttBroker, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }

  sensors.requestTemperatures();
  float Temp1 = sensors.getTempCByIndex(0);
  float Temp2 = sensors.getTempCByIndex(1);
  
  dtostrf(Temp1, 4, 2, str_Temp1);
  dtostrf(Temp2, 4, 2, str_Temp2);
  
  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
  sprintf(payload, "%s", ""); 
  sprintf(payload, "{\"%s\": %s,", VARIABLE_LABEL_1, str_Temp1); // Adds the variable label
  sprintf(payload, "%s\"%s\": %s,", payload, VARIABLE_LABEL_2, str_Temp2); // Adds the variable label
  
  /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/


  sprintf(payload, "%s {\"value\": %s}}", payload, str_Temp1); // Adds the value
  sprintf(payload, "%s {\"value\": %s}}", payload, str_Temp2); // Adds the value 
  Serial.println("Publishing data to Ubidots Cloud");
  Serial.print("Temp1 = ");
  Serial.println(Temp1);
  Serial.print("Temp2 = ");
  Serial.println(Temp2);
  client.publish(topic, payload);
  client.loop();
  delay(5000);
}

char mqttBroker[] = “industrial.api.ubidots.com”; ********

Hello @amrokhalifa,

Can you please print the topic and the payload to make sure they’re valid and according to what’s expected by the MQTT broker.
For the time being, note that the labels, both of Devices or Variables, must be all lowercase and can only contain alphanumeric characters, dashes and underscores. This means that you should avoid white-spaces like the one in your DEVICE_LABEL variable.

-Sebastian

Hi Sebastian

There is an error with uploading a picture of my serial monitor, can i send it to u in any other way.
However, it reads and displays the temperature measurements on the serial monitor. It also says
“Attempting MQTT connection…
Connected”
“Publishing data to Ubidots Cloud” as well as both temp1 and temp2

But when i opened my ubidots i couldn’t find anything.
Please dont be hard at me, i am a beginner in it.

Thank you very much

Hi @amrokhalifa

Can you print the topic and payload your building in the code to the serial monitor and then, if you still have issues uploading the picture, simply copy and paste both of then here to check them up?
To do so, use the below lines and include them in your code just before calling the client.publish() method.

Serial.println(topic);
Serial.println(payload);

Thank you.

Hi
I printed the topic and payload but i still cannot see the data on ubidots.
I have a question regarding the ubidots account, should i create anything on there or it will create the variables automatically ?

Thank you

Notice that your payload does not fit the expected JSON structure that you may reference in our docs. It should looks like as follows:

{"VARIABLE-LABEL_1": {"value":VALUE, "context":{"KEY":VALUE}}, ··· , "VARIABLE-LABEL_N": {"value":VALUE, "context":{"KEY": VALUE}}}

UPDATE: Here’s simpler structure yet valid. This works only to send the values.

{"VARIABLE-LABEL_1": VALUE, ··· , "VARIABLE-LABEL_N": VALUE}

Variables are created automatically, just fix your payload and everything should go on the wheels.

All the best

Hi Jota
Does it look like this? i tried it but there is an error

sprintf(payload, {“VARIABLE-LABEL_1”: {“value”:VALUE, “context”:{“KEY”:VALUE}}, “VARIABLE-LABEL_2”: {“value”:VALUE, “context”:{“KEY”: VALUE}}};

Hello @amrokhalifa,

This is the code to publish your 2 temperatures variables to Ubidots correctly. If everything goes as expected, you should see a new device in the Devices section

// INCLUDE LIBRARIES
#include <DallasTemperature.h>
#include <OneWire.h>
#include <WiFi.h>
#include <PubSubClient.h>

#define WIFISSID "Flat 9"
#define PASSWORD "CxDkE9VGQScP"
#define TOKEN "xxxxxxxxxxxxxxxxxxxx" // Ubidots Token

// DEFINe CONSTANTS
#define MQTT_CLIENT_NAME "AmroKhalifa2020"
#define Pin D4int temp;
#define ONE_WIRE_BUS 4 // set pin GPIO 4 as sensors

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

const char *VARIABLE_LABEL_1 = "temp1";                 // Assign the variable label
const char *VARIABLE_LABEL_2 = "temp2";                 // Assign the variable label
const char *DEVICE_LABEL = "temperature_project";   // Assign the device label

char mqttBroker[] = "industrial.api.ubidots.com";
char payload[300];
char topic[150];

char str_Temp1[10];
char str_Temp2[10];

WiFiClient ubidots;
PubSubClient client(ubidots);

void callback(char *topic, byte *payload, unsigned int length)
{
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;
    String message(p);
    Serial.write(payload, length);
    Serial.println(topic);
}

void reconnect()
{
    while (!client.connected())
    {
        Serial.println("Attempting MQTT connection...");

        // Attempt to connect
        if (client.connect(MQTT_CLIENT_NAME, TOKEN, ""))
        {
            Serial.println("Connected");
        }
        else
        {
            Serial.print("Failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 2 seconds");
            delay(2000); //wait 2 seconds before retrying
        }
    }
}

void setup()
{
    Serial.begin(115200);
    sensors.begin();

    WiFi.begin(WIFISSID, PASSWORD);
    Serial.println();
    Serial.print("Wait for WiFi...");

    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(500);
    }

    Serial.println("");
    Serial.println("WiFi Connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    client.setServer(mqttBroker, 1883);
    client.setCallback(callback);

    // Builds the topic. As it won't change, it can be done in the Seyup function
    sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
}

void loop()
{
    if (!client.connected())
    {
        reconnect();
    }

    sensors.requestTemperatures();
    float Temp1 = sensors.getTempCByIndex(0);
    float Temp2 = sensors.getTempCByIndex(1);

    /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
    dtostrf(Temp1, 4, 2, str_Temp1);
    dtostrf(Temp2, 4, 2, str_Temp2);

    sprintf(payload, "%s", "");                                                 // Cleand the payload
    sprintf(payload, "{\"%s\": %s,", VARIABLE_LABEL_1, str_Temp1);              // Adds the variable label 1 and its value
    sprintf(payload, "%s\"%s\": %s}", payload, VARIABLE_LABEL_2, str_Temp2);    // Adds the variable label 2 and its value

    Serial.print("Temp1 = ");
    Serial.println(Temp1);
    Serial.print("Temp2 = ");
    Serial.println(Temp2);
    Serial.println("Publishing data to Ubidots Cloud");
    Serial.println(payload);
    client.publish(topic, payload);
    client.loop();
    delay(5000);
}

I used the below article as reference

Best,

–David