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.

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.

Original board (left), and 1MB flash version (right).
The unusual pinout of the ESP-01 breakout board.

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.

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.

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.

The ESP-01 wired up to an FTDI adaptor using a breadboard in 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.

$ sudo python get-pip.py
$ sudo pip install pyserial
$ 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}
$ ls -l /dev/tty* | grep usb
crw-rw-rw- 1 root wheel 11, 66 4 Jan 14:15 /dev/tty.usbserial-A9048F6Z
$
$ 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…
$

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
ATOK
AT+GMR00170901OK
AT+CWMODE=1OKAT+RSTOKets 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
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
AT+CWJAP=”SSID”,”PASSWORD”OK
AT+CWJAP?+CWJAP:”Babilim”OK
AT+CIFSR
192.168.1.223
AT+CWQAPOK
AT+CIFSR
ERROR
AT+CIPMUX=1OK
AT+CIPSTART=0,”TCP”,”www.google.com",80
OK
Linked
AT+CIPSEND=0,18> GET / HTTP/1.0SEND 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
Talking to the ESP-01 using CoolTerm.
AT+CIPSEND=0,18> GET http://www.google.co.uk/?gfe_rd=cr&ei=SqmJVsrQI-7S8Afcq5wI HTTP/1.1SEND OK
The tail end of the actual Google home page.

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.

$ 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…
$
The ESP-01 with the NodeMCU running Lua.
Wiring for attaching an LED to +GPIO2+ on the ESP-01.
> pin = 4
> gpio.mode(pin,gpio.OUTPUT)
> gpio.write(pin,gpio.HIGH)
> gpio.write(pin,gpio.LOW)
>
Mapping between GPIO Pin number and IO Index.
-- 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
$ esp port set /dev/tty.usbserial-A9048F6Z
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)
$ esp file write webserver.lua
$ esp file list
266 bytes webserver.lua
$ esp file execute webserver.lua

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.

$ esp file write webserver.lua init.lua
$ esp file list
266 bytes init.lua
266 bytes webserver.lua
$ esp restart
The ESP-01 with a simple Lua webserver.
$ 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

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.

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.

Installing the Arduino Development Environment

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

The Arduino Development Environment.

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.

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

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.

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.
Selecting a generic ESP8266 based 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”);
}
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”
tools.esptool.upload.pattern=”PATH/esptool.py” — port “{serial.port}” write_flash 0x00000 “{build.path}/{build.project_name}.bin”
Connecting to Wireless Network
…….
WiFi connected
Server started
192.168.1.224
Toggling an LED with the Arduino web server sketch.
new client
GET /gpio/1 HTTP/1.1
Client disconnected
new client
GET /favicon.ico HTTP/1.1
invalid request
The LED connected to the ESP-01 has been turned on via the web.

Scientist, Author, Hacker, Maker, and Journalist.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store