This tutorial shows how to use the Arduino MEGA 2560 and Arduino Ethernet shield to make a web server that hosts a web page allowing 24 outputs to be controlled by clicking checkboxes on the web page.
Basic Code Structure
The Arduino MEGA and Ethernet shield are programmed to behave as a web server that serves up the web page from the micro SD card when a web browser connects to the server and requests the page.
Hardware and Circuit Diagram
An Arduino MEGA 2560 and Arduino Ethernet shield are used in this project. A 2GB micro SD card is used to store the web page that is hosted by the Arduino.
The circuit diagram shows how the LEDs are connected to the Arduino. Only the first two and last two LEDs with series resistors are shown in the circuit as the rest of the LEDs are connected in the same way sequentially from pin 26 to pin 49 of the Arduino MEGA.
NOTE: Pins 50 to 53 (four pins) can not be used as outputs when using the Ethernet shield. This is because these are SPI port pins that are used to control the Ethernet chip and SD card.
Arduino Sketch Code
The setup() function initializes the SD card, then sets the Arduino pins 26 to 49 as outputs and switches them low (or off).
The Ethernet is then initialized before the main loop is run.
The Main Loop
The main loop in the sketch handles the browser requests. It responds to two types of requests – a request for the web page and an Ajax request.
When a web browser is used to connect to the web server at it’s IP address, the Arduino web server responds with the index.htm page which then gets loaded to the browser.
The Arduino responds to the Ajax request with an XML file that contains all the states of the LEDs / checkboxes. This is so that if a second browser connects to the web server, the correct states of the checkboxes (checked or unchecked) will be set on the page.
Each time the an Ajax request is received by the Arduino, the SetLEDs() function is run which sees which checkboxes have been checked or unchecked and then sets or clears the corresponding LED.
The state of each LED is stored as a bit in the LED_state array which consists of 3 bytes of 8 bits each = 24 bits corresponding to the 24 outputs. Whenever the state of an LED is set or cleared, the corresponding bit is set in the array to keep track of the LED states.
Because of this array, each time that the array is accessed, it is accessed in a for loop as 3 bytes and a secondfor loop accesses each bit in the current byte using bitwise operators.
After SetLEDs() is called in response to the received Ajax request, XML_response() is called to send back the XML file containing the LED states.
Tags: 201503, arduino mega2560, ethernet shield, tutorial, 24 output, web server, ajax