Go Down

Topic: My Home Automation Web Switch (Read 2845 times) previous topic - next topic

erasmudj

This is my attempt at Home Automation.
The problem is you have to manually refresh the page to get the feedback of the outputs.
When I put an auto refresh in the header the code does not work.

If anyone can help me with buttons instead of text to trigger the outputs to add a better look to the page.

I would also like to have push button inputs to trigger the corresponding outputs. This will be to switch on and off the equipment without a PC/tablet/phone.

Thanks in advance.
Thanks to zoomkat for the base code.

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x48, 0x66 }; //physical mac address
byte ip[] = { 192,168,101,201 }; // ip in lan
byte gateway[] = { 192,168,101,2 }; // internet access via router
EthernetServer server(8000); //server port
char* myStrings[]={ "Switch 1",
                    "Switch 2",
                    "Switch 3",
                    "Switch 4",
                    "Switch 5"};           
char* offStrings[]={"<a STYLE=\"background-color:red\" href=\"/?off1\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:red\" href=\"/?off2\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:red\" href=\"/?off3\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:red\" href=\"/?off4\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:red\" href=\"/?off5\" target=\"inlineframe\">"};
char* onStrings[]={ "<a STYLE=\"background-color:green\" href=\"/?on1\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:green\" href=\"/?on2\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:green\" href=\"/?on3\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:green\" href=\"/?on4\" target=\"inlineframe\">",
                    "<a STYLE=\"background-color:green\" href=\"/?on5\" target=\"inlineframe\">"};
char* offSStrings[]={"off1", "off2", "off3", "off4", "off5"};
char* onSStrings[]={"on1", "on2", "on3", "on4", "on5"};
String readString;

void setup(){

  pinMode(2, OUTPUT); //pin selected to control
  pinMode(3, OUTPUT); //pin selected to control
  pinMode(4, OUTPUT); //pin selected to control
  pinMode(5, OUTPUT); //pin selected to control
  pinMode(6, OUTPUT); //pin selected to control
  pinMode(7, OUTPUT); //pin selected to control
  //start Ethernet
  Ethernet.begin(mac, ip, gateway, gateway);
  server.begin();
    //enable serial data print
  Serial.begin(9600);
  Serial.println("server LED test 1.0"); // so I can keep track of what is loaded

}

void loop(){
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {

          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {

          Serial.println(readString); //print to serial monitor for debuging

          //now output HTML data header
             if(readString.indexOf('?') >=0) { //don't send new page
               client.println("HTTP/1.1 204 Zoomkat");
               client.println();
             //  client.println();
             }
             else {
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();
          client.println("<HTML><HEAD><TITLE>Arduino Home Automation</TITLE>");
          client.println("<meta name = 'viewport' content = 'user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width'/>");
          client.println("</HEAD><BODY>");
          client.print("<div style=\"background:white; color:green; position: absolute; margin:20px; border: grey solid 2px; padding:0 10px 4px 10px;\"><H1>Arduino button</H1>");

          client.println("<center>");
          for (int i = 0; i<5; i++){
            if (digitalRead(i+2))
             {
             client.println(offStrings[i]);
             client.println(myStrings[i]);
             client.println("</a><br /><br />"); 
             }
            else
            {
             client.println(onStrings[i]);
             client.println(myStrings[i]);
             client.println("</a><br /><br />"); 
            }
          }

          client.println("<IFRAME name=inlineframe style=\"display:none\" ></IFRAME>");
          client.println("</table></center></DIV></BODY></HTML>");
             }

          delay(1);
          //stopping client
          client.stop();

          // control arduino pin
          for (int ii = 0; ii<5; ii++){
          if(readString.indexOf(onSStrings[ii]) >0)//checks for on
            digitalWrite(ii+2, HIGH);    // set pin high
          if(readString.indexOf(offSStrings[ii]) >0)//checks for off
            digitalWrite(ii+2, LOW);    // set pin low
          }
          //clearing string for next read
          readString="";
        }
      }
    }
  }
}

