[FOR REVIEW] Send data to ubidots every 5 minutes

i try to modify the project oil level monitoring project , i want the esp32 send the distance data every 5 minute and dht sensor data for every 1 minute

  if (millis() - (1*60*1000UL) > lastHT)  // once every 1 minutes
  { 
   lastHT= millis();
    sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s,",  VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
    sprintf(payload, "%s\"%s\": %s}", payload,VARIABLE_LABEL_3, str_TempSensor);
  }
   if (millis() - (5*60*1000UL) > lastSE)  // once every 5 minutes
  {
    lastSE= millis();
    sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s}",  VARIABLE_LABEL_1, str_sensor); // Adds the variable label
  }

but it keeps sending data to ubidots every second

Dear @vindobangun,

The sample code provided below show you how to manage the intervals time to trigger the action of send data. Take the code as a reference to build your own! :smiley:

unsigned long previousMillis_one = 0; // store the last time updated
unsigned long previousMillis_two = 0; // store the last time updated

long one_minute_interval = 1*60*1000UL; // interval desired (millisenconds)
long five_minutes_interval = 5*60*1000UL; // interval desired (millisenconds)

int count = 0; // test counter

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

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis_one > one_minute_interval) {
    previousMillis_one = currentMillis;
    Serial.println("One minute interval");
  } 

  if (currentMillis - previousMillis_two > five_minutes_interval) {
    previousMillis_two = currentMillis;
    Serial.println("Five minutes interval");
  } 

  /* -------------- DEBUG PURPOSE -------------- */ 
  // reset counter
  if (count >= 300) {
    count = 0; 
  }
  count++;
  Serial.println(count);
  /* ------------------------------------------- */
  delay(1000);
}

I hope this would help you!

All the best
Maria C.

if i want to send to ubidot i need to put the code in here right?

if (currentMillis - previousMillis_one > one_minute_interval) {
previousMillis_one = currentMillis;
Serial.println(“One minute interval”);
}

Dear @vindobangun,

That depends on your solution. As you mentioned above:

  • If you desire to send distance data every five minutes you should send the data in the five minutes condition:
  if (currentMillis - previousMillis_two > five_minutes_interval) {
    previousMillis_two = currentMillis;
    Serial.println("Five minutes interval");
  } 
  • If you desire to send dht data every one minute you should send the data in the one minute condition:

  if (currentMillis - previousMillis_one > one_minute_interval) {
    previousMillis_one = currentMillis;
    Serial.println("One minute interval");
  } 

I hope this would help you!

All the best,
Maria C.

do i need to put this code to every condition?

sprintf(topic, “%s%s”, “/v1.6/devices/”, DEVICE_LABEL);
sprintf(payload, “%s”, “”); // Cleans the payload

Dear @vindobangun,

The topic variable is a global constant, so it should be located out of the conditionals. The payload variable depends on the data desired to be sent and how often should be sent.

In your case:

  • Conditional to send DHT data every one minute; here you should structure the payload to build the desired data to be sent (DHT data), then handle the request to Ubidots.

  • Conditional to send distance data every five minutes; here you should structure the payload to build the desired data to be sent (distance), then handle the request to Ubidots.

I hope this clears your doubts! :smiley:

All the best,
Maria C.

i made 2 version , the first one

