Blink from a webpage


In the previous tutorial we set up a simple web server and responded to incoming HTTP requests with a static web page, this time we're going to have some interaction between the web page and the device. We'll set up a simple web page with a button and when you click that button we'll toggle the LED on the ESP8266.

In the setup function we're going to add some additional handlers for incoming URIs.

Instead of serving up a simple 'Hello World' text response, this time we're pointing the root URI towards the servePage function, in which we'll create a more detailed HTML response.

We've added a second handler for the /args URI and pointed it towards the handleArgs function, this will be used to process the incoming data.

Finally we've added an onNotFound handler, this should respond to all other URIs and direct the browser back towards the root homepage.

The servePage function still only creates a simple response for the client, but this time is is written in HTML. The sample creates a button and wraps it with a link to change the location of the browser when the user clicks the button. The new URI contains some arguments that tell the ESP8266 what is required. In this case we would like the LED to be toggled. This additional data will be sent from the browser to the web server on our device and the web server can interpret it accordingly.

The handleArgs function looks a bit more involved but the actual core is still pretty simple. The first four lines are just included to aid debugging, they create a string of data that lists all of the incoming arguments to the web server and they send that string to the serial port. This makes it very easy to see what was actually sent by the browser.

The middle of the function contains a for loop which iterates through all of the incoming arguments. There may be multiple arguments coming from the browser and they could be in any order so we loop through them all comparing the argument name against the value we're looking for, in this case 'led'. Once we have identified the argument we look at the value of the argument to decide what to do with it, in our case the value is 'toggle' but it could easily be 'on' or 'off'. If both the argument and it's value match then we toggle the state of the built in LED (don't forget to set up the LED pin as an output at the beginning of the program).

Upload the code and connect to the wifi network created by the device, point the browser towards http://192.168.4.1/ and you should see a simple page with a single button load. When you click that button the LED on the ESP8266 should toggle between the on and off state.


Popular posts from this blog

Rainbow Puzzle Box

Wiring the Ruida Controller

Laser Cut Cryptex