I am unable to connect to thingspeak server
Latest activity Edit by Christopher Stapels
on 8 Apr 2024
#include <WiFiS3.h>
#define LDR_PIN A0 // LDR sensor pin
#define WIFI_SSID "Nahi Chalega"
#define WIFI_PASSWORD "12234556889"
#define THINGSPEAK_HOST "api.thingspeak.com"
#define THINGSPEAK_API_KEY "xxxxxxxxxxxxxxxx" // Replace YOUR_API_KEY with your ThingSpeak Write API key
#define CHANNEL_ID "2498369" // Replace YOUR_CHANNEL_ID with your ThingSpeak channel ID
WiFiSSLClient client;
void setup() {
Serial.begin(9600);
connectWiFi();
}
void loop() {
int ldrValue = analogRead(LDR_PIN); // Read LDR sensor value
Serial.print("LDR Sensor Value: ");
Serial.println(ldrValue);
sendToThingSpeak(ldrValue);
delay(2000); // Send data every 20 seconds
}
void connectWiFi() {
Serial.println("Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
void sendToThingSpeak(int value) {
if (client.connect(THINGSPEAK_HOST, 80)) {
String data = "field1=" + String(value);
String request = "POST /update HTTP/1.1\nHost: " + String(THINGSPEAK_HOST) + "\nConnection: close\nX-THINGSPEAKAPIKEY: " + String(THINGSPEAK_API_KEY) + "\nContent-Type: application/x-www-form-urlencoded\nContent-Length: " + String(data.length()) + "\n\n" + data;
client.print(request);
Serial.println("Data sent to ThingSpeak!");
} else {
Serial.println("Failed to connect to ThingSpeak!");
}
client.stop();
}
1 Comment
Time DescendingI recommend using the ThingSpeak library for arduino and particle. It will take care of a lot of these issues for you.
Do you have a free account? If so you are posting way too fast to ThingSpeak.
delay(2000); // Send data every 20 seconds
This is actualy not 20 seconds, its 2 seconds as written. you might consider
delay(20000); / Send data every 20 seconds
If you slam the ThingSpeak server, you may get blocked.
If you are sticking with this code, id consider outputting your POST string to the serial monitor to make sure it is formatted correctly. Or switch to a GET, since the syntax is easier.
Can you tell us anything else about your project? We really like to hear how people are using ThingSpeak.
Sign in to participate