zoomkat

The below code uses a frame box to enclose a status page for the arduino analog input pins. You should be able to incorporate something similar into your main control page. Note that the F() macro needs to be used on static text lines or you may have low memory issues. 

Code: [Select]

// zoomkat's meta refresh data frame test page 8/17/13
// use http://192.168.1.102:84 in your brouser for main page
// http://192.168.1.102:84/data static data page
// http://192.168.1.102:84/datastart meta refresh data page
// for use with W5100 based ethernet shields
// set the refresh rate to 0 for fastest update
// use STOP for single data updates

#include <SPI.h>
#include <Ethernet.h>

const int analogInPin0 = A0;
const int analogInPin1 = A1;
const int analogInPin2 = A2;
const int analogInPin3 = A3;
const int analogInPin4 = A4;
const int analogInPin5 = A5;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 102 }; // arduino ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port
unsigned long int x=0; //set refresh counter to 0
String readString;

//////////////////////

void setup(){
  Serial.begin(9600);
    // disable SD SPI if memory card in the uSD slot
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  server.begin();
  Serial.println(F("meta refresh data frame test 8/17/13")); // so I can keep track of what is loaded
}

void loop(){
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
         if (readString.length() < 100) {
          readString += c;
         }
        //check if HTTP request has ended
        if (c == '\n') {

          //check get atring received
          Serial.println(readString);

          //output HTML data header
          //client.println("HTTP/1.1 200 OK");
          //client.println("Content-Type: text/html");
          //client.println();
         
          client.print(F("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"));

          //generate data page
          if(readString.indexOf("data") >0) {  //checks for "data" page
            x=x+1; //page upload counter
            client.print(F("<HTML><HEAD>"));
            //meta-refresh page every 1 seconds if "datastart" page
            if(readString.indexOf("datastart") >0) client.print(F("<meta http-equiv='refresh' content='1'>"));
            //meta-refresh 0 for fast data
            if(readString.indexOf("datafast") >0) client.print(F("<meta http-equiv='refresh' content='0'>"));
            client.print(F("<title>Zoomkat's meta-refresh test</title></head><BODY><br>"));
            client.print(F("page refresh number: "));
            client.print(x); //current refresh count
            client.print(F("<br><br>"));
           
              //output the value of each analog input pin
            client.print(F("analog input0 is: "));
            client.print(analogRead(analogInPin0));
           
            client.print(F("<br>analog input1 is: "));
            client.print(analogRead(analogInPin1));
                       
            client.print(F("<br>analog input2 is: "));
            client.print(analogRead(analogInPin2));
           
            client.print(F("<br>analog input3 is: "));
            client.print(analogRead(analogInPin3));
                                   
            client.print(F("<br>analog input4 is: "));
            client.print(analogRead(analogInPin4));
           
            client.print(F("<br>analog input5 is: "));
            client.print(analogRead(analogInPin5));
            client.print(F("<br></BODY></HTML>"));
           }
          //generate main page with iframe
          else
          {
            client.print(F("<HTML><HEAD><TITLE>Zoomkat's frame refresh test</TITLE></HEAD>"
            "Zoomkat's Arduino frame meta refresh test 8/17/13"
            "<BR><BR>Arduino analog input data frame:<BR>"
            "&nbsp;&nbsp;<a href='/datastart' target='DataBox' title=''yy''>META-REFRESH</a>"
            "&nbsp;&nbsp;&nbsp;&nbsp;<a href='/data' target='DataBox' title=''xx''>SINGLE-STOP</a>"
            "&nbsp;&nbsp;&nbsp;&nbsp;<a href='/datafast' target='DataBox' title=''zz''>FAST-DATA</a><BR>"
            "<iframe src='/data' width='350' height='250' name='DataBox'>"
            "</iframe><BR></HTML>"));
          }
          delay(1);
          //stopping client
          client.stop();
          //clearing string for next read
          readString="";
        }
      }
    }
  }
}

Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

