Skip to content

Instantly share code, notes, and snippets.

@Resseguie
Created January 7, 2014 17:24
Show Gist options
  • Save Resseguie/8302903 to your computer and use it in GitHub Desktop.
Save Resseguie/8302903 to your computer and use it in GitHub Desktop.
Oversimplified method of sending ThingSpeak updates from Spark Core. (Not really recommended for real world use.) This connects and sends data successfully several times, but eventually something hangs and it stops updating.
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "THINGSPEAK_WRITE_KEY";
const unsigned int updateThingSpeakInterval = 30000;
// Variable Setup
unsigned long lastConnectionTime = 0;
// Initialize TCP Client
TCPClient client;
void setup()
{
// Start Serial for debugging on the Serial Monitor
Serial.begin(9600);
delay(1000);
Serial.println("Setup complete");
}
void loop()
{
// Read value from Analog Input Pin 0
String analogPin0 = String(analogRead(A0), (unsigned char) DEC);
// Update ThingSpeak
if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
{
updateThingSpeak("field1="+analogPin0);
}else{
delay(500);
}
}
void updateThingSpeak(String tsData)
{
if (client.connect(thingSpeakAddress, 80))
{
Serial.println("Sending TS update: "+tsData);
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
lastConnectionTime = millis();
delay(2000);
// Just ignore return info for now
Serial.println("Disconnecting");
client.flush();
client.stop();
}
else
{
Serial.println("Connection to ThingSpeak Failed--disconnecting");
client.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment