ESP8266 and the Arduino IDE

Updated: 15.06.2017
The old guide was out of date and had become a little messy and I had been thinking about redoing it for a while. Also, how I use the ESP8266 has changed and since I am using one as part of a IOT Word Clock I am currently building I thought I would update the guide. So, here is the all new version 2.0. The post for the IOT Word Clock will come later, probably much later…

 
When the ESP8266 first came out there was a lot of excitement and buzz. Here was a new chip that was cheap and allowed internet connectivity. I got caught up in all the excitement and bought several different modules. I intended to use them in various projects where I wanted some kind of remote control. Things didn’t go as planned though, I found the AT command interface very clunky and the ESp8266’s not very reliable. I put the ESP8266s away in the bottom of a draw and moved to Bluetooth.

Things changed when the ESP8266 core for the Arduino IDE was released. This meant you could program them as if they were Arduinos, no more messing around with AT commands. Programming the ESP8266s via the Arduino IDE made things a lot easier and it meant that in many cases you no longer required an Arduino.

ESP8266 Basic Specs
Adding the ESP8266 core to the Arduino IDE
ESP8266 development Boards
NodeMCU Boards
ESP8266 Sketch 1: Blink an LED
ESP8266 Sketch 2: Control an LED from a web page
ESP8266 Downloads

 
 


 
 

ESP8266 Basic Specs

By now everybody should know that the ESP8266 is, in essence, a small microprocessor with built in wi-fi. It is faster than most Arduinos and has more memory than most Arduinos and has less pins than an Arduino.

  • 32-bit RISC CPU: Tensilica Xtensa L106 running at 80 MHz
  • 64 KiB of instruction RAM, 96 KiB of data RAM
  • External QSPI flash: 512 KiB to 4 MiB (up to 16 MiB is supported)
  • IEEE 802.11 b/g/n Wi-Fi
    • Integrated TR switch, balun, LNA, power amplifier and matching network
    • WEP or WPA/WPA2 authentication, or open networks
  • 16 GPIO pins
  • SPI
  • I²C
  • I²S interfaces with DMA (sharing pins with GPIO)
  • UART on dedicated pins, plus a transmit-only UART can be enabled on GPIO2
  • 10-bit ADC (this is a Successive Approximation ADC)

For small projects that require web connection it can replace an Arduino but for other projects it can be used to complement an Arduino perfectly and this is how I mostly use them. I offload the web part of a project to the ESP8266 and use an Arduino, usually a Nano, as the main microprocessor. The two talk to each other using serial.


 

Adding the ESP8266 core to the Arduino IDE

First things first. You can’t use the Arduino IDE until you have added the ESP8266 core. I presume you have the Arduino IDE either installed, or like me, are using the non installed folder version. In this example I am using IDE version 1.8.3. At the time of writing this is the latest.

Open the preferences, and enter the following address in to the Additional Board Manager URLs field.

http://arduino.esp8266.com/stable/package_esp8266com_index.json

You can enter multiple URLs, you just need to separate them with commas.

For more information about the ESP8266 core visit the projects GitHub page.

ESP8266_001_Install_Arduino_Core
ESP8266_002_Install_Arduino_Core
ESP8266_003_Install_Arduino_Core

After entering the ESP8266 url, open up the board manager window and scroll down to the ESP8266 entry (usually at the bottom).
ESP8266_007_Install_Arduino_Core

Select the ESP8266 entry. When you click it an install option will appear
ESP8266_008b_Install_Arduino_Core

Select the latest version and click install.
ESP8266_009b_Install_Arduino_Core

After the installation has finished, go to the boards section and you should now have a whole list of different ESP8266 modules to chose from.
ESP8266_005_Install_Arduino_Core

The selected board appears at the bottom of the IDE. Here I am using a NodeMCU V0.9 board.
ESP8266_006_Install_Arduino_Core


 
 

ESP8266 development Boards

There are now many different development boards and for a while it seemed everybody and their dog was creating a new one. I have more-or-less settled on the NodeMCU boards for general development or my own programming board.

To program the ESP8266-01 I built a programming board. This works well but requires a usb-to-serial adapter.
ESP8266-01_ProgrammingBoard
For more details see the ESP8266-01 Programming Breakout Board post.

For normal development I generally use a NodeMCU 0.9 board. Having the usb built in makes these very convenient to use. When these first came out I bought a few and I am still working my way through them. Should I need to buy more I will get the V1.0 or what ever the latest version is at the time.
I use the NodeMCU boards like an Arduino and program them through the Arduino IDE not Lua. When development is done I upload the finished code to what ever ESP8266 module I am using in the project (normally an ESP8266-01).

ESP8266_0014_NodeMCU_Board_01_1200The NodeMCU boards have USB built in and this makes them easy and convenient to use, just connect them to a computer the same as a typical Arduino. Remember the pins are still 3.3v only though.

There is now a 1.0 version which is what I recommend. These have more memory and they fit breadboards better. The 0.9 version fits on to a breadboard but it covers all the holes so you cannot make any connections unless you have it hanging from one side like I do, see the photo below.

NodeMCU V1.0The NodeMCU v1.0 board is slightly slimmer than the v0.9 version so it fits a bread board better. You should also notice the colour of the small ESP8266 daughter board is black rather than blue. This (normally) means the ESP8266 module is using the ESP-12E rather than the ESP-12 chip.

esp8266-LoLin_V3.0_400I also have a couple of the Lolin 3.0 boards which I have had lots of trouble with and recommend you do not buy.


 
 

NodeMCU Boards

The NodeMCU project is a package of hardware and software and the NodeMCU boards were originally intended to run the LUA language programming language. Conveniently, the boards can be used with the Arduino IDE and be programmed just like another Arduino. When programmed through the Arduino IDE you can think of the NodeMCU board as if it were an Arduino with slightly fewer pins and wifi built in. One thing to note though, is the pin mapping. This is a little different to an Arduino. With the NodeMCU board there are two sets of pin definitions; the ESP8266s GPIO pins and the boards D pins.

If you use a pin number such as:

int LED_Pin = 1;

you refer to the GPIO pin and this is not the same as the D pins labelled on the boards. To reference the pin numbers on the boards you have to use D1:

int LED_Pin = D1;

The below shows the pin mapping for the v0.9 board. Image courtesy of www.cnx-software.com.
ESP8266_0016_NodeMCUv0.9_pinMap

NodeMCU 0.9 Pin Mapping

PIN GPIO PIN GPIO
D0 16 D6 12
D1 5 D7 13
D2 4 D8 15
D3 0 D9 3
D4 2 D10 1
D5 14

 
NodeMCU v1.0 Pin Mapping
nodemcudevkit_v1-0_PinMap_1200

CH340GThe NodeMCU boards use the CH340 serial adaptor chip and if this is the first time you have used it you will need a driver. The driver (all OSs) can be downloaded from the manufacturers website here or the Windows driver can be downloaded from this website here.


 
 

ESP8266 Sketch 1: Blink an LED

As a first step let’s blink an LED. This may seem very basic but it ensures everything is working as it should be. I am using the NodeMCU 0.9 board but any similar board will work the same.

Connect an LED and resistor to pin D2. Remember the ESP8266 is a 3.3v device so a smallish resistor is required. LEDs generally have a forward voltage drop of 2v-3v depending on the colour. Assuming our LED has a forward voltage drop of 2V and uses 0.2mA ( 0.02A ) we can calculate (using ohm’s law) the value of the resistor required.

R = supply voltage – voltage drop (Vs – Vf) / Current required (I)
R = 3.3 – 2 / 0.02
R = 65

So I need a 65 ohm resistor, I don’t have any so I am using 100 ohm. When selecting a resistor, slightly larger is OK but a smaller one is not. The larger the resistor the dimmer the LED will appear.

Circuit

Very simple circuit. and LED and a resistor in series connected to D1.

ESP8266_021_Sketch01_circuit_800

ESP8266_020_Sketch01_Breadboard._800

ESP8266 Sketch 1: Blink an LED

This is basically the blink example from the Arduino IDE. All I have done is change the pin. Upload the sketch and if everything is fine the LED should blink on and off once a second.

 
/*
ESP8266 Blink 
Blink an LED connected to pin D1 
*/
 
// ModeMCU pin mapping is a little weird so use D0, D1,D3 rather than 1,2,3
// pin 1,2,3 refers to the GPIO pins
 
int LED_Pin = D1;
 
void setup() 
{
  pinMode(LED_Pin, OUTPUT); 
}
 
void loop() 
{
  digitalWrite(LED_Pin, LOW);   
  delay(1000);
  digitalWrite(LED_Pin, HIGH); 
  delay(1000);  
}

If you have everything correct the LED should blink on/off once a second.
ESP8266_022_Sketch01_LED


 
 

ESP8266 Sketch 2: Control an LED from a web page

The next step is to build a web page control panel so we can control the LED remotely.

For this example I will be using the ESP8266 as an access point (AP Mode). This means the ESP8266 will create its own little network which we can connect to. The ESP8266 will then serve a small web page which we can view on a mobile device or any web enabled device such as a laptop.

I still have the LED connected to pin D1 but now I want to turn it on and off from a web page viewed on a mobile device. The web page will need 2 buttons, one for on and one for off. It would be nice if it also showed the current LED status. Something like “LED is on” and “LED is off”. Since this is a first example of a web control the actual web page should be as simply as possible.

I won’t go in to detail about creating web pages, if you new to this there are many other sites to help you.

Strings

A typical Arduino has very limited memory and due to how Strings (with a capital S) eat and corrupt memory using Strings is, at best, frowned upon and at worst seen as pure evil. Not so with the ESP8266. The ESP8266 has a lot more memory and the fact that web pages are a lot of text, Strings are the way to go.

If you do not need to edit the html at run time, char arrays are still better though.

ESP8266wifi library

Thanks to libraries using the ESP8266 to create web apps is fairly easy. I am using the ESP8266wifi library by ekstrand. The download will be a zip file, inside the zip file is a folder, copy the folder to the libraries folder inside the Arduino folder.

ESP8266_0010_Install_Arduino_Core

ESP8266_0011_Install_Arduino_Core

Since doing this update the ESP8266wifi library has been renamed to SerialESP8266wifi. You can download the version I am using here.

The basic web page

I will start with a very basic web page and try to explain what it does.

<!DOCTYPE html>
<html>
	<head>
		<title>LED Control</title>
	</head>
	<body>
 
		<div id='main'>
			<h2>LED Control</h2>
			<form id='F1' action='LEDON'>
				<input class='button' type='submit' value='LED ON' >
			</form>
			<br>
			<form id='F2' action='LEDOFF'>
				<input class='button' type='submit' value='LED OFF' >
			</form
			><br>
		</div>
 
	</body>
</html>
<!DOCTYPE html> - Tell the browser we are using html 5
<html> - Start the html
<head> = Start the head section
<title>LED Control</title> - Call the page LED Control. The title is displayed in the browser tab
</head> - close the head section
 
<body> - Open the body section.
 
<div id='main'> = start a div. This comes in handy a little later.
<h2>LED Control</h2> - Display a title at the top of the page
 
<form id='F1' action='LEDON'> - I am using forms that containing a button
<input class='button' type='submit' value='LED ON' > - The LED ON button. The button has a class called "button". This is used later.
</form>
 
<br>
<form id='F2' action='LEDOFF'>
<input class='button' type='submit' value='LED OFF' > - The LED OFF button
</form
><br>
 
</div>
 
</body>
</html>

The above will display a title and 2 buttons. Each button is inside its own form. Using 2 forms means I have 2 actions.
1, action=’LEDON’ for when the ON button is clicked, and
2, action=’LEDOff’ for when the off button is clicked.

The action value gets appended to the ip address such as
1, 192.168.4.1/LEDON, and
2, 192.168.4.1/LEDOFF.

and when the ESP8266 receives the request (more later) the “LEDON” and “LEDOFF” part can be checked for and acted upon if found.

 

