Quick reference for the ESP8266

The Adafruit Feather HUZZAH board (image attribution: Adafruit).
Below is a quick reference for ESP8266-based boards. If it is your first timeworking with this board please consider reading the following sections first:
Installing MicroPython
See the corresponding section of tutorial:Getting started with MicroPython on the ESP8266. It also includesa troubleshooting subsection.
General board control
The MicroPython REPL is on UART0 (GPIO1=TX, GPIO3=RX) at baudrate 115200.Tab-completion is useful to find out what methods an object has.Paste mode (ctrl-E) is useful to paste a large slab of Python code intothe REPL.
Themachine module:
importmachinemachine.freq()# get the current frequency of the CPUmachine.freq(160000000)# set the CPU frequency to 160 MHz
Theesp module:
importespesp.osdebug(None)# turn off vendor O/S debugging messagesesp.osdebug(0)# redirect vendor O/S debugging messages to UART(0)
Networking
Thenetwork.WLAN class in thenetwork module:
importnetworkwlan=network.WLAN(network.WLAN.IF_STA)# create station interfacewlan.active(True)# activate the interfacewlan.scan()# scan for access pointswlan.isconnected()# check if the station is connected to an APwlan.connect('ssid','key')# connect to an APwlan.config('mac')# get the interface's MAC addresswlan.ipconfig('addr4')# get the interface's IPv4 addressesap=network.WLAN(network.WLAN.IF_AP)# create access-point interfaceap.active(True)# activate the interfaceap.config(ssid='ESP-AP')# set the SSID of the access point
A useful function for connecting to your local WiFi network is:
defdo_connect():importnetworkwlan=network.WLAN(network.WLAN.IF_STA)wlan.active(True)ifnotwlan.isconnected():print('connecting to network...')wlan.connect('ssid','key')whilenotwlan.isconnected():passprint('network config:',wlan.ipconfig('addr4'))
Once the network is established thesocket module can be usedto create and use TCP/UDP sockets as usual.
Delay and timing
Use thetime module:
importtimetime.sleep(1)# sleep for 1 secondtime.sleep_ms(500)# sleep for 500 millisecondstime.sleep_us(10)# sleep for 10 microsecondsstart=time.ticks_ms()# get millisecond counterdelta=time.ticks_diff(time.ticks_ms(),start)# compute time difference
Timers
Virtual (RTOS-based) timers are supported. Use themachine.Timer classwith timer ID of -1:
frommachineimportTimertim=Timer(-1)tim.init(period=5000,mode=Timer.ONE_SHOT,callback=lambdat:print(1))tim.init(period=2000,mode=Timer.PERIODIC,callback=lambdat:print(2))
The period is in milliseconds.
By default, timer callbacks are scheduled as soft interrupts on this port.Specifyhard=True to run them in hard interrupt context instead.
Pins and GPIO
Use themachine.Pin class:
frommachineimportPinp0=Pin(0,Pin.OUT)# create output pin on GPIO0p0.on()# set pin to "on" (high) levelp0.off()# set pin to "off" (low) levelp0.value(1)# set pin to on/highp2=Pin(2,Pin.IN)# create input pin on GPIO2print(p2.value())# get value, 0 or 1p4=Pin(4,Pin.IN,Pin.PULL_UP)# enable internal pull-up resistorp5=Pin(5,Pin.OUT,value=1)# set pin high on creation
Available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspondto the actual GPIO pin numbers of ESP8266 chip. Note that many end-userboards use their own adhoc pin numbering (marked e.g. D0, D1, …). AsMicroPython supports different boards and modules, physical pin numberingwas chosen as the lowest common denominator. For mapping between boardlogical pins and physical chip pins, consult your board documentation.
Note that Pin(1) and Pin(3) are REPL UART TX and RX respectively.Also note that Pin(16) is a special pin (used for wakeup from deepsleepmode) and may be not available for use with higher-level classes likeNeopixel.
There’s a higher-level abstractionmachine.Signalwhich can be used to invert a pin. Useful for illuminating active-low LEDsusingon() orvalue(1).
UART (serial bus)
Seemachine.UART.
frommachineimportUARTuart=UART(0,baudrate=9600)uart.write('hello')uart.read(5)# read up to 5 bytes
Two UARTs are available. UART0 is on Pins 1 (TX) and 3 (RX). UART0 isbidirectional, and by default is used for the REPL. UART1 is on Pins 2(TX) and 8 (RX) however Pin 8 is used to connect the flash chip, soUART1 is TX only.
When UART0 is attached to the REPL, all incoming chars on UART(0) gostraight to stdin so uart.read() will always return None. Usesys.stdin.read() if it’s needed to read characters from the UART(0)while it’s also used for the REPL (or detach, read, then reattach).When detached the UART(0) can be used for other purposes.
If there are no objects in any of the dupterm slots when the REPL is started (onhard or soft reset) then UART(0) is automaticallyattached. Without this, the only way to recover a board without a REPL would beto completely erase and reflash (which would install the default boot.py whichattaches the REPL).
To detach the REPL from UART0, use:
importosos.dupterm(None,1)
The REPL is attached by default. If you have detached it, to reattachit use:
importos,machineuart=machine.UART(0,115200)os.dupterm(uart,1)
PWM (pulse width modulation)
PWM can be enabled on all pins except Pin(16). There is a single frequencyfor all channels, with range between 1 and 1000 (measured in Hz). The dutycycle is between 0 and 1023 inclusive.
Use themachine.PWM class:
frommachineimportPin,PWMpwm0=PWM(Pin(0))# create PWM object from a pinpwm0.freq()# get current frequencypwm0.freq(1000)# set frequencypwm0.duty()# get current duty cyclepwm0.duty(200)# set duty cyclepwm0.deinit()# turn off PWM on the pinpwm2=PWM(Pin(2),freq=500,duty=512)# create and configure in one go
ADC (analog to digital conversion)
ADC is available on a dedicated pin.Note that input voltages on the ADC pin must be between 0v and 1.0v.
Use themachine.ADC class:
frommachineimportADCadc=ADC(0)# create ADC object on ADC pinadc.read()# read value, 0-1024
Software SPI bus
There are two SPI drivers. One is implemented in software (bit-banging)and works on all pins, and is accessed via themachine.SoftSPIclass:
frommachineimportPin,SoftSPI# construct an SPI bus on the given pins# polarity is the idle state of SCK# phase=0 means sample on the first edge of SCK, phase=1 means the secondspi=SoftSPI(baudrate=100000,polarity=1,phase=0,sck=Pin(0),mosi=Pin(2),miso=Pin(4))spi.init(baudrate=200000)# set the baudratespi.read(10)# read 10 bytes on MISOspi.read(10,0xff)# read 10 bytes while outputting 0xff on MOSIbuf=bytearray(50)# create a bufferspi.readinto(buf)# read into the given buffer (reads 50 bytes in this case)spi.readinto(buf,0xff)# read into the given buffer and output 0xff on MOSIspi.write(b'12345')# write 5 bytes on MOSIbuf=bytearray(4)# create a bufferspi.write_readinto(b'1234',buf)# write to MOSI and read from MISO into the bufferspi.write_readinto(buf,buf)# write buf to MOSI and read MISO back into buf
Hardware SPI bus
The hardware SPI is faster (up to 80Mhz), but only works on following pins:MISO is GPIO12,MOSI is GPIO13, andSCK is GPIO14. It has the samemethods as the bitbanging SPI class above, except for the pin parameters for theconstructor and init (as those are fixed):
frommachineimportPin,SPIhspi=SPI(1,baudrate=80000000,polarity=0,phase=0)
(SPI(0) is used for FlashROM and not available to users.)
I2C bus
The I2C driver is implemented in software and works on all pins,and is accessed via themachine.I2C class (which is analias ofmachine.SoftI2C):
frommachineimportPin,I2C# construct an I2C busi2c=I2C(scl=Pin(5),sda=Pin(4),freq=100000)i2c.readfrom(0x3a,4)# read 4 bytes from peripheral device with address 0x3ai2c.writeto(0x3a,'12')# write '12' to peripheral device with address 0x3abuf=bytearray(10)# create a buffer with 10 bytesi2c.writeto(0x3a,buf)# write the given buffer to the peripheral
Real time clock (RTC)
Seemachine.RTC
frommachineimportRTCrtc=RTC()rtc.datetime((2017,8,23,0,1,12,48,0))# set a specific date and# time, eg. 2017/8/23 1:12:48# the day-of-week value is ignoredrtc.datetime()# get date and time# synchronize with ntp# need to be connected to wifiimportntptimentptime.settime()# set the rtc datetime from the remote serverrtc.datetime()# get the date and time in UTC
Note
Not all methods are implemented:RTC.now(),RTC.irq(handler=*)(using a custom handler),RTC.init() andRTC.deinit() arecurrently not supported.
WDT (Watchdog timer)
Seemachine.WDT.
frommachineimportWDT# enable the WDTwdt=WDT()wdt.feed()
Deep-sleep mode
Connect GPIO16 to the reset pin (RST on HUZZAH). Then the following codecan be used to sleep, wake and check the reset cause:
importmachine# configure RTC.ALARM0 to be able to wake the devicertc=machine.RTC()rtc.irq(trigger=rtc.ALARM0,wake=machine.DEEPSLEEP)# check if the device woke from a deep sleepifmachine.reset_cause()==machine.DEEPSLEEP_RESET:print('woke from a deep sleep')# set RTC.ALARM0 to fire after 10 seconds (waking the device)rtc.alarm(rtc.ALARM0,10000)# put the device to sleepmachine.deepsleep()
OneWire driver
The OneWire driver is implemented in software and works on all pins:
frommachineimportPinimportonewireow=onewire.OneWire(Pin(12))# create a OneWire bus on GPIO12ow.scan()# return a list of devices on the busow.reset()# reset the busow.readbyte()# read a byteow.writebyte(0x12)# write a byte on the busow.write('123')# write bytes on the busow.select_rom(b'12345678')# select a specific device by its ROM code
There is a specific driver for DS18S20 and DS18B20 devices:
importtime,ds18x20ds=ds18x20.DS18X20(ow)roms=ds.scan()ds.convert_temp()time.sleep_ms(750)forrominroms:print(ds.read_temp(rom))
Be sure to put a 4.7k pull-up resistor on the data line. Note thattheconvert_temp() method must be called each time you want tosample the temperature.
NeoPixel driver
Use theneopixel module:
frommachineimportPinfromneopixelimportNeoPixelpin=Pin(0,Pin.OUT)# set GPIO0 to output to drive NeoPixelsnp=NeoPixel(pin,8)# create NeoPixel driver on GPIO0 for 8 pixelsnp[0]=(255,255,255)# set the first pixel to whitenp.write()# write data to all pixelsr,g,b=np[0]# get first pixel colour
Warning
By defaultNeoPixel is configured to control the more popular800kHzunits. It is possible to use alternative timing to control other (typically400kHz) devices by passingtiming=0 when constructing theNeoPixel object.
For low-level driving of a NeoPixel seemachine.bitstream.
APA102 driver
Use theapa102 module:
frommachineimportPinfromapa102importAPA102clock=Pin(14,Pin.OUT)# set GPIO14 to output to drive the clockdata=Pin(13,Pin.OUT)# set GPIO13 to output to drive the dataapa=APA102(clock,data,8)# create APA102 driver on the clock and the data pin for 8 pixelsapa[0]=(255,255,255,31)# set the first pixel to white with a maximum brightness of 31apa.write()# write data to all pixelsr,g,b,brightness=apa[0]# get first pixel colour
For low-level driving of an APA102:
importespesp.apa102_write(clock_pin,data_pin,rgbi_buf)
DHT driver
The DHT driver is implemented in software and works on all pins:
importdhtimportmachined=dht.DHT11(machine.Pin(4))d.measure()d.temperature()# eg. 23 (°C)d.humidity()# eg. 41 (% RH)d=dht.DHT22(machine.Pin(4))d.measure()d.temperature()# eg. 23.6 (°C)d.humidity()# eg. 41.3 (% RH)
SSD1306 driver
Driver for SSD1306 monochrome OLED displays. See tutorialUsing a SSD1306 OLED display.
frommachineimportPin,I2Cimportssd1306i2c=I2C(scl=Pin(5),sda=Pin(4),freq=100000)display=ssd1306.SSD1306_I2C(128,64,i2c)display.text('Hello World',0,0,1)display.show()
WebREPL (web browser interactive prompt)
WebREPL (REPL over WebSockets, accessible via a web browser) is anexperimental feature available in ESP8266 port. Download web clientfromhttps://github.com/micropython/webrepl (hosted version availableathttp://micropython.org/webrepl), and configure it by executing:
importwebrepl_setup
and following on-screen instructions. After reboot, it will be availablefor connection. If you disabled automatic start-up on boot, you mayrun configured daemon on demand using:
importwebreplwebrepl.start()
The supported way to use WebREPL is by connecting to ESP8266 access point,but the daemon is also started on STA interface if it is active, so if yourrouter is set up and works correctly, you may also use WebREPL while connectedto your normal Internet access point (use the ESP8266 AP connection methodif you face any issues).
Besides terminal/command prompt access, WebREPL also has provision for filetransfer (both upload and download). Web client has buttons for thecorresponding functions, or you can use command-line clientwebrepl_cli.pyfrom the repository above.
See the MicroPython forum for other community-supported alternativesto transfer files to ESP8266.