written on Nov 03, 2011
I want to log data from the Arduino to my root server using HTTP. The Arduino Ethershield makes this really simple.
In the Makefile (see older blogpost this LIBS need to be loaded:
LIBS = Ethernet Ethernet/utility String SPI
First version of my HTTP client on Arduino:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };
byte ip[] = { 192,168,1, 42 };
byte gateway[] = { 192, 168, 1, 1};
byte subnet[] = { 255, 255, 255, 0 };
byte server[] = { 192, 168, 1, 2 };
// initialize the library instance:
Client client(server, 80);
const int postingInterval = 9000; // delay between updates
long lastConnectionTime = 0; // last time connected to the server
boolean lastConnected = false; // state of the connection
long counter = 1;
String txtMsg="";
void sendData() {
if (client.connect()) {
Serial.println("connecting...");
client.print("POST /input/ HTTP/1.1\n");
client.print("Host: HOSTNAME\n");
client.print("X-ApiKey: RANDOM_API_KEY\n");
client.println("User-Agent: Arduino");
client.println("Accept: text/html");
client.print("Content-Length: ");
client.println(txtMsg.length(), DEC);
client.print("Content-Type: text/json\n");
client.println("Connection: close\n");
client.println(txtMsg);
lastConnectionTime = millis();
counter += 1;
Serial.println("sent...");
}
else {
Serial.println("connection failed");
delay(1000);
}
}
void setup()
{
// start the Ethernet connection:
Ethernet.begin(mac, ip);
Serial.begin(9600);
// delay for the ethernet to get up
delay(1000);
}
void loop()
{
// get the sensor data (using the sensor is the next step -- atm no real data)
int sensorReading = 42;
if(millis() - lastConnectionTime > postingInterval) {
// disconnect old client
Serial.println();
Serial.println("disconnecting.");
client.stop();
delay(1000);
// the JSON message
txtMsg = "[ value=";
txtMsg += sensorReading;
txtMsg += ", counter=";
txtMsg += counter;
txtMsg += "]";
sendData();
}
lastConnected = client.connected();
}