Getting Started with the ESP8266

One of the drivers behind the explosive growth of network connected devices we’ve seen over the last year or two is the availability of cheap, capable, micro-controllers with built-in networking.

As a result, we’ve seen a large number of boards intended for the Internet of Things. Most of these take the “kitchen sink” approach throwing more, and different, radios onto the board. The ESP8266 is not one of those boards.

The ESP8266

The ESP8266 a micro-controller chip from Chinese manufacturer Espressif. Built around a Tensilica Xtensa LX3 processor, it includes on-board Wi-Fi. Originally intended as a UART to WiFi adaptor, allowing other micro-controllers to connect to a Wi-Fi network and make simple TCP/IP connections using Hayes-style commands, the ESP8266 quickly became popular as a stand alone micro-controller because of its low price point.

Despite the initial lack of documentation, a large community formed 
around the ESP8266, and the community created and supported firmware for the chip.

Although the ESP8266 chip is made by Espressif, modules bearing the chip 
come from a variety of different manufacturers, and on a somewhat bewildering variety of breakout board form factors.

Original board (left), and 1MB flash version (right).

However, perhaps the most commonly available was the ESP-01 which has a tiny form factor and can be picked up for less than $2. Unfortunately, while the pin out of the ESP-01 is physically compatible with a breadboard, it is not electrically compatible.

The unusual pinout of the ESP-01 breakout board.

This means that, at least to start off with, we’re going to have to use jumpers when we use the ESP-01. While there are a lot easier ways to buy, and use, the ESP8266 these days, there are a lot of ESP-01 boards out there, and they’re amazingly cheap. So despite the hassle, they’re a great way to get started with the ESP8266 and the Internet of Things.

Connecting the board to your laptop

The first thing we need to do is connect the board to your laptop so you 
can load new firmware, and eventually your own code, onto the ESP-01. 
The easiest method to attach the board to your computer is to use a 3.3V 
compatible FTDI adaptor board — like the FTDI Basic from SparkFun or the FTDI Friend from Adafruit.

The ESP-01 wired up to an FTDI adaptor in normal operation.

The ESP8266 requires 3.3V power — do not power it with 5V! It also does 
not have 5V tolerant inputs. This means that Rx/Tx communication needs 
to be level converted down to 3.3V. Many FTDI boards have a single jumper 
or switch to change from 3.3V to 5V operation; make sure yours is set 
for 3.3V. You should also note that while the current consumption of the 
module is 80mA at idle state, it can draw as much as 300mA while in 
operation.

Plug your FTDI adaptor into your laptop, and grab a bunch of jumper wires, and go ahead and connect Rx pin of the ESP-01 to the Tx on the FTDI adaptor, and the Tx of the ESP-01 to the Rx on the adaptor. Then go on to connect the GND pin of the ESP-01 to the GND pin of the FTDI adaptor. Finally connect both the CH_PD (chip power down pin) and the ESP-01 VCC pin on the FTDI adaptor (you might need to use a bread board). If all goes well the blue light on the ESP-01 will flicker briefly, and the red (power on) light will light up on the board.

The ESP8266 can draw a good deal of current (Amps) from the USB port. If you find that the board is continually rebooting you may not be supplying enough current to the port. If you’re using a USB hub make try connecting the cable directly to your laptop.

The CH_PD pin acts as an enable pin for the board. Unless this pin is 
pulled to +3.3V the chip will not boot. You can pull the pin HIGH either 
directly or using a pull up resistor (using a 1kΩ or 3.31kΩ resistor is recommended to limit the current to the pin).

Now we know the board is working (electrically at least) we need to consider software.

Which firmware?

There is a large number of different sources for the ESP-01 board, some 
more reliable than others. While most of the boards I’ve seen ship with 
Espressif’s AT command firmware I’ve seen versions of the board ship without firmware, with Lua support, and even in one unusual case already set up up to support the Arduino development environment out of the box. I’ve also seen the boards configured with baud rates ranging from 9,600 to 115,200.