The sketch

Download link at the bottom of the page.

/*
 * Sketch: ESP8266_LED_Control_02
 * Control an LED from a web browser
 * Intended to be run on an ESP8266
 * 
 * connect to the ESP8266 AP then
 * use web broswer to go to 192.168.4.1
 * 
 */
 
 
#include <ESP8266WiFi.h>
const char WiFiPassword[] = "12345678";
const char AP_NameChar[] = "LEDControl" ;
 
WiFiServer server(80);
 
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = "<!DOCTYPE html><html><head><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='LED ON' ></form><br>";
String html_3 = "<form id='F2' action='LEDOFF'><input class='button' type='submit' value='LED OFF' ></form><br>";
String html_4 = "</div></body></html>";
 
String request = "";
int LED_Pin = D1;
 
void setup() 
{
    pinMode(LED_Pin, OUTPUT); 
 
    boolean conn = WiFi.softAP(AP_NameChar, WiFiPassword);
    server.begin();
 
} // void setup()
 
 
void loop() 
{
 
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client)  {  return;  }
 
    // Read the first line of the request
    request = client.readStringUntil('\r');
 
    if       ( request.indexOf("LEDON") > 0 )  { digitalWrite(LED_Pin, HIGH);  }
    else if  ( request.indexOf("LEDOFF") > 0 ) { digitalWrite(LED_Pin, LOW);   }
 
    client.flush();
 
    client.print( header );
    client.print( html_1 );
    client.print( html_2 );
    client.print( html_3 );
    client.print( html_4);
 
    delay(5);
  // The client will actually be disconnected when the function returns and 'client' object is detroyed
 
} // void loop()

Sketch details

At the top of the sketch the ESP8266wifi library is added and the password and ssid for the ESP8266 server is set. The ssid is the name that is broadcast by the ESP8266. Remember that we are using the ESP8266 in AP mode so it will create its own network. The network will be called “LEDControl”.

#include <ESP8266WiFi.h>
const char WiFiPassword[] = "12345678";
const char AP_NameChar[] = "LEDControl" ;

I have condensed the html and placed it inside 4 Strings. The Strings will be sent to a connected web browser when a request is made. I have used several variables to make it easier to see but just one can be if wished.

String html_1 = "<!DOCTYPE html><html><head><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='LED ON' ></form><br>";
String html_3 = "<form id='F2' action='LEDOFF'><input class='button' type='submit' value='LED OFF' ></form><br>";
String html_4 = "</div></body></html>";

To tell the browser what type of file we are sending and what format the file is in we use a HTTP header. In this case we are using HTTP1.1 and plain text.

String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";

When the LED On button is clicked, /LEDON is added to the address and when the LED OFF button is clicked “LEDOFF” is added. I check for these with

if       ( request.indexOf("LEDON") > 0 )  { digitalWrite(LED_Pin, HIGH);  }
else if  ( request.indexOf("LEDOFF") > 0 ) { digitalWrite(LED_Pin, LOW);   }

indexof returns the position of the search text or 0 if it is not found. This means if the result is > 0 we know we have a match. If we have “LEDON” we turn the LED on with “digitalWrite(LED_Pin, HIGH);” and if we have “LEDOFF” we turn the LED on with “digitalWrite(LED_Pin, LOW);”

 

HTTP requests

When a web browser contacts a web server it makes a request. The request is in plain text and can contain various types of information. Using Firefox on an Android mobile phone, when I connect to the ESP8266 using address 192.168.4.1 the request contains:

GET / HTTP/1.1
Host: 192.168.4.1
User-Agent: Mozilla/5.0 (Android 6.0.1; Mobile; rv:51.0) Gecko/51.0 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

 
Now if I click the LEDON button I get:

GET /LEDON HTTP/1.1
Host: 192.168.4.1
User-Agent: Mozilla/5.0 (Android 6.0.1; Mobile; rv:51.0) Gecko/51.0 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.4.1/
Connection: keep-alive
Upgrade-Insecure-Requests: 1

 
You will notice the extra “LEDON” in the first line. If I click the LEDOFF button it would be “LEDOFF”. This is the bit we need to know whether or not the LED is being turned on or off. Because it is in the first line, the first line is all we need and since the lines end with a carriage return (\r) character we can read the just the first line with:

request = client.readStringUntil('\r');

We can then check the request variable to see if contains either “LEDON” or LEDOFF”. We do not need to worry about the rest of the request.

For more details about HTTP requests start with the List of HTTP header fields at wikipedia, HTTP headers at MDN, and Header Field Definitions over at w3.org

 

Giving it a go

Connect the LED, upload the code and connect to the ESP8266 from a mobile device using the ip address 192.186.4.1 (the default ip address for the ESP8266wifi library).

ESP8266_030_web_server_1200
Because we defined a password when we initialized the server we need to enter it when we connect.

The first thing you will notice is that the page is very small. It is very very small. Zoom in and click the “LED ON” button. If everything is good the LED will turn on. Then, just for the pure joy of it, click the “LED OFF” button (after zooming in again) to turn off the LED.

ESP8266_031_LED_Control_1200

Unless you have really good eyesight and very thin fingers we need to make the text larger. We could just change the font size but when using a browser on a regular PC the text would be too big. A better way is to tell the browser to resize if we are on a mobile device and we can do this using the meta “viewport” tag. And since we are adding meta statements let’s add the correct character encoding tag as well. Meta statements go in the head section and I have placed these above the title tag.

<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<title>LED Control</title>
</head>

This should make the page a little larger.
ESP8266_032_LED_Control_360

The page is bigger but still on the small size. To change this we can use css. First we make the text bigger with

body {font-size:140%;}

This makes all text 40% bigger. To make the page a little more presentable next we centre by adding css the the div “main”

#main {display: table; margin: auto; padding: 0 10px 0 10px;}

Since I am adding css I might as well add a bit more to make the page a even prettier. The buttons are very plain and we can change this with

.button {padding:10px 10px 10px 10px; width:100%; background-color: #4CAF50; font-size: 120%;}

and finally let’s center the page title with

h2 {text-align:center;}

 
CSS also goes in the head section and is enclosed in “style” tags. Adding all the above we get

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<style>
body {font-size:140%;} 
#main {display: table; margin: auto;  padding: 0 10px 0 10px; } 
h2,{text-align:center; } 
.button { padding:10px 10px 10px 10px; width:100%;  background-color: #4CAF50; font-size: 120%;}
</style>
<title>LED Control</title>
</head>

The new sketch looks like this (the only difference is the html used). Download link at the bottom of the page.

/*
 * Sketch: ESP8266_LED_Control_02A
 * Now with added CSS
 * Control an LED from a web browser
 * Intended to be run on an ESP8266
 * 
 * connect to the ESP8266 AP then
 * use web broswer to go to 192.168.4.1
 * 
 */
 
#include <ESP8266WiFi.h>
const char WiFiPassword[] = "12345678";
const char AP_NameChar[] = "LEDControl" ;
 
WiFiServer server(80);
 
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'/><meta charset='utf-8'><style>body {font-size:140%;} #main {display: table; margin: auto;  padding: 0 10px 0 10px; } h2,{text-align:center; } .button { padding:10px 10px 10px 10px; width:100%;  background-color: #4CAF50; font-size: 120%;}</style><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='LED ON' ></form><br>";
String html_3 = "<form id='F2' action='LEDOFF'><input class='button' type='submit' value='LED OFF' ></form><br>";
String html_4 = "</div></body></html>";
 
String request = "";
int LED_Pin = D1;
 
void setup() 
{
    pinMode(LED_Pin, OUTPUT); 
 
    boolean conn = WiFi.softAP(AP_NameChar, WiFiPassword);
    server.begin();
 
} // void setup()
 
 
 
void loop() 
{
 
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client)  {  return;  }
 
    // Read the first line of the request
    request = client.readStringUntil('\r');
 
    if       ( request.indexOf("LEDON") > 0 )  { digitalWrite(LED_Pin, HIGH);  }
    else if  ( request.indexOf("LEDOFF") > 0 ) { digitalWrite(LED_Pin, LOW);   }
 
    client.flush();
 
    client.print( header );
    client.print( html_1 );
    client.print( html_2 );
    client.print( html_3 );
    client.print( html_4);
 
    delay(5);
  // The client will actually be disconnected when the function returns and 'client' object is detroyed
 
} // void loop()

and that little bit of css has completely changed how the web page looks
ESP8266_033_LED_Control_360

 

LED status

The page now looks a lot nicer but we still don’t know if the LED is on or off. To add a status we need to check the D2 pin and if it is HIGH the LED is on and if it is LOW we know the LED is off. We can then add a message in the web page showing the LED status.

To make things easier I have introduced a new String variable called “html_LED”. This will be used to store the LED status message. In the main loop we check the pin status and create the appropriate LED status message. The should be placed after we have checked for “LEDON” and “LEDOFF” and set the D2 pin.

// Get the LED pin status and create the LED status message
if (digitalRead(LED_Pin) == HIGH) { html_LED = "The LED is on<br><br>"; }
else                              { html_LED = "The LED is off<br><br>"; }

and below that we need to add “html_LED” when we send the html to the connected device with

client.print( header );
client.print( html_1 );    
client.print( html_LED );
client.print( html_2 );
client.print( html_3 );
client.print( html_4);

The full sketch. Download link at the bottom of the page.

/*
 * Sketch: ESP8266_LED_Control_02B
 * Now with added CSS and LED status
 * Control an LED from a web browser
 * Intended to be run on an ESP8266
 * 
 * connect to the ESP8266 AP then
 * use web broswer to go to 192.168.4.1
 * 
 */
 
 
#include <ESP8266WiFi.h>
const char WiFiPassword[] = "12345678";
const char AP_NameChar[] = "LEDControl" ;
 
WiFiServer server(80);
 
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'/><meta charset='utf-8'><style>body {font-size:140%;} #main {display: table; margin: auto;  padding: 0 10px 0 10px; } h2,{text-align:center; } .button { padding:10px 10px 10px 10px; width:100%;  background-color: #4CAF50; font-size: 120%;}</style><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_LED = "";
String html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='LED ON' ></form><br>";
String html_3 = "<form id='F2' action='LEDOFF'><input class='button' type='submit' value='LED OFF' ></form><br>";
String html_4 = "</div></body></html>";
 
String request = "";
int LED_Pin = D1;
 
void setup() 
{
    pinMode(LED_Pin, OUTPUT); 
 
    boolean conn = WiFi.softAP(AP_NameChar, WiFiPassword);
    server.begin();
 
} // void setup()
 
 
 
void loop() 
{
 
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client)  {  return;  }
 
    // Read the first line of the request
    request = client.readStringUntil('\r');
 
    if       ( request.indexOf("LEDON") > 0 )  { digitalWrite(LED_Pin, HIGH);  }
    else if  ( request.indexOf("LEDOFF") > 0 ) { digitalWrite(LED_Pin, LOW);   }
 
    // Get the LED pin status and create the LED status message
    if (digitalRead(LED_Pin) == HIGH) { html_LED = "The LED is on<br><br>"; }
    else                              { html_LED = "The LED is off<br><br>"; }
 
 
    client.flush();
 
    client.print( header );
    client.print( html_1 );    
    client.print( html_LED );
    client.print( html_2 );
    client.print( html_3 );
    client.print( html_4);
 
    delay(5);
  // The client will actually be disconnected when the function returns and 'client' object is detroyed
 
} // void loop()

ESP8266_034_LED_Control_525

 

LED status: Part 2. One button

I personally do not like to have multiple buttons controlling the same thing. We have one LED so we should be able to use just one button. Since we are checking the LED status before we send out the html file, we can change the html we send based on the LED status. We are already doing this with the LED status message so why not do it with the buttons (or more specifically the button).

Using a single button, if the LED is off, the button can say “Turn on the LED” and if the LED is on, it can say “Turn off the LED”. An easy way to do this is to copy the appropriate form to a String before sending.

