Created
January 7, 2014 05:19
-
-
Save Resseguie/8294929 to your computer and use it in GitHub Desktop.
Attempting to send analog data from Spark Core to Thingspeak. (Note: Something still not fully working. First post works, then it hangs.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ThingSpeak Settings | |
char thingSpeakAddress[] = "api.thingspeak.com"; | |
String writeAPIKey = "THINGSPEAK_WRITE_API"; | |
const unsigned int updateThingSpeakInterval = 30000; | |
unsigned long lastConnectionTime = 0; | |
bool lastConnected = false; | |
int failedCounter = 0; | |
TCPClient client; | |
void setup() | |
{ | |
Serial.begin(9600); | |
delay(1000); | |
} | |
void loop() | |
{ | |
// Read value from Analog Input Pin 0 | |
String analogPin0 = String(analogRead(A0), (unsigned char) DEC); | |
// Print Update Response to Serial Monitor | |
if (client.available()) | |
{ | |
char c = client.read(); | |
Serial.print(c); | |
} | |
// Disconnect from ThingSpeak | |
if (!client.connected() && lastConnected) | |
{ | |
Serial.println("...disconnected"); | |
Serial.println(); | |
client.stop(); | |
} | |
// Update ThingSpeak | |
if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) | |
{ | |
updateThingSpeak("field1="+analogPin0); | |
} | |
lastConnected = client.connected(); | |
} | |
void updateThingSpeak(String tsData) | |
{ | |
if (client.connect(thingSpeakAddress, 80)) | |
{ | |
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(); | |
} | |
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