Because of this problem I geneally don’t bother trying to figure out what 
firmware the board has shipped with, and go straight ahead and upload my 
own onto the board.

Enabling bootloader mode

Since we want to start by uploading new firmware to the board, we need 
to make some special (additional) wiring connections. Go ahead and unplug 
the FTI adaptor from your laptop.

To put the board into “bootloader mode”, ready to recieve new firmware, 
the GPIO0 pin must be pulled to GND and the GPIO2 pin must be 
pulled HIGH, to +3.3V.

The ESP-01 wired up to an FTDI adaptor using a breadboard in bootloader mode.

Once you’ve added the extra wires, plug the FTDI adaptor back into your 
laptop. The blue light on the ESP-01 should flicker briefly again, and 
the red light will come on steady. We’re ready to upload firmware.

Note while the documentation says to ensure “GPIO2 is pulled high” for 
firmware upload, this doesn’t appear to be (always) necessary. More information on the boot process of the ESP8266 can be found on the wiki.

If you didn’t unplug the ESP-01 before attaching the wires to the GPIO0 and GPIO2 pins you should do so now, as the board needs to be power cycled to place it into bootloader mode.

Flashing firmware to the ESP-01

The most flexible way to update the firmware on the ESP-01 is from the 
command line. Amongst the easiest available method is the esptool.py tool, which is written in Python. Before you install the esptool tool, you first need Python 2.7 installed on your computer.

If you don’t already have Python installed you can find installers for Mac and Windows. Python for Linux can be installed using your favourite package 
manager.

Beyond Python itself, the esptool needs the PySerial library. On Windows, you should use the pyserial installer whilst on Mac and Linux you should download the get-pip.py script and then install pyserial.

$ sudo python get-pip.py
$ sudo pip install pyserial

Now grab the esptool script from its Github repository, and check to see if it works.

$ git clone https://github.com/themadinventor/esptool.git
$ cd esptool
$ python esptool.py -h
usage: esptool [-h] [ — port PORT] [ — baud BAUD]
{load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,flash_id,read_flash,erase_flash}

Find the serial port for your FTDI adaptor. On Windows you can do this 
using the Device Manager; on Mac or Linux you can usually find it by 
looking in the /dev directory.

$ ls -l /dev/tty* | grep usb
crw-rw-rw- 1 root wheel 11, 66 4 Jan 14:15 /dev/tty.usbserial-A9048F6Z
$

For instance, on my Mac the serial port for my FTDI adaptor is /dev/tty.usbserial-A9048F6Z.

We’ll start off by flashing the official Espressif AT Command firmware 
onto the board. It’s actually pretty confusing as to where the “official” 
repository for this firmware lives, so for convenience you can find a 
copy of a recent build in my Github repository. You could just clone the repository, or pull the individual file.

Once you’ve downloaded the firmware you should now just be able to

$ python esptool.py -p /dev/tty.usbserial-A9048F6Z write_flash 0x00 ESP_8266_BIN0.92.bin
Connecting…
Erasing flash…
Took 1.82s to erase flash block
Wrote 520192 bytes at 0x00000000 in 53.6 seconds (77.6 kbit/s)…
Leaving…
$

where you should substitute the name of your serial port for mine, which was /dev/tty.usbserial-A9048F6Z.

If you’re using MS Windows, and would prefer to avoid the command line, you might want to consider using the NodeMCU Flasher tool to upload the firmware to the ESP8266 board.

After loading the firmware onto the board you should unplug the FTDI 
adaptor and remove the jumper wires going to GPIO0 and GPIO2 before 
plugging it back into your computer. This way the board will be booted 
into the AT firmware rather than into bootloader mode.

Using the ESP8266 as a UART to WiFi

You probably won’t use the ESP8266 in UART to WiFi mode, as there are much more interesting things we can do with the board. However, it’s interesting to take a look at how the chip was originally intended to be used.

Connecting to the Internet

To talk to the board using the FTDI adaptor we’re going to need a serial 
port terminal program. There are many terminal programs available. I’m 
going to be using CoolTerm by Roger Meier. This is a relatively simple application that’s perfectly suited to allow you configure the ESP8266.

