Hi everyone
I'm trying to use the sketch below to test sending data out to ThingsSpeak using the arduino ethernet shield, but for some reason this sketch seems to "hang" after running once. The serial output that I get is:
Connecting to the internet via ethernet...
(an IP number here...)
Temperature: 15
1=15
Connected to thingspeak.com
1=15
Fields sent sent to www.thingspeak.com
I've looked at this sketch over and over and over and I can't seem to find what the problem is. Does anyone have any suggestions of what I could modify to make it send data continuously every ~60sec? I think that I'm almost there, but I can't seem to find the trouble line(s)... ![]()
#include <SPI.h>
#include <Ethernet.h>
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "XXXXXX"; // Add your Thingspeak API key here
EthernetClient client;
const int SETDELAY = 60 * 1000;
int status;
int failedConnectionAttempCounter;
void setup()
{
Serial.begin(9600);
Serial.println();
connectToInternet();
}
void connectToInternet()
{
if (client.connected())
{
client.stop();
}
Serial.println("Connecting to the internet via ethernet...");
byte mac[] = { XXXXXXXXXXX }; // Must be unique on local network
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore
for(;;){
;
}
}
Serial.println(Ethernet.localIP());
}
void loop()
{
Serial.println("\n");
ReportTemperatureToSerialOut();
ReportTemperatureToThingspeak();
}
void ReportTemperatureToSerialOut()
{
Serial.print("Temperature: ");
Serial.println("15");
}
void ReportTemperatureToThingspeak()
{
// Use short field names i.e. 1 instead of field1
String fields = "1=15";
Serial.println(fields);
if (client.connect(thingSpeakAddress, 80))
{
Serial.println("Connected to thingspeak.com");
// Create HTTP POST Data
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: XXXXXXXXXXX\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(fields.length());
client.print("\n\n");
client.print(fields);
Serial.print(fields);
Serial.print("\n");
Serial.println("Fields sent sent to www.thingspeak.com");
delay(SETDELAY);
}
else
{
Serial.println("Connection to thingSpeak Failed");
Serial.println();
failedConnectionAttempCounter++;
// Re-start the ethernet connection after three failed connection attempts
if (failedConnectionAttempCounter > 3 )
{
Serial.println("Re-starting the ethernet connection...");
connectToInternet();
failedConnectionAttempCounter = 0;
}
}
}