When I use Ubidots.h I can't use analogRead

Hey guys! I have a weird problem programming my college project: a weather station with ESP32.

Context:
I’m using a LDR as a UV index sensor (I know that’s not right but we can’t afford that sensor).

So, I’m using a ESP32 with Arduino and when I try to read the value given by the LDR it shows 0 on the serial monitor when I’m using “Ubidots.h”. ubidots.send() to be precise.
I’ll show you the code and the serial monitor

> // IMPORTANT: Device type are only supported through HTTP
> 
> /****************************************
>  * Include Libraries
>  ****************************************/
> 
> #include "Ubidots.h"
> #include <WiFi.h> // importing all the required libraries
> #include "Arduino.h"
> #include "DHT.h"
> #include "BMP085.h"
> #include <Wire.h>
> 
> /****************************************
>   Define Instances and Constants
>  ****************************************/
> //const char* DEVICE_TYPE = "my-type";     // Edit here your device type label
> const char* WIFI_SSID = "xxxxxx";           // Put here your Wi-Fi SSID
> const char* WIFI_PASS = "xxxxx";           // Put here your Wi-Fi password
> 
> const char* UBIDOTS_TOKEN = "xxxxxxxx";  // Put here your Ubidots TOKEN
> Ubidots ubidots(UBIDOTS_TOKEN, UBI_UDP);
> 
> #define DHTPIN 5 // dht sensor is connected to D5
> #define DHTTYPE DHT11     // DHT 11
> DHT dht(DHTPIN, DHTTYPE); // initialise dht sensor
> 
> BMP085 myBarometer; // initialise pressure sensor
> 
> #define LDRPIN 0 //LDR conectado en GPIO 0
> 
> float temperature; // parameters
> float humidity;
> float pressure;
> float mbar;
> int LDR;
> float uv;
> int norte;
> int sur;
> int este;
> int oeste;
> int velocidad;
> int sensor;
> /****************************************
>   Auxiliar Functions
>  ****************************************/
>    
> void sendSensor() // function to read sensor values
> {
>   humidity = dht.readHumidity();
>   temperature = dht.readTemperature();
>   if (isnan(humidity) || isnan(temperature)) 
>   {
>     Serial.println("Failed to read from DHT sensor!");
>     return;
>   }
>   
>   pressure = myBarometer.bmp085GetPressure(myBarometer.bmp085ReadUP()); // read pressure value in pascals
>   mbar = pressure / 100; // convert pascals to millibar (millibar = hectopascales)
>   
> 
>   LDR = analogRead(LDRPIN);
>   Serial.println(LDR);
>   
>   uv= map(LDR,0,4095,0,11);
>   
>   //LDR= 5;
>   norte=1;
>   sur=0;
>   este=0;
>   oeste=0;
>   velocidad=15;
>   
>   ubidots.add("Temperatura", temperature);  // Change for your variable name
>   ubidots.add("Humedad", humidity);
>   ubidots.add("Presion", mbar);
>   ubidots.add("Indice UV", uv);
>   ubidots.add("Norte", norte);
>   ubidots.add("Sur", sur);
>   ubidots.add("Este", este);
>   ubidots.add("Oeste", oeste);
>   ubidots.add("Velocidad Viento", velocidad);
> }
> 
> /****************************************
>   Main Functions
>  ****************************************/
> 
> void setup() {
>   
>   Serial.begin(115200);
>   myBarometer.init();
>   dht.begin();
>   delay(1000);
>   ubidots.wifiConnect(WIFI_SSID, WIFI_PASS);
>   delay(1000);
> }
> 
> void loop() {
> 
>   sendSensor();
>   
>   bool bufferSent = false;
>   bufferSent = ubidots.send();  // Will send data to a device label that matches the device Id
>   
>     
>   if (bufferSent) {
>     // Do something if values were sent properly
>     Serial.println("Values sent by the device");
>     
>   }
>   delay(5000);
> }

Here’s the serial monitor

On the contrary, when I run this example code for analogRead:

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int LDR = analogRead(0);
  // print out the value you read:
  Serial.println(LDR);
  delay(1000);        // delay in between reads for stability
}

It shows this:

In conclusion, I’m clearly missing something and I can’t find out what it is. Please help me

:tired_face: :tired_face:

Hi @PaulRC ,
I hope that you’re doing great.

We’ll have a look into this with another analog sensor and make sure we find out what could be happening in your case.

Have you tried not using the map() function to check if the value continues to be 0?

We greatly appreciate on your patience.

Best regards,
Sebastián

Hi @Sebastian!
Thank you so much for replying and trying to help me, I appreciate it.
I’ve tried with and without the map() function (doesn’t work in both cases).
Moreover, I also tried commenting everything except the analogRead() part, the ubidots.add() AND the ubidots.send(). In that case it doesn’t read anything, still sent a 0.

Which is why I believe that something’s odd with the ubidots.send() and the analogRead() function.

I look forward to your reply.

Paul

executive summary: Try using other pins like analogRead(32) when combining analogRead with WiFi on ESP32. I got it working from this pin to ubidots.

Hi Paul,
just changed my “running system” and at least I could reproduce your error. I connected an LDR with resistor to GIOP 0 = Pin 25 of the ESP32, defined an int pauls_sensor, tested reading normal values, but with ubidots publishing I only get 0 there. Publishing the variable as a constant value to ubidots works fine, but not as reading this variable from analog input on pin 25.