Configuring CoolTerm to talk the the ESP-01 board via the FTDI adaptor

Open up CoolTerm and hit the “Options” icon. Select the correct serial 
port from the pull down menu, set the baudrate to 115,200, and ensure 
that “Enter Key Emulation” is set to CR+LF. The rest of the settings should be correct. Then go ahead click the OK button, followed by the “Connect” icon. If everything goes okay the “Connected” timer in the bottom left-hand section of the window will start to increment. This is usually the only sign that things are working

If you see a lot of junk characters on your display you’re probably using the wrong baud rate setting.

At this point go ahead and type AT into the CoolTerm window. The board 
should reply OK.

AT
OK

If you make a mistake you’ll see Error. Don’t worry; it’s pretty hard to break anything at this point.

If you don’t get a response, check your hardware connections. The most likely culprit is that you didn’t connect the communication lines correctly, so try swapping the Rx and Tx wires around. You should also check your baud rate; the AT firmware default is usually 115,200 baud. Finally, you should make sure your line endings are CR+LF. Unlike the earlier versions of the firmware that expected CR only, the current versions require CR+LF.

At this point you can go ahead and check the firmware version using the GMR (for Get Modem Revision) command:

AT+GMR
00170901
OK

if the board replies with +00170901+, then all is well.

If you find that your ESP8266 board is rebooting regularly, seemingly at 
random, it’s possible that you’re not providing enough power to the board. 
The ESP8266 can take more than 300mA of power when WiFi is turned on.

Now let’s go ahead and get this board connected to the Internet. The first 
thing we need to do is change the operating mode of the board to mode “1”
with the CWMODE command, the restart the board with the RST command.

AT+CWMODE=1
OK
AT+RST
OK
ets Jan 8 2013,rst cause:4, boot mode:(3,0)
wdt reset
load 0x40100000, len 212, room 16
tail 4
chksum 0x5e
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x1c
load 0x3ffe8314, len 72, room 8
tail 0
chksum 0x55
csum 0x55
jump to user1
ready

The ESP8266 has three modes; mode 1 which is “Station” mode, mode 2 which is “Access Point” mode, and mode 3 which is “AP + Station” mode where the device can act as a WiFi client and access point simultaeously.

Now we’ve put the board into client mode, let’s go ahead and grab a list 
of available WiFi access points in the area with the List Access Points
(CWLAP) command:

AT+CWLAP
+CWLAP:(0,””,0,18:58:ff:3f:00:00,0)
+CWLAP:(3,”Babilim”,-50,f8:1e:XX:XX:XX:XX,1)
+CWLAP:(3,”Technicolor”,-78,9c:97:XX:XX:XX:XX,6)
+CWLAP:(4,”EE-BrightBox-g77psn”,-89,18:83:bf:XX:XX:XX,1)
+CWLAP:(3,”Onion”,-56,00:e0:XX:XX:XX:XX,6)
+CWLAP:(3,”SKY80XXX”,-74,90:01:3b:XX:XX:XX,11)
OK

All the Access Points visible to the ESP8266 are listed. The first number 
inside the brackets indicates the encryption: 0 is an open network, 1 is
WEP, 2 is WPA_PSK, 3 is WPA2_PSK, and 4 is WPA_WPA2_PSK. Next comes the SSID of the access point in quotes, followed by the currently measured Received Signal Strength Indication (RSSI) value for the AP, followed by the access point’s MAC address, and WiFI channel.

To connect your ESP-8266 to an access point, we use the Join Access Point 
(CWJAP) command:

AT+CWJAP=”SSID”,”PASSWORD”
OK

Remember to substitute the name of your network (for SSID) and network password (for PASSWORD).

We can now check that the board properly associated with the network, 
and what IP address it was allocated with the CIFSR command.

AT+CWJAP?
+CWJAP:”Babilim”
OK
AT+CIFSR
192.168.1.223