if (currentMillis - previousMillis_one > one_minute_interval) {
Serial.println(“Publishing values to Ubidots Cloud”);
previousMillis_one = currentMillis;
Serial.println(“One minute interval”);
sprintf(topic, “%s%s”, “/v1.6/devices/”, DEVICE_LABEL);
sprintf(payload, “%s”, “”); // Cleans the payload
sprintf(payload, “{"%s": %s,”, VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
sprintf(payload, “%s"%s": %s}”, payload,VARIABLE_LABEL_3, str_TmpSensor);
Serial.println(payload);
client.publish(topic, payload);
client.loop();
}

if (currentMillis - previousMillis_two > five_minutes_interval) {
Serial.println(“Publishing values to Ubidots Cloud”);
previousMillis_two = currentMillis;
Serial.println(“Five minutes interval”);
sprintf(topic, “%s%s”, “/v1.6/devices/”, DEVICE_LABEL);
sprintf(payload, “%s”, “”); // Cleans the payload
sprintf(payload, “{"%s": %s}”, VARIABLE_LABEL_1, str_sensor); // Adds the variable label
Serial.println(payload);
client.publish(topic, payload);
client.loop();
}

in serial monitor it looks like the data send in interval , but it didn’t actually send to ubidots

the second version

if (currentMillis - previousMillis_one > one_minute_interval) {
Serial.println(“Publishing values to Ubidots Cloud”);
previousMillis_one = currentMillis;
Serial.println(“One minute interval”);
sprintf(topic, “%s%s”, “/v1.6/devices/”, DEVICE_LABEL);
sprintf(payload, “%s”, “”); // Cleans the payload
sprintf(payload, “{"%s": %s,”, VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
sprintf(payload, “%s"%s": %s}”, payload,VARIABLE_LABEL_3, str_TmpSensor);
Serial.println(payload);

}

if (currentMillis - previousMillis_two > five_minutes_interval) {
Serial.println(“Publishing values to Ubidots Cloud”);
previousMillis_two = currentMillis;
Serial.println(“Five minutes interval”);
sprintf(topic, “%s%s”, “/v1.6/devices/”, DEVICE_LABEL);
sprintf(payload, “%s”, “”); // Cleans the payload
sprintf(payload, “{"%s": %s}”, VARIABLE_LABEL_1, str_sensor); // Adds the variable label
}

/* Publish the request to Ubidots */
client.publish(topic, payload);
client.loop();

it still send the data every second to ubidots.

Dear @vindobangun

If you you test the sample code provided above, you will note that the intervals works as should be. You just need to include the lines of code to handle the data with the platform and you should don’t have any isse.

Anyway, here is a sample test that I just build which is already tested and works how is expected. Follow it in order to build your own:


/****************************************
 * Include Libraries
 ****************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

/****************************************
 * Define Constants
 ****************************************/
namespace {
  char WIFISSID[] = "xxxxxxxxxxxx"; // Put your WifiSSID here
  char PASSWORD[] = "xxxxxxxxxxxx"; // Put your wifi password here
  const char * TOKEN = "xxxxxxxxxxxx"; // Put your Ubidots' TOKEN
  const char * MQTT_CLIENT_NAME = "xxxxxxxxxxxx"; // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; 
  const char * VARIABLE_LABEL_1 = "distance"; // Assign the variable label
  const char * VARIABLE_LABEL_2 = "humidity"; // Assign the variable label
  const char * VARIABLE_LABEL_3 = "temperature"; // Assign the variable label
  const char * DEVICE_LABEL = "esp8266"; // Assign the device label
  const char * MQTT_BROKER = "things.ubidots.com";  

}

/* Sensor's declarations */
float distance;
/* Space to store the request */
char payload[300];
char topic[150];
/* Space to store values to send */
char str_sensor[10];
char str_TempSensor[10];
char str_HumSensor[10];

unsigned long previousMillis_one = 0; // store the last time updated
unsigned long previousMillis_two = 0; // store the last time updated

long one_minute_interval = 1*60*1000UL; // interval desired (millisenconds)
long five_minutes_interval = 5*60*1000UL; // interval desired (millisenconds)

/****************************************
 * Auxiliar Functions
 ****************************************/
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() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    
    // Attemp 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");
      // Wait 2 seconds before retrying
      delay(2000);
    }
  }
}

/****************************************
 * Main Functions
 ****************************************/
