Hi experts,
Apologies for a beginner stupid question if it turns out to be that way.
I've been tinkering with Arduino since a while, but not an expert programmer. I'm trying to upload some sensor data to Thingspeak via the Aarduino IDE, but I can't figure out whether data is being sent out or not because I don't see anything on Thingspeak. Current setup is as below:
- ESP32 module in Arduino IDE v1.8.12
- On Thinkspeak, I have a channel by the name ESP32_Random where I've defined 3 fields.
- Generating some random numbers and trying to upload them to Thingspeak. Once random numbers are seen on Thingspeak, I could add sensor data as well
So below is the source code. On the serial monitor it appears that data is being uploaded to the server, but I don't see it on my Thingspeak channel visualisation. I used my mobile phone as a WiFi Hotspot, but without the mobile data connection, and I could see Connection Error on Serial Monitor, indicating that the HTTP request is being handled correctly in the code. But still no luck with seeing the data on my Thingspeak channel. Any idea what might be going wrong?
Also in the below code, is there a way to print the response code from the server as well? That would also help me confirm whether the data was sent out correctly or not.
Thanks so much for your help.
#include <WiFi.h>
String apiKey = "XXXXXXXXXXXXXXXXXX"; // Enter your Write API key from ThingSpeak
String answer = "0";
const char *ssid = "MyWiFi"; // replace with your wifi ssid and wpa2 key
const char *pass = "MyWiFi";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
int h = 0;
float t =0;
float p = 0;
h = random(100);
t = random(85);
p = random(2000); //changing temperature parameter to celsius
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr += "&field2=";
postStr += String(p);
postStr += "&field3=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.println( postStr );
Serial.print("Pres: ");
Serial.println(p);
Serial.print("Temp:");
Serial.print(t);
Serial.println(" C");
Serial.print("Hum: ");
Serial.println(h);
Serial.println("%. Send to Thingspeak.");
}
else
{
Serial.println("Connection Failed");
}
client.stop();
Serial.println("Waiting...");
delay(20000);
}