erasmudj

Thanks Zoomkat.

I got it working using W.A. Smith, http://startingelectronics.com tutorials. The index page is stored on a SD card.

There is 8 outputs in total 7 digital and one analog used as digital.

Here is the code for the Arduino
Code: [Select]
/*--------------------------------------------------------------
  Program:      WS_8_Outputs

  Description:  Arduino web server 8 outputs, using buttons.
                The web page is stored on the micro SD card.
 
  Hardware:     Arduino Uno and official Arduino Ethernet
                shield. Should work with other Arduinos and
                compatible Ethernet shields.
                2Gb micro SD card formatted FAT16.
                Output pins 2, 3, 5, 6, 7, 8 ,9 and 16(AI 2) for
                (LEDs).
               
  Software:     Developed using Arduino 1.0.5 software
                Should be compatible with Arduino 1.0 +
                SD card contains web page called index.htm
 
  References:   - WebServer example by David A. Mellis and
                  modified by Tom Igoe
                - SD card examples by David A. Mellis and
                  Tom Igoe
                - Ethernet library documentation:
                  http://arduino.cc/en/Reference/Ethernet
                - SD Card library documentation:
                  http://arduino.cc/en/Reference/SD

  Reference:     W.A. Smith, http://startingelectronics.com
--------------------------------------------------------------*/

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   60
#define output_size 8

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x48, 0x66 };
IPAddress ip(192,168,101,201); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
File webFile;               // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
char* LEDStringOn[]={"LED1=1", "LED2=1", "LED3=1", "LED4=1", "LED5=1", "LED6=1", "LED7=1", "LED8=1"};
char* LEDStringOff[]={"LED1=0", "LED2=0", "LED3=0", "LED4=0", "LED5=0", "LED6=0", "LED7=0", "LED8=0"};
int Pout[] = { 2, 3, 5, 6, 7, 8 ,9, 16 };
boolean LED_state[8] = {0}; // stores the states of the LEDs

void setup()
{
    // disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
    Serial.begin(9600);       // for debugging
    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");

//outputs

for (int i = 0; i<output_size; i++){
    pinMode(Pout[i], OUTPUT);
}
   
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
}

void loop()
{
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // limit the size of the stored received HTTP request
                // buffer first part of HTTP request in HTTP_req array (string)
                // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                if (req_index < (REQ_BUF_SZ - 1)) {
                    HTTP_req[req_index] = c;          // save HTTP request character
                    req_index++;
                }
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file
                    if (StrContains(HTTP_req, "ajax_inputs")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: keep-alive");
                        client.println();
                        SetLEDs();
                        // send XML file containing input states
                        XML_response(client);
                    }
                    else {  // web page request
                        // send rest of HTTP header
                        client.println("Content-Type: text/html");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send web page
                        webFile = SD.open("index.htm");        // open web page file
                        if (webFile) {
                            while(webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    // display received HTTP request on serial port
                    Serial.print(HTTP_req);
                    // reset buffer index and all buffer elements to 0
                    req_index = 0;
                    StrClear(HTTP_req, REQ_BUF_SZ);
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
}

// checks if received HTTP request is switching on/off LEDs
// also saves the state of the LEDs
void SetLEDs(void)
{
    // LED 1 (pin 2)
for (int i2 = 0; i2<output_size; i2++){
    if (StrContains(HTTP_req, LEDStringOn[i2])) {
        LED_state[i2] = 1;  // save LED state
        digitalWrite(Pout[i2], HIGH);
    }
    else if (StrContains(HTTP_req, LEDStringOff[i2])) {
        LED_state[i2] = 0;  // save LED state
        digitalWrite(Pout[i2], LOW);
    }
}
   
}

// send the XML file LED status
void XML_response(EthernetClient cl)
{
    int count;                 // used by 'for' loops
   
    cl.print("<?xml version = \"1.0\" ?>");
    cl.print("<inputs>");

    // button LED states
    // LED1
for (int i3 = 0; i3<output_size; i3++){
    cl.print("<LED>");
    if (LED_state[i3]) {
        cl.print("on");
    }
    else {
        cl.print("off");
    }
    cl.println("</LED>");
    }
cl.print("</inputs>");
}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
    char found = 0;
    char index = 0;
    char len;

    len = strlen(str);
   
    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }

    return 0;
}


