Starting Electronics needs your help! Please make a donation to help cover our hosting and other costs. Click the donate button to send a donation of any amount.
Created on: 13 February 2013
Part 8 of the Arduino Ethernet Shield Web Server Tutorial
Before continuing with this part of the tutorial, you will need to have completed the previous part of this tutorial and understand it.
This video shows the Arduino web server displaying the switch status automatically using AJAX.
Can't see the video? View on YouTube →
Use the same hardware as the previous part of this tutorial – a push button switch interfaced to pin 3 of the Arduino with Ethernet shield.
Only three modifications need to be made to the previous sketch (eth_websrv_AJAX_switch) to automate the AJAX call that updates the switch status on the web page.
The modified sketch is shown here:
The image below shows the modifications that were made to the HTML file that the Arduino sketch sends to the web browser (this file is sent line by line using client.println() in the sketch).
Firstly, the code that creates a button on the web page has been removed as the button is no longer needed. It can be seen commented out in the above image.
The GetSwitchState() function that was previously being called each time the button was pressed is now being called when the page is loaded. This is done by calling the function when the page load event occurs by modifying the <body> tag of the HTML: <body onload="GetSwitchState()">
This is added to the Arduino sketch with the following line of code:
The GetSwitchState() function would only be called once when the web page loads, unless we change the code to periodically call this function.
The following line of code is added to the bottom of the GetSwitchState() function to make sure that this function is called every second:
This code is added to the web page by adding this line to the Arduino sketch:
As an Amazon Associate I earn from qualifying purchases: