Reading Switch State using an Arduino Web Server

Created on: 2 February 2013

Part 6 of the Arduino Ethernet Shield Web Server Tutorial

A push button switch interfaced to the Arduino is read to see whether it is on or off. The state of the switch is displayed on a web page. The Arduino with Ethernet shield is set up as a web server and accessed from a web browser.

This video shows the web server operating and the state of the switch being displayed in the web browser.

The browser refreshes the web page every second, so it can take up to a second for the new state of the switch to be displayed after pressing or releasing the button.

Arduino Web Server Hardware for Reading the Switch

The switch is interfaced to the Arduino / Ethernet shield as done in the circuit diagram from this article: Project 4: Switch a LED on when Switch is Closed (Button) except that the switch is connected to pin 3 and not pin 2 of the Arduino (the article actually uses the circuit diagram from one of the Arduino examples on the Arduino website).

Switch Web Server Sketch

The source code for the switch status Arduino web server is shown below.

/*--------------------------------------------------------------
  Program:      eth_websrv_switch

  Description:  Arduino web server shows the state of a switch
                on a web page. Does not use the SD card.
  
  Hardware:     Arduino Uno and official Arduino Ethernet
                shield. Should work with other Arduinos and
                compatible Ethernet shields.
                
  Software:     Developed using Arduino 1.0.3 software
                Should be compatible with Arduino 1.0 +
  
  References:   - WebServer example by David A. Mellis and 
                  modified by Tom Igoe
                - Ethernet library documentation:
                  http://arduino.cc/en/Reference/Ethernet

  Date:         12 January 2013
 
  Author:       W.A. Smith, http://startingelectronics.org
--------------------------------------------------------------*/

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

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 0, 0, 20); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80

void setup()
{
    Ethernet.begin(mac, ip);    // initialize Ethernet device
    server.begin();             // start to listen for clients
    pinMode(3, INPUT);  // input pin for switch
}

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
                // 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");
                    client.println("Content-Type: text/html");
                    client.println("Connnection: close");
                    client.println();
                    // send web page
                    client.println("<!DOCTYPE html>");
                    client.println("<html>");
                    client.println("<head>");
                    client.println("<title>Arduino Read Switch State</title>");
                    client.println("<meta http-equiv=\"refresh\" content=\"1\">");
                    client.println("</head>");
                    client.println("<body>");
                    client.println("<h1>Switch</h1>");
                    client.println("<p>State of switch is:</p>");
                    GetSwitchState(client);
                    client.println("</body>");
                    client.println("</html>");
                    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)
}

void GetSwitchState(EthernetClient cl)
{
    if (digitalRead(3)) {
        cl.println("<p>ON</p>");
    }
    else {
        cl.println("<p>OFF</p>");
    }
}

Modification to Sketch

Again, this sketch is a modified version of the eth_websrv_page sketch from the basic Arduino web server.

Reading the Switch

The web page is created as usual, except that the function GetSwitchState() is called when the text for the switch is to be displayed.

In the GetSwitchState() function, the state of the switch is read. The text that is sent to the browser will be a HTML paragraph that contains either "ON" or "OFF", depending of the state of the switch.

Refreshing the Browser

A line of HTML in the <head> part of the HTML page sent to the browser is used to tell the browser to refresh the page every second. This allows the new state of the switch to be displayed if it has changed.

The line of code in the sketch that does this is shown here:

client.println("<meta http-equiv=\"refresh\" content=\"1\">");

This will be sent to the browser as the following HTML code:

<meta http-equiv="refresh" content="1">

Remember that you can right-click on the web page in your browser and then select View Page Source on the pop-up menu (or similar menu item depending on the browser you are using).

The "1" in the code tells the browser to refresh every 1 second.

This is the same method used to read the analog inputs of the Arduino in the WebServer example that is built into the Arduino software (found in the Arduino IDE under File → Examples → Ethernet → WebServer).

Improving this Example

The annoying thing about this method of refreshing the page is that the browser flashes every second as it updates the page. In the next part of this tutorial we will use a method called AJAX that will refresh only part of the web page that displays the switch state.