erasmudj


Here is the code for the index.htm stored on the SD card
Code: [Select]
<!DOCTYPE html>
<html>
    <head>
        <title>Arduino Ajax I/O</title>
        <meta name = 'viewport' content = 'user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width'/>
        <script>
strLED1 = "";
strLED2 = "";
strLED3 = "";
strLED4 = "";
strLED5 = "";
strLED6 = "";
strLED7 = "";
strLED8 = "";
var LED1_state = 0;
var LED2_state = 0;
var LED3_state = 0;
var LED4_state = 0;
var LED5_state = 0;
var LED6_state = 0;
var LED7_state = 0;
var LED8_state = 0;

function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
// XML file received - contains analog values, switch values and LED states
var count;
// LED 1
if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
document.getElementById("LED1").style.backgroundColor="red";
LED1_state = 1;
}
else {
document.getElementById("LED1").style.backgroundColor="green";
LED1_state = 0;
}
// LED 2
if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
document.getElementById("LED2").style.backgroundColor="red";
LED2_state = 1;
}
else {
document.getElementById("LED2").style.backgroundColor="green";
LED2_state = 0;
}
// LED 3
if (this.responseXML.getElementsByTagName('LED')[2].childNodes[0].nodeValue === "on") {
document.getElementById("LED3").style.backgroundColor="red";
LED3_state = 1;
}
else {
document.getElementById("LED3").style.backgroundColor="green";
LED3_state = 0;
}
// LED 4
if (this.responseXML.getElementsByTagName('LED')[3].childNodes[0].nodeValue === "on") {
document.getElementById("LED4").style.backgroundColor="red";
LED4_state = 1;
}
else {
document.getElementById("LED4").style.backgroundColor="green";
LED4_state = 0;
}
// LED 5
if (this.responseXML.getElementsByTagName('LED')[4].childNodes[0].nodeValue === "on") {
document.getElementById("LED5").style.backgroundColor="red";
LED5_state = 1;
}
else {
document.getElementById("LED5").style.backgroundColor="green";
LED5_state = 0;
}
// LED 6
if (this.responseXML.getElementsByTagName('LED')[5].childNodes[0].nodeValue === "on") {
document.getElementById("LED6").style.backgroundColor="red";
LED6_state = 1;
}
else {
document.getElementById("LED6").style.backgroundColor="green";
LED6_state = 0;
}
// LED 7
if (this.responseXML.getElementsByTagName('LED')[6].childNodes[0].nodeValue === "on") {
document.getElementById("LED7").style.backgroundColor="red";
LED7_state = 1;
}
else {
document.getElementById("LED7").style.backgroundColor="green";
LED7_state = 0;
}
// LED 8
if (this.responseXML.getElementsByTagName('LED')[7].childNodes[0].nodeValue === "on") {
document.getElementById("LED8").style.backgroundColor="red";
LED8_state = 1;
}
else {
document.getElementById("LED8").style.backgroundColor="green";
LED8_state = 0;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs" +  strLED1 + strLED2 +strLED3 + strLED4 + strLED5 + strLED6 + strLED7 + strLED8 +nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);
strLED1 = "";
strLED2 = "";
strLED3 = "";
strLED4 = "";
strLED5 = "";
strLED6 = "";
strLED7 = "";
strLED8 = "";
}
// service LEDs when checkbox checked/unchecked
function GetButton1()
{
if (LED1_state === 1) {
LED1_state = 0;
strLED1 = "&LED1=0";
}
else {
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButton2()
{
if (LED2_state === 1) {
LED2_state = 0;
strLED2 = "&LED2=0";
}
else {
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function GetButton3()
{
if (LED3_state === 1) {
LED3_state = 0;
strLED3 = "&LED3=0";
}
else {
LED3_state = 1;
strLED3 = "&LED3=1";
}
}
function GetButton4()
{
if (LED4_state === 1) {
LED4_state = 0;
strLED4 = "&LED4=0";
}
else {
LED4_state = 1;
strLED4 = "&LED4=1";
}
}
function GetButton5()
{
if (LED5_state === 1) {
LED5_state = 0;
strLED5 = "&LED5=0";
}
else {
LED5_state = 1;
strLED5 = "&LED5=1";
}
}
function GetButton6()
{
if (LED6_state === 1) {
LED6_state = 0;
strLED6 = "&LED6=0";
}
else {
LED6_state = 1;
strLED6 = "&LED6=1";
}
}
function GetButton7()
{
if (LED7_state === 1) {
LED7_state = 0;
strLED7 = "&LED7=0";
}
else {
LED7_state = 1;
strLED7 = "&LED7=1";
}
}
function GetButton8()
{
if (LED8_state === 1) {
LED8_state = 0;
strLED8 = "&LED8=0";
}
else {
LED8_state = 1;
strLED8 = "&LED8=1";
}
}
</script>
<style>
.container {
    width: 200px;
    margin:0 auto;

.IO_box {
float: left;
margin: 0 10px 10px 0;
border: 2px solid blue;
padding: 0 5px 0 5px;
width: 200px;
position:relative;
float: left;
}
h1 {
font-size: 120%;
margin: 0 0 10px 0;
}
h2 {
font-size: 85%;
color: #5734E6;
margin: 5px 0 5px 0;
}
p, form, button {
font-size: 80%;
color: #252525;
}
.small_text {
font-size: 70%;
color: #737373;
}
</style>
    </head>
    <body onload="GetArduinoIO()">
        <h1>Arduino Ajax I/O</h1>
        <div class="container">

        <div class="IO_box">
        <br>
<button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED1" onclick="GetButton1()">LED 1</button><br /><br />
<button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED2" onclick="GetButton2()">LED 2</button><br /><br />
        <button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED3" onclick="GetButton3()">LED 3</button><br /><br />
<button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED4" onclick="GetButton4()">LED 4</button><br /><br />
        <button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED5" onclick="GetButton5()">LED 5</button><br /><br />
        <button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED6" onclick="GetButton6()">LED 6</button><br /><br />
        <button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED7" onclick="GetButton7()">LED 7</button><br /><br />
        <button type="button" style="width:200px; height:30px; background-color: #ccc; border-radius:15px; font-size: 16px" id="LED8" onclick="GetButton8()">LED 8</button><br /><br />
</div>
</div>
</div>

    </body>
</html>


The next step would be to have the web page on a dedicated server and not on the Arduino. This will allow for more than one Arduino to be used and have effect and sound on the web page.

tom_rosenback

Change setTimeout to setInterval and off you go :D

erasmudj

Thank Tom.

Anyone have an idea on how to move the web server off the arduino and onto a PC/Server?
I have no idea on how to get ajax working between two IP's.

The other rout could be to use web-sockets or TCP packets to do the communication.

Any help would be appreciated.
Thanks in advance.

tom_rosenback

There is quite many changes you need to do to be able to move your HTML to a webserver outside of Arduino.

1.  A webserver, eg XAMPP with PHP support
2. Make Arduino listen for off / on / status commands, where "off" sets an output to 0 (LOW), "on" respectively "on" to 1 (HIGH), also if no command is given a status report should be printed in a format that can be handled by your webserver, eg JSON / XML.
3. Create a PHP page which takes a command and passes it on to Arduino, eg
     Making a request to serverip/api.php?cmd=off&id=1 will make a request to arduinoip/?off=1 with eg file_getcontents method in PHP. Result of this would be the same status report as cmd=status gives, eg { "digitial_1": "ON",  "digital_2": "OFF" } api.php needs to print out all output it gets from arduino. Reason why you need this page is that javascript doesn´t like cross-domain request which means it will fail if you make a request directly from the HTML page in 4.
4. Create a HTML page which lists all the digital outputs as buttons and makes the request to api.php with javascript / jQuery.

I probably have missed something but this should do the base for you.

Hope I didn´t scare you off, but I´m sure if you just give it some thought you will figure it out. Also there is some good examples out there.

zoomkat

In simple html code, you can put the full URL to the arduino in the main page. Below the first line of code is used when the main page and control are from the same IP address. The second line would be in a page that is served from a different IP address from the arduino.

Code: [Select]

<input type=button value=ON onmousedown=location.href='/?on4'>

<input type=button value=ON onmousedown=location.href='http://zoomkat.no-ip.org:88/?on4'>
Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

tom_rosenback


In simple html code, you can put the full URL to the arduino in the main page. Below the first line of code is used when the main page and control are from the same IP address. The second line would be in a page that is served from a different IP address from the arduino.

Code: [Select]

<input type=button value=ON onmousedown=location.href='/?on4'>

<input type=button value=ON onmousedown=location.href='http://zoomkat.no-ip.org:88/?on4'>



That´s true, I just continued on the XHR request  trail. Both buttons above will work, but with the second you would have to have the arduino to redirect back to where it came from.

zoomkat

Quote
Both buttons above will work, but with the second you would have to have the arduino to redirect back to where it came from.


I kind of do that by sending the browser a status: 204 and putting anything returned into a bit-bucket iframe like below.

Code: [Select]

//zoomkat 10-6-13
//simple button GET with iframe code
//open serial monitor to see what the arduino receives
//use the ' instead of " in html ilnes
//address will look like http://192.168.1.102:84/ when submited
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //ethernet shield mac address
byte ip[] = { 192, 168, 1, 102 }; // arduino IP in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port

String readString;

//////////////////////

void setup(){

  pinMode(4, OUTPUT); //pin selected to control
  //start Ethernet
  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  server.begin();

  //enable serial data print
  Serial.begin(9600);
  Serial.println("servertest1"); // so I can keep track of what is loaded
}

void loop(){
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {

          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {

          ///////////////
          Serial.println(readString); //print to serial monitor for debuging

          //now output HTML data header
             if(readString.indexOf('?') >=0) { //don't send new page
               client.println("HTTP/1.1 204 Zoomkat");
               client.println();
               client.println(); 
             }
             else {
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();

          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<TITLE>Arduino GET test page</TITLE>");
          client.println("</HEAD>");
          client.println("<BODY>");

          client.println("<H1>Zoomkat's simple Arduino button</H1>");
         
          client.println("<a href='/?on1' target='inlineframe'>ON</a>");
          client.println("<a href='/?off' target='inlineframe'>OFF</a>");

          client.println("<IFRAME name=inlineframe style='display:none'>");         
          client.println("</IFRAME>");

          client.println("</BODY>");
          client.println("</HTML>");
             }

          delay(1);
          //stopping client
          client.stop();

          ///////////////////// control arduino pin
          if(readString.indexOf("on1") >0)//checks for on
          {
            digitalWrite(4, HIGH);    // set pin 4 high
            Serial.println("Led On");
          }
          if(readString.indexOf("off") >0)//checks for off
          {
            digitalWrite(4, LOW);    // set pin 4 low
            Serial.println("Led Off");
          }
          //clearing string for next read
          readString="";

        }
      }
    }
  }
}
Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

Go Up