Hi, have put together some firmware (definitely a kludge) for sending sensor values to ThingSpeak. I’ve never attempted something like this before, having previously only tinkered with Arduino.
I have drawn on the post on this forum regarding Xively for code, as well as the API documentation for ThingSpeak regarding interfacing from an Arduino. After having put this together yesterday, i found another thread on this forum regarding POST commands and HTTP i think from memory which seemed to be doing something similar.
I uploaded the code to my Core last night and it was certainly able to connect to ThingSpeak, though i haven’t been able to successfully get any data uploaded. One problem i suspect is not having the length() command available to determine the length of the data packet to be uploaded. I had a guess at including the number 4 instead?!
There seem to be quite a few people interested in doing something like this, so no doubt a common method will evolve.
Interested in thoughts.
Chatty
#define writeAPIkey "<API Key here>"
#define CHANNEL_ID "<Channel ID here>"
int LED = D0;
int i = 0;
TCPClient client;
int LDR = A0;
int lastUp = 0;
int status = 0;
void setup() {
pinMode(LED, OUTPUT);
pinMode(LDR, INPUT);
}
void loop() {
if(millis()-lastUp>10000){
LDR = analogRead(A0);
lastUp = millis();
ThingSpeakUpdate(LDR);
}
}
void ThingSpeakUpdate(int LDR) {
if(client.connect("api.thingspeak.com", 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: ");
client.print(writeAPIkey);
client.print("Content-Type: application/x-www-form-urlencoded\n");
// sheer guess here at how to tell ThingSpeak what length to expect
client.print("Content-Length: 4\n");
client.print(LDR);
client.println();
// signals that you have successfully connected
ledStatus(2, 500);
// check for a response from ThingSpeak.
// A successfull connection will return the channel ID (4 digit number),
// a failure will return 0
status = client.available();
if(status >= 1){
// status is a value greater than the failure
ledStatus(6, 100);
}
else{
// status is equal to the failure response
ledStatus(3, 250);
}
}
else{
//failed to connect
ledStatus(3, 1000);
}
if(!client.connected()){
client.stop();
}
client.flush();
client.stop();
}
void ledStatus(int x, int t){
for (int j = 0; j <= x; j++){
digitalWrite(LED, HIGH);
delay(t);
digitalWrite(LED, LOW);
delay(t);
}
}