void setup() {
  Serial.begin(115200);
  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(MQTT_BROKER, 1883);
  client.setCallback(callback);  
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  
  unsigned long currentMillis = millis();

  float humidity = random(0, 1000)*1.0;
  float temperature = random(0, 1000)*1.0;  
  float distance = random(0, 1000)*1.0;
  
  /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
  dtostrf(distance, 4, 2, str_sensor);
  dtostrf(humidity, 4, 2, str_HumSensor);
  dtostrf(temperature, 4, 2, str_TempSensor);

  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);

  if (currentMillis - previousMillis_one > one_minute_interval) {
    previousMillis_one = currentMillis;
    Serial.println("One minute interval");
  
    /* Building the Ubidots request */
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s}", VARIABLE_LABEL_1, str_sensor); // Adds the variable label

    Serial.println("Publishing values to Ubidots Cloud");
    Serial.print("Distance = ");
    Serial.println(distance);
    
    /* Publish the request to Ubidots */
    client.publish(topic, payload);
    client.loop();
   
  } 

  if (currentMillis - previousMillis_two > five_minutes_interval) {
    previousMillis_two = currentMillis;
    Serial.println("Five minutes interval");
    
    /* Building the Ubidots request */
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s,", VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
    sprintf(payload, "%s\"%s\": %s}", payload, VARIABLE_LABEL_3, str_TempSensor); // Adds the variable label

    /* Print the sensor reading to the Serial Monitor */
    Serial.println("Publishing values to Ubidots Cloud");
    Serial.print("Humidity = ");
    Serial.println(humidity);
    Serial.print("Temperature = ");
    Serial.println(temperature);
    
    /* Publish the request to Ubidots */
    client.publish(topic, payload);
    client.loop();
  }
  Serial.println("looping....");
  delay(1000);
}

Regards,
Maria C.

it still can’t send data to ubidots

 /****************************************
  * Include Libraries
  ****************************************/
 
 #include <PubSubClient.h>
 #include <WiFi.h>
 
 /****************************************
  * Define Constants
  ****************************************/
 namespace {
   char WIFISSID[] = "Main"; // Put your WifiSSID here
   char PASSWORD[] = "milala123"; // Put your wifi password here
   const char * TOKEN = ""; // Put your Ubidots' TOKEN
   const char * MQTT_CLIENT_NAME = "KzSf1IZSOv"; // MQTT client Name, please enter your own
alphanumeric character ASCII string; 
   const char * VARIABLE_LABEL_1 = "distance"; // Assign the variable label
   const char * VARIABLE_LABEL_2 = "humidity"; // Assign the variable label
   const char * VARIABLE_LABEL_3 = "temperature"; // Assign the variable label
   const char * DEVICE_LABEL = "tugaskp"; // Assign the device label
   const char * MQTT_BROKER = "things.ubidots.com";  
 
 }
 
 /* Sensor's declarations */
 float distance;
 /* Space to store the request */
 char payload[300];
 char topic[150];
 /* Space to store values to send */
 char str_sensor[10];
 char str_TempSensor[10];
 char str_HumSensor[10];
 
 unsigned long previousMillis_one = 0; // store the last time updated
 unsigned long previousMillis_two = 0; // store the last time updated
 
 long one_minute_interval = 1*60*1000UL; // interval desired (millisenconds)
 long five_minutes_interval = 5*60*1000UL; // interval desired (millisenconds)
 
 /****************************************
  * Auxiliar Functions
  ****************************************/
 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() {
   // Loop until we're reconnected
   while (!client.connected()) {
     Serial.println("Attempting MQTT connection...");
     
     // Attemp 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");
       // Wait 2 seconds before retrying
       delay(2000);
     }
   }
 }
 
 /****************************************
  * Main Functions
  ****************************************/
 void setup() {
   Serial.begin(115200);
   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(MQTT_BROKER, 1883);
   client.setCallback(callback);  
}

 void loop() {
   if (!client.connected()) {
     reconnect();
   }
   
   unsigned long currentMillis = millis();
 
   float humidity = random(0, 1000)*1.0;
   float temperature = random(0, 1000)*1.0;  
   float distance = random(0, 1000)*1.0;
   
   /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
   dtostrf(distance, 4, 2, str_sensor);
   dtostrf(humidity, 4, 2, str_HumSensor);
   dtostrf(temperature, 4, 2, str_TempSensor);
 
   sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
 
   if (currentMillis - previousMillis_one > one_minute_interval) {
     previousMillis_one = currentMillis;
     Serial.println("One minute interval");
   
     /* Building the Ubidots request */
     sprintf(payload, "%s", ""); // Cleans the payload
     sprintf(payload, "{\"%s\": %s}", VARIABLE_LABEL_1, str_sensor); // Adds the variable label
 
     Serial.println("Publishing values to Ubidots Cloud");
     Serial.print("Distance = ");
     Serial.println(distance);
     
     /* Publish the request to Ubidots */
     client.publish(topic, payload);
     client.loop();
    
   } 
 
   if (currentMillis - previousMillis_two > five_minutes_interval) {
     previousMillis_two = currentMillis;
     Serial.println("Five minutes interval");
     
     /* Building the Ubidots request */
     sprintf(payload, "%s", ""); // Cleans the payload
     sprintf(payload, "{\"%s\": %s,", VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
     sprintf(payload, "%s\"%s\": %s}", payload, VARIABLE_LABEL_3, str_TempSensor); // Adds the variable label
 
     /* Print the sensor reading to the Serial Monitor */
     Serial.println("Publishing values to Ubidots Cloud");
     Serial.print("Humidity = ");
     Serial.println(humidity);
     Serial.print("Temperature = ");
     Serial.println(temperature);
     
     /* Publish the request to Ubidots */
     client.publish(topic, payload);
     client.loop();
   }
   Serial.println("looping....");
   delay(1000);
 }

im also cant send data to ubidots.
Using ESP32 a a code really similar of the one mariahernandez desccribe.

/****************************************
 * Include Libraries
 ****************************************/
#include <WiFi.h>
#include <PubSubClient.h>
#include <ESPmDNS.h>

// BME280 PARAMETERS
#include <Adafruit_BME280.h>
#define I2C_SDA 21
#define I2C_SCL 22
#define BME280_ADD 0x76
#define SEALEVELPRESSURE_HPA (1026.0)
Adafruit_BME280 bme(I2C_SDA, I2C_SCL);

#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);

void displaySensorDetails(void)
{
  sensor_t sensor;
  tsl.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" lux");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" lux");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" lux");  
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void configureSensor(void)
{
/* You can also manually set the gain or enable auto-gain support */
// tsl.setGain(TSL2561_GAIN_1X);      /* No gain ... use in bright light to avoid sensor saturation */
// tsl.setGain(TSL2561_GAIN_16X);     /* 16x gain ... use in low light to boost sensitivity */
tsl.enableAutoRange(true);            /* Auto-gain ... switches automatically between 1x and 16x */
  
/* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */
   tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS);  /* medium resolution and speed   */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);  /* 16-bit data but slowest conversions */

 /* Update these values depending on what you've set above! */  
 Serial.println("------------------------------------");
 Serial.print  ("Gain:         "); Serial.println("Auto");
 Serial.print  ("Timing:       "); Serial.println("101 ms");
 Serial.println("------------------------------------");
}