Using the same idea as with the LED status message change the String variables that contain the html

String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'/><meta charset='utf-8'><style>body {font-size:140%;} #main {display: table; margin: auto;  padding: 0 10px 0 10px; } h2,{text-align:center; } .button { padding:10px 10px 10px 10px; width:100%;  background-color: #4CAF50; font-size: 120%;}</style><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_2 = "";
String html_4 = "</div></body></html>";

and then, after we know the LED status we copy 1 of 2 forms in to html_2

// Get the LED pin status and create the LED status message
if (digitalRead(LED_Pin) == HIGH) 
{
    // the LED is on so the button needs to say turn it off
    html_2 = "<form id='F1' action='LEDOFF'><input class='button' type='submit' value='Turn of the LED' ></form><br>";
}
else                              
{
    // the LED is off so the button needs to say turn it on
    html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='Turn on the LED' ></form><br>";
}

Notice that both forms have the same id value

Then send the html using

client.print( header );
client.print( html_1 );    
client.print( html_2 );
client.print( html_4);

 

The final sketch

Download link at the bottom of the page.

/*
 * Sketch: ESP8266_LED_Control_02C
 * Now with added CSS and a single button
 * Control an LED from a web browser
 * Intended to be run on an ESP8266
 * 
 * connect to the ESP8266 AP then
 * use web broswer to go to 192.168.4.1
 * 
 */
 
 
#include <ESP8266WiFi.h>
const char WiFiPassword[] = "12345678";
const char AP_NameChar[] = "LEDControl" ;
 
WiFiServer server(80);
 
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'/><meta charset='utf-8'><style>body {font-size:140%;} #main {display: table; margin: auto;  padding: 0 10px 0 10px; } h2,{text-align:center; } .button { padding:10px 10px 10px 10px; width:100%;  background-color: #4CAF50; font-size: 120%;}</style><title>LED Control</title></head><body><div id='main'><h2>LED Control</h2>";
String html_2 = "";
String html_4 = "</div></body></html>";
 
String request = "";
int LED_Pin = D1;
 
void setup() 
{
    pinMode(LED_Pin, OUTPUT); 
 
    boolean conn = WiFi.softAP(AP_NameChar, WiFiPassword);
    server.begin();
 
} // void setup()
 
 
 
void loop() 
{
 
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client)  {  return;  }
 
    // Read the first line of the request
    request = client.readStringUntil('\r');
 
    if       ( request.indexOf("LEDON") > 0 )  { digitalWrite(LED_Pin, HIGH);  }
    else if  ( request.indexOf("LEDOFF") > 0 ) { digitalWrite(LED_Pin, LOW);   }
 
 
    // Get the LED pin status and create the LED status message
    if (digitalRead(LED_Pin) == HIGH) 
    {
        // the LED is on so the button needs to say turn it off
       html_2 = "<form id='F1' action='LEDOFF'><input class='button' type='submit' value='Turn of the LED' ></form><br>";
    }
    else                              
    {
        // the LED is off so the button needs to say turn it on
        html_2 = "<form id='F1' action='LEDON'><input class='button' type='submit' value='Turn on the LED' ></form><br>";
    }
 
 
    client.flush();
 
    client.print( header );
    client.print( html_1 );    
    client.print( html_2 );
    client.print( html_4);
 
    delay(5);
  // The client will actually be disconnected when the function returns and 'client' object is detroyed
 
} // void loop()

And here is the final web page
ESP8266_035_LED_Control_525

 
 

 
 

ESP8266 Downloads

Sketches: ESP8266_LED_Control_02(ABC).
CH340/341 drivers all OSes manufacturers site.
CH340 driver for Windows from this website..
ESP8266wifi library (pre rename. The one used for the above example).

 
 
 
 

3 thoughts on “ESP8266 and the Arduino IDE

  1. Pingback: Arduino & ESP8266 Webserver | Martyn Currey

  2. Pingback: Bluetooth Modules | Martyn Currey

Leave a Reply

Your email address will not be published. Required fields are marked *


nine − = 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>