Arduino Core Documentation

Digital IO
Pin numbers in Arduino correspond directly to the ESP8266 GPIO pin numbers. pinMode, digitalRead, and
digitalWrite functions work as usual, so to read GPIO2, call digitalRead(2).
Digital pins 0—15 can be INPUT, OUTPUT, or INPUT_PULLUP. Pin 16 can be INPUT, OUTPUT or
INPUT_PULLDOWN_16. At startup, pins are configured as INPUT.
Pins may also serve other functions, like Serial, I2C, SPI. These functions are normally activated by the corresponding
library. The diagram below shows pin mapping for the popular ESP-12 module

Digital pins 6—11 are not shown on this diagram because they are used to connect flash memory chip on most modules.
Trying to use these pins as IOs will likely cause the program to crash.
Note that some boards and modules (ESP-12ED, NodeMCU 1.0) also break out pins 9 and 11. These may be used as
IO if flash chip works in DIO mode (as opposed to QIO, which is the default one).
Pin interrupts are supported through attachInterrupt, detachInterrupt functions. Interrupts may be attached to any GPIO pin, except GPIO16. Standard Arduino interrupt types are supported: CHANGE, RISING,
FALLING.
Analog input
ESP8266 has a single ADC channel available to users. It may be used either to read voltage at ADC pin, or to read
module supply voltage (VCC).
To read external voltage applied to ADC pin, use analogRead(A0). Input voltage range is 0 — 1.0V.
To read VCC voltage, use ESP.getVcc() and ADC pin must be kept unconnected. Additionally, the following line
has to be added to the sketch:
ADC_MODE(ADC_VCC);
This line has to appear outside of any functions, for instance right after the #include lines of your sketch.
Analog output
analogWrite(pin, value) enables software PWM on the given pin. PWM may be used on pins 0 to 16. Call
analogWrite(pin, 0) to disable PWM on the pin. value may be in range from 0 to PWMRANGE, which is
equal to 1023 by default. PWM range may be changed by calling analogWriteRange(new_range).
PWM frequency is 1kHz by default. Call analogWriteFreq(new_frequency) to change the frequency.
Timing and delays
millis() and micros() return the number of milliseconds and microseconds elapsed after reset, respectively.
delay(ms) pauses the sketch for a given number of milliseconds and allows WiFi and TCP/IP tasks to run.
delayMicroseconds(us) pauses for a given number of microseconds.
Remember that there is a lot of code that needs to run on the chip besides the sketch when WiFi is connected. WiFi
and TCP/IP libraries get a chance to handle any pending events each time the loop() function completes, OR when
delay is called. If you have a loop somewhere in your sketch that takes a lot of time (>50ms) without calling delay,
you might consider adding a call to delay function to keep the WiFi stack running smoothly.
There is also a yield() function which is equivalent to delay(0). The delayMicroseconds function, on the
other hand, does not yield to other tasks, so using it for delays more than 20 milliseconds is not recommended.
Serial
Serial object works much the same way as on a regular Arduino. Apart from hardware FIFO (128 bytes for TX and
RX) HardwareSerial has additional 256-byte TX and RX buffers. Both transmit and receive is interrupt-driven. Write
and read functions only block the sketch execution when the respective FIFO/buffers are full/empty.
6 Chapter 2. Reference
ESP8266 Arduino Core Documentation, Release 2.4.0
Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15
(TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0
back to GPIO1 and GPIO3.
Serial1 uses UART1, TX pin is GPIO2. UART1 can not be used to receive data because normally it’s RX pin is
occupied for flash chip connection. To use Serial1, call Serial1.begin(baudrate).
If Serial1 is not used and Serial is not swapped - TX for UART0 can be mapped to GPIO2 instead by calling
Serial.set_tx(2) after Serial.begin or directly with Serial.begin(baud, config, mode, 2).
By default the diagnostic output from WiFi libraries is disabled when you call Serial.begin. To enable debug output again, call Serial.setDebugOutput(true). To redirect debug output to Serial1 instead, call
Serial1.setDebugOutput(true).
You also need to use Serial.setDebugOutput(true) to enable output from printf() function.
Both Serial and Serial1 objects support 5, 6, 7, 8 data bits, odd (O), even (E), and no (N) parity, and
1 or 2 stop bits. To set the desired mode, call Serial.begin(baudrate, SERIAL_8N1), Serial.
begin(baudrate, SERIAL_6E2), etc.
A new method has been implemented on both Serial and Serial1 to get current baud rate setting. To get the
current baud rate, call Serial.baudRate(), Serial1.baudRate(). Return a int of current speed. For

I’ve done this also for official ESP8266 Software Serial library, see this pull request.
Note that this implementation is only for ESP8266 based boards, and will not works with other Arduino boards.
Progmem
The Program memory features work much the same way as on a regular Arduino; placing read only data and strings in
read only memory and freeing heap for your application. The important difference is that on the ESP8266 the literal
strings are not pooled. This means that the same literal string defined inside a F("") and/or PSTR("") will take up
space for each instance in the code. So you will need to manage the duplicate strings yourself.
There is one additional helper macro to make it easier to pass const PROGMEM strings to methods that take a
__FlashStringHelper called FPSTR(). The use of this will help make it easier to pool strings. Not pooling

1 Like

WiFi(ESP8266WiFi library)
ESP8266WiFi library has been developed basing on ESP8266 SDK, using naming convention and overall functionality
philosophy of the Arduino WiFi Shield library. Over time the wealth Wi-Fi features ported from ESP8266 SDK to this
library outgrew the APIs of WiFi Shield library and it became apparent that we need to provide separate documentation
on what is new and extra.
ESP8266WiFi library documentation.
Ticker
Library for calling functions repeatedly with a certain period. Two examples included.
It is currently not recommended to do blocking IO operations (network, serial, file) from Ticker callback functions.
Instead, set a flag inside the ticker callback and check for that flag inside the loop function.
Here is library to simplificate Ticker usage and avoid WDT reset: TickerScheduler
EEPROM
This is a bit different from standard EEPROM class. You need to call EEPROM.begin(size) before you start
reading or writing, size being the number of bytes you want to use. Size can be anywhere between 4 and 4096 bytes.
EEPROM.write does not write to flash immediately, instead you must call EEPROM.commit() whenever you wish
to save changes to flash. EEPROM.end() will also commit, and will release the RAM copy of EEPROM contents.
EEPROM library uses one sector of flash located just after the SPIFFS.
Three examples included.
9
ESP8266 Arduino Core Documentation, Release 2.4.0
I2C (Wire library)
Wire library currently supports master mode up to approximately 450KHz. Before using I2C, pins for SDA and SCL
need to be set by calling Wire.begin(int sda, int scl), i.e. Wire.begin(0, 2) on ESP-01, else they
default to pins 4(SDA) and 5(SCL).
SPI
SPI library supports the entire Arduino SPI API including transactions, including setting phase (CPHA). Setting the
Clock polarity (CPOL) is not supported, yet (SPI_MODE2 and SPI_MODE3 not working).
The usual SPI pins are:
• MOSI = GPIO13
• MISO = GPIO12
• SCLK = GPIO14
There’s an extended mode where you can swap the normal pins to the SPI0 hardware pins. This is enabled by calling
SPI.pins(6, 7, 8, 0) before the call to SPI.begin(). The pins would change to:
• MOSI = SD1
• MISO = SD0
• SCLK = CLK
• HWCS = GPIO0
This mode shares the SPI pins with the controller that reads the program code from flash and is controlled by a
hardware arbiter (the flash has always higher priority). For this mode the CS will be controlled by hardware as you
can’t handle the CS line with a GPIO, you never actually know when the arbiter is going to grant you access to the bus
so you must let it handle CS automatically.
SoftwareSerial
An ESP8266 port of SoftwareSerial library done by Peter Lerup (@plerup) supports baud rate up to 115200 and multiples SoftwareSerial instances. See https://github.com/plerup/espsoftwareserial if you want to suggest an improvement
or open an issue related to SoftwareSerial.
ESP-specific APIs
Some ESP-specific APIs related to deep sleep, RTC and flash memories are available in the ESP object.
ESP.deepSleep(microseconds, mode) will put the chip into deep sleep. mode is one of
WAKE_RF_DEFAULT, WAKE_RFCAL, WAKE_NO_RFCAL, WAKE_RF_DISABLED. (GPIO16 needs to be tied to
RST to wake from deepSleep.)
ESP.rtcUserMemoryWrite(offset, &data, sizeof(data)) and ESP.
rtcUserMemoryRead(offset, &data, sizeof(data)) allow data to be stored in and retrieved
from the RTC user memory of the chip respectively. Total size of RTC user memory is 512 bytes, so offset +
sizeof(data) shouldn’t exceed 512. Data should be 4-byte aligned. The stored data can be retained between
deep sleep cycles. However, the data might be lost after power cycling the chip.
10 Chapter 3. Libraries
ESP8266 Arduino Core Documentation, Release 2.4.0
ESP.restart() restarts the CPU.
ESP.getResetReason() returns a String containing the last reset reason in human readable format.
ESP.getFreeHeap() returns the free heap size.
ESP.getChipId() returns the ESP8266 chip ID as a 32-bit integer.
ESP.getCoreVersion() returns a String containing the core version.
ESP.getSdkVersion() returns the SDK version as a char.
ESP.getCpuFreqMHz() returns the CPU frequency in MHz as an unsigned 8-bit integer.
ESP.getSketchSize() returns the size of the current sketch as an unsigned 32-bit integer.
ESP.getFreeSketchSpace() returns the free sketch space as an unsigned 32-bit integer.
ESP.getSketchMD5() returns a lowercase String containing the MD5 of the current sketch.
ESP.getFlashChipId() returns the flash chip ID as a 32-bit integer.
ESP.getFlashChipSize() returns the flash chip size, in bytes, as seen by the SDK (may be less than actual
size).
ESP.getFlashChipRealSize() returns the real chip size, in bytes, based on the flash chip ID.
ESP.getFlashChipSpeed(void) returns the flash chip frequency, in Hz.
ESP.getCycleCount() returns the cpu instruction cycle count since start as an unsigned 32-bit. This is useful for
accurate timing of very short actions like bit banging.
ESP.getVcc() may be used to measure supply voltage. ESP needs to reconfigure the ADC at startup in order for
this feature to be available. Add the following line to the top of your sketch to use getVcc:
ADC_MODE(ADC_VCC);
TOUT pin has to be disconnected in this mode.
Note that by default ADC is configured to read from TOUT pin using analogRead(A0), and ESP.getVCC() is
not available.
mDNS and DNS-SD responder (ESP8266mDNS library)
Allows the sketch to respond to multicast DNS queries for domain names like “foo.local”, and DNS-SD (service
discovery) queries. See attached example for details.
SSDP responder (ESP8266SSDP)
SSDP is another service discovery protocol, supported on Windows out of the box. See attached example for reference.
DNS server (DNSServer library)
Implements a simple DNS server that can be used in both STA and AP modes. The DNS server currently supports
only one domain (for all other domains it will reply with NXDOMAIN or custom status code). With it, clients can
open a web server running on ESP8266 using a domain name, not an IP address.
3.8. mDNS and DNS-SD responder (ESP8266mDNS library) 11
ESP8266 Arduino Core Documentation, Release 2.4.0
Servo
This library exposes the ability to control RC (hobby) servo motors. It will support upto 24 servos on any available
output pin. By defualt the first 12 servos will use Timer0 and currently this will not interfere with any other support.
Servo counts above 12 will use Timer1 and features that use it will be effected. While many RC servo motors will
accept the 3.3V IO data pin from a ESP8266, most will not be able to run off 3.3v and will require another power
source that matches their specifications. Make sure to connect the grounds between the ESP8266 and the servo motor
power supply.
Other libraries (not included with the IDE)
Libraries that don’t rely on low-level access to AVR registers should work well. Here are a few libraries that were
verified to work:
• Adafruit_ILI9341 - Port of the Adafruit ILI9341 for the ESP8266
• arduinoVNC - VNC Client for Arduino
• arduinoWebSockets - WebSocket Server and Client compatible with ESP8266 (RFC6455)
• aREST - REST API handler library.
• Blynk - easy IoT framework for Makers (check out the Kickstarter page).
• DallasTemperature
• DHT-sensor-library - Arduino library for the DHT11/DHT22 temperature and humidity sensors. Download
latest v1.1.1 library and no changes are necessary. Older versions should initialize DHT as follows: DHT
dht(DHTPIN, DHTTYPE, 15)
• DimSwitch - Control electronic dimmable ballasts for fluorescent light tubes remotely as if using a wall switch.
• Encoder - Arduino library for rotary encoders. Version 1.4 supports ESP8266.
• esp8266_mdns - mDNS queries and responses on esp8266. Or to describe it another way: An mDNS Client or
Bonjour Client library for the esp8266.
• ESPAsyncTCP - Asynchronous TCP Library for ESP8266 and ESP32/31B
• ESPAsyncWebServer - Asynchronous Web Server Library for ESP8266 and ESP32/31B
• Homie for ESP8266 - Arduino framework for ESP8266 implementing Homie, an MQTT convention for the IoT.
• NeoPixel - Adafruit’s NeoPixel library, now with support for the ESP8266 (use version 1.0.2 or higher from
Arduino’s library manager).
• NeoPixelBus - Arduino NeoPixel library compatible with ESP8266. Use the “DmaDriven” or “UartDriven”
branches for ESP8266. Includes HSL color support and more.
• PubSubClient - MQTT library by @Imroy.
• RTC - Arduino Library for Ds1307 & Ds3231 compatible with ESP8266.
• Souliss, Smart Home - Framework for Smart Home based on Arduino, Android and openHAB.
• ST7735 - Adafruit’s ST7735 library modified to be compatible with ESP8266. Just make sure to modify the
pins in the examples as they are still AVR specific.
• Task - Arduino Nonpreemptive multitasking library. While similiar to the included Ticker library in the functionality provided, this library was meant for cross Arduino compatibility.
• TickerScheduler - Library provides simple scheduler for Ticker to avoid WDT reset
12 Chapter 3. Libraries
ESP8266 Arduino Core Documentation, Release 2.4.0
• Teleinfo - Generic French Power Meter library to read Teleinfo energy monitoring data such as consuption,
contract, power, period, … This library is cross platform, ESP8266, Arduino, Particle, and simple C++. French
dedicated post on author’s blog and all related information about Teleinfo also available.
• UTFT-ESP8266 - UTFT display library with support for ESP8266. Only serial interface (SPI) displays are
supported for now (no 8-bit parallel mode, etc). Also includes support for the hardware SPI controller of the
ESP8266.
• WiFiManager - WiFi Connection manager with web captive portal. If it can’t connect, it starts AP mode and a
configuration portal so you can choose and enter WiFi credentials.
• OneWire - Library for Dallas/Maxim 1-Wire Chips.
• Adafruit-PCD8544-Nokia-5110-LCD-Library - Port of the Adafruit PCD8544 - library for the ESP8266.
• PCF8574_ESP - A very simplistic library for using the PCF857//PCF8574A I2C 8-pin GPIO-expander.
• Dot Matrix Display Library 2 - Freetronics DMD & Generic 16 x 32 P10 style Dot Matrix Display Library
• SdFat-beta - SD-card library with support for long filenames, software- and hardware-based SPI and lots more.
• FastLED - a library for easily & efficiently controlling a wide variety of LED chipsets, like the Neopixel
(WS2812B), DotStar, LPD8806 and many more. Includes fading, gradient, color conversion functions.
• OLED - a library for controlling I2C connected OLED displays. Tested with 0.96 inch OLED graphics display.
• MFRC522 - A library for using the Mifare RC522 RFID-tag reader/writer.
• Ping - lets the ESP8266 ping a remote machine.
• AsyncPing - fully asynchronous Ping library (have full ping statistic and hardware MAC

1 Like

File system limitations
The filesystem implementation for ESP8266 had to accomodate the constraints of the chip, among which its limited
RAM. SPIFFS was selected because it is designed for small systems, but that comes at the cost of some simplifications
and limitations.
First, behind the scenes, SPIFFS does not support directories, it just stores a “flat” list of files. But contrary to
traditional filesystems, the slash character ‘/’ is allowed in filenames, so the functions that deal with directory listing
(e.g. openDir("/website")) basically just filter the filenames and keep the ones that start with the requested
prefix (/website/). Practically speaking, that makes little difference though.
Second, there is a limit of 32 chars in total for filenames. One ‘\0’ char is reserved for C string termination, so that
leaves us with 31 usable characters.
Combined, that means it is advised to keep filenames short and not use deeply nested directories, as the full path of
each file (including directories, ‘/’ characters, base name, dot and extension) has to be 31 chars at a maximum. For
example, the filename /website/images/bird_thumbnail.jpg is 34 chars and will cause some problems if
used, for example in exists() or in case another file starts with the same first 31 characters.
Warning: That limit is easily reached and if ignored, problems might go unnoticed because no error message will
appear at compilation nor runtime.
For more details on the internals of SPIFFS implementation, see the SPIFFS readme file.
Uploading files to file system
ESP8266FS is a tool which integrates into the Arduino IDE. It adds a menu item to Tools menu for uploading the
contents of sketch data directory into ESP8266 flash file system.
• Download the tool: https://github.com/esp8266/arduino-esp8266fs-plugin/releases/download/0.3.0/
ESP8266FS-0.3.0.zip.
• In your Arduino sketchbook directory, create tools directory if it doesn’t exist yet
• Unpack the tool into tools directory (the path will look like <home_dir>/Arduino/tools/
ESP8266FS/tool/esp8266fs.jar)
• Restart Arduino IDE
• Open a sketch (or create a new one and save it)
• Go to sketch directory (choose Sketch > Show Sketch Folder)
• Create a directory named data and any files you want in the file system there
• Make sure you have selected a board, port, and closed Serial Monitor
• Select Tools > ESP8266 Sketch Data Upload. This should start uploading the files into ESP8266 flash file
system. When done, IDE status bar will display SPIFFS Image Uploaded message.
16 Chapter 4. Filesystem
ESP8266 Arduino Core Documentation, Release 2.4.0
File system object (SPIFFS)
begin
SPIFFS.begin()
This method mounts SPIFFS file system. It must be called before any other FS APIs are used. Returns true if file
system was mounted successfully, false otherwise.
end
SPIFFS.end()
This method unmounts SPIFFS file system. Use this method before updating SPIFFS using OTA.
format
SPIFFS.format()
Formats the file system. May be called either before or after calling begin. Returns true if formatting was successful.
open
SPIFFS.open(path, mode)
Opens a file. path should be an absolute path starting with a slash (e.g. /dir/filename.txt). mode is a string
specifying access mode. It can be one of “r”, “w”, “a”, “r+”, “w+”, “a+”. Meaning of these modes is the same as for
fopen C function.
r Open text file for reading. The stream is positioned at the
beginning of the file.
r+ Open for reading and writing. The stream is positioned at the
beginning of the file.
w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is
positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is
created if it does not exist. The stream is positioned at the
end of the file.
a+ Open for reading and appending (writing at end of file). The
file is created if it does not exist. The initial file
position for reading is at the beginning of the file, but
output is always appended to the end of the file.
4.4. File system object (SPIFFS) 17
ESP8266 Arduino Core Documentation, Release 2.4.0
Returns File object. To check whether the file was opened successfully, use the boolean operator.
File f = SPIFFS.open("/f.txt", “w”);
if (!f) {
Serial.println(“file open failed”);
}
exists
SPIFFS.exists(path)
Returns true if a file with given path exists, false otherwise.
openDir
SPIFFS.openDir(path)
Opens a directory given its absolute path. Returns a Dir object.
remove
SPIFFS.remove(path)
Deletes the file given its absolute path. Returns true if file was deleted successfully.
rename
SPIFFS.rename(pathFrom, pathTo)
Renames file from pathFrom to pathTo. Paths must be absolute. Returns true if file was renamed successfully.
info
FSInfo fs_info;
SPIFFS.info(fs_info);
Fills FSInfo structure with information about the file system. Returns true is successful, false otherwise.
Filesystem information structure
struct FSInfo {
size_t totalBytes;
size_t usedBytes;
size_t blockSize;
size_t pageSize;
size_t maxOpenFiles;
size_t maxPathLength;
};
18 Chapter 4. Filesystem
ESP8266 Arduino Core Documentation, Release 2.4.0
This is the structure which may be filled using FS::info method. - totalBytes — total size of useful data on the file
system - usedBytes — number of bytes used by files - blockSize — SPIFFS block size - pageSize — SPIFFS
logical page size - maxOpenFiles — max number of files which may be open simultaneously - maxPathLength

1 Like

1 Like
© 2017 GitHub, Inc.
with by
GitHub Education