From here onwards, every time you power the board on it will try to connect to the same WiFi network. Even if the power is removed, the ESP8266 module will remember the access point it should associate to, although you can make it forget with the Quit Access Point command (CWQAP).

AT+CWQAP
OK
AT+CIFSR
ERROR

However, let’s not do that quite yet. Instead, now that we have a network connection, let’s push ahead and grab a web page as an experiment.

AT+CIPMUX=1
OK
AT+CIPSTART=0,”TCP”,”www.google.com",80
OK
Linked

Here we put the board in multiple connection mode, and then open a TCP 
connection to google.com on port 80, specifying which connection 
channel we’re going to use (0–4). Then we go ahead and send 18 bytes, 
consisting of the most basic HTTP GET request possible.

AT+CIPSEND=0,18
> GET / HTTP/1.0
SEND OK
+IPD,0,490:HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.uk/?gfe_rd=cr&ei=SqmJVsrQI-7S8Afcq5wI
Content-Length: 259
Date: Sun, 03 Jan 2016 23:05:46 GMT
Server: GFE/2.0
<HTML><HEAD><meta http-equiv=”content-type” content=”text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF=”http://www.google.co.uk/?gfe_rd=cr&amp;ei=SqmJVsrQI-7S8Afcq5wI">here</A>.
</BODY></HTML>
OK

In return we get an IPD statement back from the board. Google has replied with a status code “302 Found,” a common way of performing URL redirection, and pointed at the actual home page location.

Talking to the ESP-01 using CoolTerm.

We can then go ahead and grab the actual Google home page by retrieving the new URL.

AT+CIPSEND=0,18
> GET http://www.google.co.uk/?gfe_rd=cr&ei=SqmJVsrQI-7S8Afcq5wI HTTP/1.1
SEND OK

If successful you should see a large amount of text scroll by, it’s amazing how much CSS and Javascript is crammed into that apparently pristine white page.

The tail end of the actual Google home page.

Congratulations. Depsite that fact that we’re probably never going to use the ESP8266 in this mode again, we’ve taken a big step forward. We now know how to flash new firmware onto our board, and connect to it using the serial console.

You also know enough now to configure the the board and use it as it was 
originally intended, as a UART to WiFi bridge for another microcontroller 
like the Arduino. But as we said before, there are much more interesting 
things to do with the ESP8266.

You can find a PDF reference sheet with a full list of the available AT commands in my Github repository.

Using the ESP8266 with Lua and NodeMCU

NodeMCU is a community-built firmware written in Lua (a lightweight programming language for embedded systems) specifically to run on the ESP8266. With NodeMCU’s arrival, the ESP8266 became more than a way to give other micro-controllers a cheap WiFi connection; it became a micro-controller in its own right. The ESP8266 running NodeMCU became the cheapest WiFi enabled general purpose micro-controller available.

The latest release of the NodeMCU firmware can be downloaded from the project’s GitHub repository, and the new firmware can be flashed onto the ESP-01 in the same way we flashed the official AT Command firmware earlier.

Remember that the GPIO0 pin must be pulled to GND, and the GPIO2 pin must be pulled HIGH, to +3.3V, to enable bootloader mode.

$ python esptool.py -p /dev/tty.usbserial-A9048F6Z write_flash 0x00 nodemcu_float_0.9.6-dev_20150704.bin 
Connecting…
Erasing flash…
Took 1.13s to erase flash block
Wrote 462848 bytes at 0x00000000 in 50.6 seconds (73.2 kbit/s)…
Leaving…
$

Once we have the firmware uploaded, and toggle to the power to the board while disconnecting the wires to the GPIO0 and GPIO2 pins. Open up CoolTerm again, hit the “Options” icon, then select the correct serial port from the pull down menu, set the baudrate to 9,600 and ensure that “Enter Key Emulation” is set to CR+LF. Then go ahead click the OK button, followed by the “Connect” icon.

Note that the baud rate for the NodeMCU Lua firmware is 9,600 rather than the 115,200 of the official AT firmware.

If all goes well you should see some dots as the board boots and then a right arrow. This is the NodeMCU Lua prompt which we can then interact with.

The ESP-01 with the NodeMCU running Lua.

If we now go ahead and wire up an LED to our ESP-01 board to the GPIO0 pin.

Wiring for attaching an LED to +GPIO2+ on the ESP-01.

We can control the LED directly from the command line as follows,

> pin = 4
> gpio.mode(pin,gpio.OUTPUT)
> gpio.write(pin,gpio.HIGH)
> gpio.write(pin,gpio.LOW)
>

The pin number for z in Lua is “4.” You might expect that the value of pin numbers passed to Lua’ GPIO library are numbers of the GPIO pins. Unfortunately, it’s not that simple. The first argument to any gpio functions is actually an IO index. These IO indices map to the same GPIO pins on all of the ESP8266 modules, but they don’t map in a particularly sensible order.

Mapping between GPIO Pin number and IO Index.

You can either refer to the table above, or set up aliases in the gpio namespace in your code to simplify things when referring to the pins.

-- Set up aliases in the gpio namespace:
gpio = setmetatable({},{__index=gpio}) for k,v in pairs{3,10,4,9,2,1,nil,nil,nil,11,12,nil,6,7,5,8,0} do gpio['GPIO'..k-1] = v end
-- Use them like this:
gpio.mode( gpio.GPIO2, gpio.OUTPUT )

Pushing code to the module

Interacting with the Lua prompt on the command line isn’t the only way we can use the ESP module with a Lua firmware. If you go ahead and install the esp8266 Node.js module using npm on your computer as follows,

$ npm install -g esp8266

The package provides a command line interface for modules flashed with the NodeMCU Lua firmware, allowing you to read and write files to and from the module, as well as administer the file system. You’ll be able to use the esp command to perform tasks on a connected ESP8266 module.

First go ahead and set your serial port.

$ esp port set /dev/tty.usbserial-A9048F6Z

Then go ahead and open up your favourite text editor and write a short web server. Replace +SSID+ and +PASSWORD+ with the name and password of your Wi-Fi network.

wifi.setmode(wifi.STATION)
wifi.sta.config(“SSID”,”PASSWORD”)
srv=net.createServer(net.TCP) 
srv:listen(80,function(conn)
conn:on(“receive”,function(conn,payload)
print(payload)
conn:send(“<h1> Hello, NodeMCU.</h1>”)
end)
end)

Then upload it to the ESP module, you should see a blue LED blink while the command is executing. If you still have your LED wired up to the board from our previous example you should disconnect it from GPIO2 before uploading the new code to the board.

$ esp file write webserver.lua
$ esp file list
266 bytes webserver.lua

You can execute the program using the esp execute command.

$ esp file execute webserver.lua

If all goes well your ESP module should connect to your Wi-Fi network and start running a webserver. If you go to the configuration page of your home Wi-Fi router you should see it pop up in the list of devices connected to your WiFi network, and if you go ahead and type the IP address that your router has allocated to it into a web browser you should see “Hello, NodeMCU.”

Run a script automatically on power-up

Running a Lua script automatically whien the baord is powered on is actually really simple. The Lua firmware looks for a file called init.lua and, if it exists, runs it.

So let’s push our script to the board again, but this time we’ll call it init.lua on the module.

$ esp file write webserver.lua init.lua
$ esp file list
266 bytes init.lua
266 bytes webserver.lua

The extra filename on the end dictates what the file is called on the module. Once it’s uploaded we can restart our module from the command line,

$ esp restart

from here, if you once again connect to the board using a web browser you gain get our friendly greeting from our web server.

The ESP-01 with a simple Lua webserver.

You can also monitor the serial output of the code using the esp tool’s monitor function.

$ esp monitor
Displaying output from port /dev/tty.usbserial-A9048F6Z
Press ^C to stop.
GET / HTTP/1.1
Host: 192.168.1.151
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

Which will let you see the web server handling each web request as you make it from your browser .Some older versions of the esp module do not have the esp monitor command. In which case you can use CoolTerm to monitor the serial output of the ESP module.

A full list of the available esp command line options can be found in the documentation in the project’s Github repository. Congratulations, you now have a simple web server running on your ESP8266.

Other ESP8266 Firmware

If you’re familiar with developing using Python you might also want to 
take a look at the experimental Micropython firmware for the ESP8266. Adafruit has a good walkthrough of how to compile and install Micropython on their ESP8266.

On the other hand, if Javascript is your language of choice, then the Espruino port to the ESP8266 is the thing for you. The Espruino site has full details of how to load the Espruino firmware onto the board, and documentation on the limitations compared to a ‘real’ Espruino board.

There is also an experimental release of a Lisp firmware for the ESP8266, although since it is interpreted, rather than compiled, it runs around ×2 slower than the equivalent code written in Lua.

Finally, if you’re missing the early days of home computing, there is also BASIC firmware, again interpreted rather than compiled.

Using the ESP8266 with Arduino

The ESP8266 was already well on its way to becoming — almost by stealth — one of the leading platforms for the Internet of Things. It’s super cheap, and super easy to work with, and it’s actually fairly easy — as such things go — to get your hands on, which makes for a refreshing change. However the arrival of Arduino-compatibility has now opened things up to a much larger audience.

Originally a custom version of the Arduino development environment was required. However it’s now as easy as installing support for ESP-based boards using the Arduino board manager.

Installing the Arduino Development Environment

We’re going to be using the Arduino IDE to develop the code.

The Arduino Development Environment.

The latest version of the Arduino development environment is available from the Arduino web site. At the time of writing, this was Arduino 1.6.5.

Installing on OS X

Like most Mac applications, the development environment comes as a disk image (.dmg file) that should mount automatically after you have downloaded it. If it doesn’t, double-click on it to open it manually. After it is open, just click-and-drag the Arduino.app application into your /Applications folder. Double click on the application to open it.

Note that if you’re using a Mac when you connect your board to your computer, depending on the version of OS X you’re running, a dialog box may appear telling you that a new network interface has been detected. Just hit the Apply button. Whilst the new interface will claim to be “Not Configured,” if you inspect it in System Preferences, it is working correctly.

Installing on Linux

The Arduino development environment has been packaged and can be installed by using the package manager. On Debian type,

$ sudo apt-get install arduino

Detailed instructions for other flavours of Linux are available on the Arduino Playground. For the Aruino Uno you need librxtx-java version 2.2pre2–3 or newer installed.

Installing on MS Windows

The development environment comes as a ZIP file. Download it, unzip and then double click ot open the folder, then double click on the application to open it.

If you’re running Windows when you connect your board to your computer driver installation should begin automatically. However if you’re running Windows 7, Vista or XP it may well fail. If so click on the Start Menu and open the Control Panel. Navigate to System and Security and click on System. Once the System window is open go ahead and open the Device Manager. Under Ports (COM & LPT), or possibly under Unknown Devices, you should see a entry named “Arduino UNO (COMx).” Click on the entry and choose “Update Driver Software” and “Browse my computer for Driver Software.” Navigate to the folder containing the development environment and choose the Arduino Uno driver names Ardunio UNO.inf.

Installing support for the ESP8266

Go to the Tools➝Boards menu and click on the Boards Manager… item. This will open up the board manager popup. From there go ahead and search for “ESP8266” and click on the Install button to install support for ESP-based boards.

Installing support for the ESP8266 in the Arduino Environment.

After you’ve installed support if you go again to the Tools➝Boards menu you should see entries for a number of different ESP8266 boards at the bottom of the menu. For now select “Generic ESP8266 Module” from the menu.

Selecting a generic ESP8266 based board.

Then from the Tools➝Port menu go ahead and select the correct serial port for your board, and we’re ready to upload code to the board.

An Arduino-powered Webserver

Go to the File→Examples→ESP8266WiFi menu and load the “WiFiWebServer” sketch into an editor window. Replace the place holders values in the script for “ssid” and “password” with the SSID and password for your WiFi network.

/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/gpio/0 will set the GPIO2 low,
* http://server_ip/gpio/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/
#include <ESP8266WiFi.h>
const char* ssid = “your-ssid”;
const char* password = “your-password”;
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(2, OUTPUT);
digitalWrite(2, 0);

Serial.println();
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);

server.begin();
Serial.println(“Server started”);
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}

Serial.println(“new client”);
while(!client.available()){
delay(1);
}

String req = client.readStringUntil(‘\r’);
Serial.println(req);
client.flush();

int val;
if (req.indexOf(“/gpio/0”) != -1)
val = 0;
else if (req.indexOf(“/gpio/1”) != -1)
val = 1;
else {
Serial.println(“invalid request”);
client.stop();
return;
}
digitalWrite(2, val);
client.flush();
String s = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now “;
s += (val)?”high”:”low”;
s += “</html>\n”;
client.print(s);
delay(1);
Serial.println(“Client disonnected”);
}

Every time we upload an Arduino sketch to the board we’re essentially flashing a new firmware onto the ESP8266. So we’ll need to ensure that the GPIO0 pin is pulled to GND, and the GPIO2 pin must be pulled HIGH, to +3.3V, to enable bootloader mode.

Then hit the upload button in the Arduino development environment.

If all goes well you you should see that it is “Uploading…” and then, after a while, that it is “Done uploading.” If you encounter an error then you should double check and ensure that the CH_PD pin is pulled high, and the GPIO0 pin is pulled low. Then toggle the power on the board again to make sure it’s in bootloader mode. You should probably also check that RX is wired to TX, and TX to RX.

[TIP]
====
Under OS X the esptool used by the Arduino environment can be somewhat unreliable. If this proves to be the case, you can replace it with the esptool.py we used earlier by modifying Arduino’s platform.txt file. Close down the Arduino environment and open the platform.txt file in an editor.

You can find it in the ~/Arduino15/packages/esp8266/hardware/esp8266/VERSION directory — where VERSION is the package version of the esp8266 board package release you have installed.

Now go ahead and replace the line,

tools.esptool.upload.pattern=”{path}/{cmd}” {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp “{serial.port}” -ca 0x00000 -cf “{build.path}/{build.project_name}.bin”

with the following,

tools.esptool.upload.pattern=”PATH/esptool.py” — port “{serial.port}” write_flash 0x00000 “{build.path}/{build.project_name}.bin”

where PATH should be the fully qualified path to the esptool.py program. Restart the Arduino environment and next time you try and upload a sketch to your board the development environment will use the esptool.py program.

Once we have the sketch uploaded, remove the power to the board while disconnecting the wires to the GPIO0 and GPIO2 pins. Then go ahead and wire up your LED in the normal way to the spare GPIO pin, that’d be GPIO2 before returning power to the board.

Open the Arduino Serial Monitor by clicking on the magnifying glass icon in the top right hand corner of the development environment. If all is still going well you should see something like this,

Connecting to Wireless Network
…….
WiFi connected
Server started
192.168.1.224

which tells you that the board has connected to the network, and also what the board’s IP address ended up as when it negotiated its connection to the DHCP server.

Now you can just go to your browser and use the endpoint http://IPADDRESS/gpio/1 (where IPADDRESS is the IP address assigned to your board by your router) to pull GPIO2 high, and turn the LED on, or http://IPADDRESS/gpio/0 to pull GPIO2 low, and turn the LED off .

Toggling an LED with the Arduino web server sketch.

If you’re still connected to the Serial Console you should see something like this scroll by if you attempt to turn the LED on,

new client
GET /gpio/1 HTTP/1.1
Client disconnected
new client
GET /favicon.ico HTTP/1.1
invalid request

Here you can safely ignore the invalid request error message — that’s just your browser asking for the icon that accompanies the web pages its retrieving, it doesn’t necessarily expect a response — however at this point the LED connected to GPIO2 should be on. Go ahead and try turning it off again.

The LED connected to the ESP-01 has been turned on via the web.

If you succeed? Well, done. You’ve just replicated ninety percent of the functionality of an Internet connected light bulb and built your first Internet of Things thing.