#define ANALOG_PIN_0 34
#define ANALOG_PIN_1 35
#define co2Zero     40                        //calibrated CO2 0 level
int co2ppm = 0; 
int pino_sensor = 35;
int valor_sensor = 0;
int posicao;
String UV_index = "0";
String UV = "0"; 

//declare variables
  float temperature;
  float pressure;
  float altitude;
  float humidity;
  float  co2;
  float  uvindexx;
  float  light;



/****************************************
 * Define Constants
 ****************************************/
namespace {
  const char * WIFISSID = "N9124G"; // Put your WifiSSID here
  const char *  PASSWORD = "13031976"; // Put your wifi password here
  const char * TOKEN = "A1E-bpaq4yuQvKspTNWr8o29pyYZFKdAi9"; // Put your Ubidots' TOKEN
  const char * MQTT_CLIENT_NAME = "43de1354LAm"; // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; 
  const char * DEVICE_LABEL = "esp32"; // My Device Label
  const char * VARIABLE_LABEL_1 = "temperature"; // My Variable Label
  const char * VARIABLE_LABEL_2 = "humidity";
  const char * VARIABLE_LABEL_3 = "pressure"; // Assing the variable label
  const char * VARIABLE_LABEL_4 = "altitude"; // Assing the variable label
  const char * VARIABLE_LABEL_5 = "co2"; // Assing the variable label
  const char * VARIABLE_LABEL_6 = "uv"; // Assing the variable label
  const char * VARIABLE_LABEL_7 = "luz"; // Assing the variable label
  const char * MQTT_BROKER = "things.ubidots.com";  
}


