Thursday, August 4, 2011

Ardunio + Ethernet shield

After I received the ethernet shield, my first task was it to figure out how to monitor the temperature in my office over the network and possible in a way, which allows me to store this result in a database.

So this got me thinking, JSON is the way togo.

  • easy to create
  • easy to read
  • possible to be understood without an interpreter
  • very lightweight
  • everybody uses it
So let's see how the code would look for the arduino


#include <spi.h>
#include <ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1, 2 };

Server server(80);

void setup()
{
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
}

void loop()
{
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println();

// output the value of each analog input pin


//read twice to improve precission
float voltage = analogRead(0) * 5.0;
voltage = analogRead(0) * 5.0;

voltage /= 1024.0;

float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;

client.print("sensor {");

client.print("temperature_voltage:");
client.print(voltage);
client.print(",");


client.print("temperature_celsius:");


client.print(temperatureC);
client.print(",");

client.print("temperature_fahrenheit:");

client.print(temperatureF);
client.print("}");


break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}


now this was rather simple and results in the following json string on port 80 of the arduino address


sensor {temperature_voltage:0.74,temperature_celsius:24.22,temperature_fahrenheit:75.59}


Now back to my actual project, trying to monitor the PH value and ammonia value with an arduino and adjust the ph, if needed...

No comments:

Post a Comment