hi guys,
this project is at it's very start, the end result should be a network controlled Boiler (and maybe other devices in the future) with some advanced features.
i'm currently trying to get the basic functions to work before i start adding advanced ones.
the current setup is an arduino MEGA with an Ethernet Shield and a LED on pin 2 for testing.
the problem is turning the LED off. turning it on works fine, but in order to turn it off i need to click the button twice.
i looked at the HTTP requests via serial monitor and it seems that the LED changes only when the referrer is the "OFF" page. so when the LED is ON, one click brings up a page that seems like the "ON" page but has the "OFF" page's URL, only then the (second) button click will turn the LED off.
i suspect it has more to do with the HTML part then the Arduino code because that's the part i'm least familiar with (learning as i go) but i'm not sure.
what do you think?
thanks in advance!
my sketch:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,123,223);
EthernetServer server(12345);
String HTTP_req;
boolean LED_status = false;
void setup()
{
Ethernet.begin(mac, ip);
server.begin();
Serial.begin(9600);
pinMode(2, OUTPUT);
}
void loop()
{
EthernetClient client = server.available();
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
HTTP_req += c;
if (c == '\n' && currentLineIsBlank) {
Toggle();
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head>");
client.println("<title>Arduino Boiler Control</title>");
client.println("</head>");
client.println("<body>");
client.println("<p>Click to switch Boiler on and off.</p>");
Button(client);
client.println("</form>");
if (LED_status){
client.println("<h1>Boiler is ON</h1>");
} else client.println("<h1>Boiler is OFF</h1>");
client.println("</body>");
client.println("</html>");
Serial.print(HTTP_req);
HTTP_req = "";
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
client.stop();
}
}
void Toggle(){
if (HTTP_req.indexOf("ON?") > -1) {
LED_status = true;
digitalWrite(2, HIGH);
}
else if (HTTP_req.indexOf("OFF?") > -1){
LED_status = false;
digitalWrite(2, LOW);
}
}
void Button(EthernetClient cl)
{
if (LED_status) {
cl.println("<form method=\"get\" action=\"/OFF\">");
cl.println(" <button type=\"submit\">Turn OFF</button>");
}
else {
cl.println("<form method=\"get\" action=\"/ON\">");
cl.println(" <button type=\"submit\">Turn ON</button>");
}
}