/* Space to store the request */
char payload[300];
char topic[50];
/* Space to store values to send */
char str_sensor[10];
char str_tempSensor[10];
char str_humSensor[10];
char str_presSensor[10];
char str_altSensor[10];
char str_co2Sensor[10];
char str_uvSensor[10];
char str_lightSensor[10];

unsigned long previousMillis_one = 0; // store the last time updated
long one_minute_interval = 1*60*1000UL; // interval desired (millisenconds)
/****************************************
 * Auxiliar Functions
 ****************************************/
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() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    
    // Attemp 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");
      // Wait 2 seconds before retrying
      delay(2000);
    }
  }
}


/****************************************
 * Main Functions
 ****************************************/
void setup() {
  Serial.begin(9600);
 
  WiFi.begin(WIFISSID, PASSWORD);


  /* Assign the PINS as INPUT/OUTPUT */
  pinMode(ANALOG_PIN_0,INPUT);                     //MQ135 analog feed set for input
  pinMode(pino_sensor, INPUT);                      //VM30A nalog feed set for input

  
  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(MQTT_BROKER, 1883);
  client.setCallback(callback);  

}


void loop() {
  if (!client.connected()) {
    reconnect();
  }
 
  /* Reading sensors */
  
unsigned long currentMillis = millis();  

getCO2();
getValuesBME280();
int stringLength = 0; 
UV = Calcula_nivel_UV();
float uvindexx = UV.toFloat();  
getTSL2561();

 
  //* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
  dtostrf(temperature, 4, 2, str_tempSensor);
  dtostrf(humidity, 3, 2, str_humSensor);
  dtostrf(pressure, 4, 2, str_presSensor);
  dtostrf(altitude, 4, 2, str_altSensor);
  dtostrf(co2, 1, 0, str_co2Sensor);
  dtostrf(uvindexx, 1, 0, str_uvSensor);
  dtostrf(light, 1, 0, str_lightSensor);

  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);

  if (currentMillis - previousMillis_one > one_minute_interval) {
    previousMillis_one = currentMillis;
    Serial.println("One minute interval");

  sprintf(payload, "{\"");
  sprintf(payload, "%s%s\":%s", payload, VARIABLE_LABEL_1, str_tempSensor); // Adds the variable label
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_2, str_humSensor); // Adds the variable label
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_3, str_presSensor); // Adds the variable label
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_4, str_altSensor); // Adds the variable label
  sprintf(payload, "%s}", payload);
  Serial.println();  
  Serial.println(topic);
  Serial.println(payload);
  client.publish(topic, payload);
  Serial.println();  
  delay(5000);
  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
  sprintf(payload, "%s", ""); // Cleans the payload
  sprintf(payload, "{\"");
  sprintf(payload, "%s%s\":%s", payload, VARIABLE_LABEL_5, str_co2Sensor); // Adds the variable label
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_6, str_uvSensor); // Adds the variable label
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_7, str_lightSensor); // Adds the variable label
  sprintf(payload, "%s}", payload);
  Serial.println();  
  Serial.println(topic);
  Serial.println(payload);
  client.publish(topic, payload);
  Serial.println();  
  client.loop();
}
}

void  getCO2()
{
int co2now[10];                               //int array for co2 readings
int co2raw = 0;                               //int for raw value of co2
int co2comp = 0;                              //int for compensated co2 
int co2ppm = 0;                               //int for calculated ppm
int zzz = 0;                                  //int for averaging
for (int x = 0;x<10;x++){                   //samplpe co2 10x over 2 seconds
    co2now[x]=analogRead(ANALOG_PIN_0);
  }

for (int x = 0;x<10;x++){                     //add samples together
    zzz=zzz + co2now[x];  
  }
  co2raw = zzz/10;                            //divide samples by 10
  co2comp = co2raw - co2Zero;                 //get compensated value
  co2ppm = map(co2comp,0,1023,400,5000);      //map value for atmospheric levels
  Serial.print("CO2 ppm value : ");
  Serial.print(co2ppm);                      //print co2 ppm
  co2 = co2ppm;
  Serial.println(" PPM");                      //print units
  Serial.println();  
}