void read_pauls_sensor(){
//pauls_sensor = analogRead(0);  //pin 25 on ESP32 defined as input
pauls_sensor = 123;  //this works, publishing 123 to ubidots
Serial.print("pauls_sensor: ");
Serial.println(pauls_sensor);  //0 with ubidots // normal different values without ubidots
}

and in the loop

read_pauls_sensor();
ubidots.add("pauls_sensor", pauls_sensor);

In my case I use cheap Arduino Nanos and displays on the sensors and they just communicate their values to the ESP32. But in the future I plan to use analog inputs too.
0
123

This is probably not an ubidots issue, but there may be a problem with several pins on ESP32 using analog read and WIFI (wifi.h library?) together. Give others pins / GIOPs a try.
32 or 36 maybe.

Heureka - 32 seems to work, it uploads values.
update_showing_values
Sun is down in Tokyo so no watts coming in, but it is showing random data on the analog read.
wifi_with_analog_read

1 Like

Thank u so much!! it worked !!
That was the problem. It was a ESP32 problem, not a Ubidots problem. I’m sorry for that.
Here’s a glimpse of my project

With that problem solved, I used too a joystick for wind direction and velocity.
I’m so glad. Thank u again, all of you :heart:

3 Likes

Hi, I got some error when I try to login .Can I get the solve for this problem?

Hello @Siri

I hope this message finds you well.

Could you please show me which error are you watching when you try to login? Additionally, tell me the username of your account.

Alejandro

Hii,
“Ubidots API health check failed. HTTP response code: 404
Ubidots API is not operational. Retrying…”
This is the error I am getting when I run the code in Arduino IDE.
Can u plz resolve it!

Hello Siri,

Please show me your Arduino code to check it.

#include <WiFi.h>
#include <HTTPClient.h>
#include <arduinoFFT.h>

const char* ssid = “xxx”;
const char* password = “yyy”;
const char* ubidots_Token = “abc”;
const char* deviceLabel = “”;
const char* variableLabel = “”;
const int SENSOR_PIN = 32;
const int SAMPLES = 256;
const double SAMPLING_FREQUENCY = 1000;

ArduinoFFT FFT = ArduinoFFT();
unsigned int samplingPeriodUs;
double vReal[SAMPLES];
double vImag[SAMPLES];

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println(“Connecting to WiFi…”);
}
Serial.print("Connected to WiFi. IP address: ");
Serial.println(WiFi.localIP());
samplingPeriodUs = round(1000000 * (1.0 / SAMPLING_FREQUENCY));
}

void loop() {
if (checkUbidotsHealth()) {
for (int i = 0; i < SAMPLES; i++) {
unsigned long microseconds = micros();
vReal[i] = analogRead(SENSOR_PIN);
vImag[i] = 0;
while (micros() - microseconds < samplingPeriodUs) { }
}
FFT.windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.complexToMagnitude(vReal, vImag, SAMPLES);
sendToUbidots(vReal, SAMPLES);
} else {
Serial.println(“Ubidots API is not operational. Retrying…”);
}
delay(300000); // Delay for 5 minutes between checks
}

bool checkUbidotsHealth() {
HTTPClient http;
http.begin(“https://industrial.api.ubidots.com/api/v1.6/health/status/”);
http.addHeader(“X-Auth-Token”, ubidots_Token); // Added token for API check
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
Serial.println(“Ubidots API is operational.”);
http.end();
return true;
} else {
Serial.print("Ubidots API health check failed. HTTP response code: ");
Serial.println(httpResponseCode);
http.end();
return false;
}
}

void sendToUbidots(double* fftData, int length) {
HTTPClient http;
String url = “https://industrial.api.ubidots.com/api/v1.6/devices/” + String(deviceLabel) + “/” + String(variableLabel) + “/values”;

http.begin(url);
http.addHeader(“Content-Type”, “application/json”);
http.addHeader(“X-Auth-Token”, ubidots_Token);

String payload = “{"” + String(variableLabel) + “":[”;
for (int i = 0; i < length / 2; i++) { // Only sending half the FFT data (real part)
double frequency = i * (SAMPLING_FREQUENCY / length);
payload += “{"context":{"frequency":” + String(frequency, 2) + “},"value":” + String(fftData[i], 2) + “}”;
if (i < (length / 2) - 1) payload += “,”;
}
payload += “]}”;

Serial.print("Payload: ");
Serial.println(payload);

int attempt = 0;
int maxRetries = 5;
int baseWaitTime = 30;

while (attempt < maxRetries) {
int httpResponseCode = http.POST(payload);

if (httpResponseCode == 429) {
  int waitTime = baseWaitTime * (1 << attempt);  // Exponential backoff
  Serial.print("Rate limit exceeded. Waiting for ");
  Serial.print(waitTime);
  Serial.println(" seconds before retrying...");
  delay(waitTime * 1000);
  attempt++;
} else if (httpResponseCode > 0) {
  String response = http.getString();
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
  Serial.println("Response: ");
  Serial.println(response);
  break;
} else {
  Serial.print("Error sending POST request: ");
  Serial.println(httpResponseCode);
  attempt++;
  int waitTime = baseWaitTime * (1 << attempt);  // Exponential backoff
  Serial.print("Retrying in ");
  Serial.print(waitTime);
  Serial.println(" seconds...");
  delay(waitTime * 1000);
}

}

if (attempt == maxRetries) {
Serial.println(“Max retries exceeded. Data was not sent.”);
}

http.end();
}
Can plz go through it and let me know

Did you intentionally delete this information to protect your private data? If you’d prefer, feel free to send me a direct message with the details, as I need the full information to assist you further.

image