void getValuesBME280()
{   
   bme.begin(BME280_ADD);
  temperature = bme.readTemperature();   
  pressure = bme.readPressure() / 100.0F;   
  altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
  humidity = bme.readHumidity();
  Serial.print("Temperature = ");
  Serial.print(temperature);
  Serial.println(" ℃");
  Serial.print("Pressure = ");
  Serial.print(pressure);
  Serial.println(" hPa");
  Serial.print("Approx. Altitude = ");
  Serial.print(altitude);
  Serial.println(" m");
  Serial.print("Humidity = ");
  Serial.print(humidity);
  Serial.println(" %");
  Serial.println();  
}

String Calcula_nivel_UV()
{
  String uvindex = "0";
  int valor_sensor = 0;
  valor_sensor = analogRead(pino_sensor);
  //Calcula tensao em milivolts
  int tensao = (valor_sensor * (5.0 / 4095.0)) * 1000; //precisa checar
  
  //Compara com valores tabela UV_Index
  
  if (tensao < 50)
  {
    uvindex = "0";
  }
  else if (tensao > 50 && tensao <= 227)
  {
    uvindex = "0";
  }
  else if (tensao > 227 && tensao <= 318)
  {
    uvindex = "1";
  }
  else if (tensao > 318 && tensao <= 408)
  {
    uvindex = "2";
  }
  else if (tensao > 408 && tensao <= 503)
  {
    uvindex = "3";
  }
  else if (tensao > 503 && tensao <= 606)
  {
    uvindex = "4";
  }
  else if (tensao > 606 && tensao <= 696)
  {
    uvindex = "5";
  }
  else if (tensao > 696 && tensao <= 795)
  {
    uvindex = "6";
  }
  else if (tensao > 795 && tensao <= 881)
  {
    uvindex = "7";
  }
  else if (tensao > 881 && tensao <= 976)
  {
    uvindex = "8";
  }
  else if (tensao > 976 && tensao <= 1079)
  {
    uvindex = "9";
  }
  else if (tensao > 1079 && tensao <= 1170)
  {
    uvindex = "10";
  }
  else if (tensao > 1170)
  {
    uvindex = "11";
  }
  Serial.println(uvindex);
  Serial.println (analogRead(pino_sensor)); 
  Serial.println();
return uvindex;
}
void getTSL2561()
{
  sensors_event_t event;
  tsl.getEvent(&event);
  light = event.light;
  Serial.print(event.light); Serial.println(" lux");
  Serial.println();    
  }

Already tried set payload of all variables in one time, one by one, nothing works.
Please help appreciated.

Dear @vindobangun,

I just made a test with the sample code provided in this answer at works perfectly to me. Please, make sure that the SSID & SSIDPASSWORD are the right ones, plus your Ubidots TOKEN.

The image below shows how the variables are being sent with the intervals expected properly:

  • Distance every 1 minute

  • Temperatue & Humidity every 5 minutes

If the issue persists, I recommend you make a test using a basic example of “WebClient” which handle an HTTP request to a server. If everything works properly with the sample tested, just modify the request made to the Ubidots Server following the Ubidots API Reference.

I hope this would help you!

All the best,
Maria C.

Hello @NENAO,

To start working with the ESP32 and Ubidots you should refer to the following guide, which provides a basic example with a single variable with the reading of a pin. Once you are able to handle your data with the platform you should follow the next steps:

  1. Build the payload desired to be sent and testing sending all the variables in the same request. At this point, if you note that the variables are being created with empty values, means that one of the values sent are not supported by the Ubidots backend. For this reason, I recommend you verify the data accepted in the Ubidots REST API Reference to verify in the type of variable are the right one.
  2. Once you are able to post all the payload to Ubidots, include the intervals desired to post the data in the platform. For this, you can take as reference the following code.

I hope this would help you!

Regards,
Maria C.

it makes me confused, when i wanted to send data to ubidots every second it worked, but it didn’t worked for 1 minute or 5 minutes

Are you following exactly the code provided in this answer? Following this example exactly as it is, you should don’t have any issue getting started with it the platform!

yes i use that code and i didn’t change anything except i changed the wifissid , password, token, mqqtt_client_name, and device_label. And i put include Wifi.h since im using esp32

/****************************************
 * Include Libraries
 ****************************************/

#include <PubSubClient.h>
#include <WiFi.h>
/****************************************
 * Define Constants
 ****************************************/
namespace {
  const char * WIFISSID = "Main"; // Put your WifiSSID here
  const char *  PASSWORD = "milala123"; // Put your wifi password here
  const char * TOKEN = ""; // Put your Ubidots' TOKEN
  const char * MQTT_CLIENT_NAME = "KzSf1IZsOv"; // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; 
  const char * VARIABLE_LABEL_1 = "distance"; // Assign the variable label
  const char * VARIABLE_LABEL_2 = "humidity"; // Assign the variable label
  const char * VARIABLE_LABEL_3 = "temperature"; // Assign the variable label
  const char * DEVICE_LABEL = "tugas"; // Assign the device label
  const char * MQTT_BROKER = "things.ubidots.com";  

}

/* Sensor's declarations */
float distance;
/* Space to store the request */
char payload[300];
char topic[150];
/* Space to store values to send */
char str_sensor[10];
char str_TempSensor[10];
char str_HumSensor[10];

unsigned long previousMillis_one = 0; // store the last time updated
unsigned long previousMillis_two = 0; // store the last time updated

long one_minute_interval = 1*60*1000UL; // interval desired (millisenconds)
long five_minutes_interval = 5*60*1000UL; // interval desired (millisenconds)

/****************************************
 * Auxiliar Functions
 ****************************************/
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() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    
    // Attemp 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");
      // Wait 2 seconds before retrying
      delay(2000);
    }
  }
}

/****************************************
 * Main Functions
 ****************************************/
void setup() {
  Serial.begin(115200);
  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(MQTT_BROKER, 1883);
  client.setCallback(callback);  
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  
  unsigned long currentMillis = millis();

  float humidity = random(0, 1000)*1.0;
  float temperature = random(0, 1000)*1.0;  
  float distance = random(0, 1000)*1.0;
  
  /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
  dtostrf(distance, 4, 2, str_sensor);
  dtostrf(humidity, 4, 2, str_HumSensor);
  dtostrf(temperature, 4, 2, str_TempSensor);

  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);

  if (currentMillis - previousMillis_one > one_minute_interval) {
    previousMillis_one = currentMillis;
    Serial.println("One minute interval");
  
    /* Building the Ubidots request */
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s}", VARIABLE_LABEL_1, str_sensor); // Adds the variable label

    Serial.println("Publishing values to Ubidots Cloud");
    Serial.print("Distance = ");
    Serial.println(distance);
    
    /* Publish the request to Ubidots */
    client.publish(topic, payload);
    client.loop();
   
  } 

  if (currentMillis - previousMillis_two > five_minutes_interval) {
    previousMillis_two = currentMillis;
    Serial.println("Five minutes interval");
    
    /* Building the Ubidots request */
    sprintf(payload, "%s", ""); // Cleans the payload
    sprintf(payload, "{\"%s\": %s,", VARIABLE_LABEL_2, str_HumSensor); // Adds the variable label
    sprintf(payload, "%s\"%s\": %s}", payload, VARIABLE_LABEL_3, str_TempSensor); // Adds the variable label

    /* Print the sensor reading to the Serial Monitor */
    Serial.println("Publishing values to Ubidots Cloud");
    Serial.print("Humidity = ");
    Serial.println(humidity);
    Serial.print("Temperature = ");
    Serial.println(temperature);
    
    /* Publish the request to Ubidots */
    client.publish(topic, payload);
    client.loop();
  }
  Serial.println("looping....");
  delay(1000);
}

Dear @vindobangun,

I made the test using the ESP8266 module and works properly for me. Regrettably, I can’t ensure the right functionality of it with the ESP32.

My recommendation is to take sample code of the structure to manage the interval as the reference until building` your own sample code.

Anyway at the moment I don’t have an ESP32 with me, so once a get a chance to get the board al will make the test and I will let you know the behavior.

All the best,
Maria C.

thank you very much, please inform me when you’re done.