docs: Migrate docs

This commit is contained in:
radim.karnis
2021-11-10 15:39:54 +01:00
parent a15fd2134e
commit 9af961540f
33 changed files with 1918 additions and 1515 deletions

View File

@@ -271,7 +271,7 @@ build_docs:
script:
- cd docs
- pip install -r requirements.txt
- build-docs -l en
- build-docs -l en -t {esp8266,esp32,esp32s2,esp32c3,esp32s3}
.deploy_docs_template:
stage: deploy_docs

487
README.md
View File

@@ -1,488 +1,21 @@
# esptool.py
A Python-based, open source, platform independent, utility to communicate with the ROM bootloader in Espressif ESP8266 & ESP32 series chips.
A Python-based, open-source, platform-independent utility to communicate with the ROM bootloader in Espressif chips.
esptool.py was started by Fredrik Ahlberg (@[themadinventor](https://github.com/themadinventor/)) as an unofficial community project. Later, it was maintained by Angus Gratton (@[projectgus](https://github.com/projectgus/)). It is now supported by Espressif Systems.
[![Test esptool](https://github.com/espressif/esptool/actions/workflows/test_esptool.yml/badge.svg?branch=master)](https://github.com/espressif/esptool/actions/workflows/test_esptool.yml) [![Build esptool](https://github.com/espressif/esptool/actions/workflows/build_esptool.yml/badge.svg?branch=master)](https://github.com/espressif/esptool/actions/workflows/build_esptool.yml)
esptool.py is Free Software under a GPLv2 license.
## Documentation
[![Test esptool](https://github.com/espressif/esptool/actions/workflows/test_esptool.yml/badge.svg?branch=master)](https://github.com/espressif/esptool/actions/workflows/test_esptool.yml)[![Build esptool](https://github.com/espressif/esptool/actions/workflows/build_esptool.yml/badge.svg?branch=master)](https://github.com/espressif/esptool/actions/workflows/build_esptool.yml)
Visit the [documentation](https://docs.espressif.com/projects/esptool/) or run `esptool.py -h`.
## Installation / dependencies
### Easy Installation
You will need [either Python 2.7 or Python 3.4 or newer](https://www.python.org/downloads/) installed on your system.
The latest stable esptool.py release can be installed from [pypi](http://pypi.python.org/pypi/esptool) via pip:
```
$ pip install esptool
```
With some Python installations this may not work and you'll receive an error, try `python -m pip install esptool` or `pip2 install esptool`, or consult your [Python installation manual](https://pip.pypa.io/en/stable/installing/) for information about how to access pip.
[Setuptools](https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html) is also a requirement which is not available on all systems by default. You can install it by a package manager of your operating system, or by `pip install setuptools`.
After installing, you will have `esptool.py` installed into the default Python executables directory and you should be able to run it with the command `esptool.py` or `python -m esptool`. Please note that probably only `python -m esptool` will work for Pythons installed from Windows Store.
### Development Mode Installation
Development mode allows you to run the latest development version from this repository.
```sh
$ git clone https://github.com/espressif/esptool.git
$ cd esptool
$ pip install --user -e .
```
This will install esptool's dependencies and create some executable script wrappers in the user's `bin` directory. The wrappers will run the scripts found in the git working directory directly, so any time the working directory contents change it will pick up the new versions.
It's also possible to run the scripts directly from the working directory with this Development Mode installation.
(Note: if you actually plan to do development work with esptool itself, see the CONTRIBUTING.md file.)
## Usage
Use `esptool.py -h` to see a summary of all available commands and command line options.
To see all options for a particular command, append `-h` to the command name. ie `esptool.py write_flash -h`.
## Common Options
### Serial Port
* The serial port is selected using the `-p` option, like `-p /dev/ttyUSB0` (Linux and macOS) or `-p COM1` (Windows).
* A default serial port can be specified by setting the `ESPTOOL_PORT` environment variable.
* If no `-p` option or `ESPTOOL_PORT` value is specified, `esptool.py` will enumerate all connected serial ports and try each one until it finds an Espressif device connected (new behaviour in v2.4.0).
Note: Windows and macOS may require drivers to be installed for a particular USB/serial adapter, before a serial port is available. Consult the documentation for your particular device. On macOS, you can also consult [System Information](https://support.apple.com/en-us/HT203001)'s list of USB devices to identify the manufacturer or device ID when the adapter is plugged in. On Windows, you can use [Windows Update or Device Manager](https://support.microsoft.com/en-us/help/15048/windows-7-update-driver-hardware-not-working-properly) to find a driver.
If using Cygwin or WSL on Windows, you have to convert the Windows-style name into a Unix-style path (`COM1` -> `/dev/ttyS0`, and so on). (This is not necessary if using ESP-IDF for ESP32 with the supplied Windows MSYS2 environment, this environment uses a native Windows Python which accepts COM ports as-is.)
In Linux, the current user may not have access to serial ports and a "Permission Denied" error will appear. On most Linux distributions, the solution is to add the user to the `dialout` group with a command like `sudo usermod -a -G dialout <USERNAME>`. Check your Linux distribution's documentation for more information.
### Baud rate
The default esptool.py baud rate is 115200bps. Different rates may be set using `-b 921600` (or another baud rate of your choice). A default baud rate can also be specified using the `ESPTOOL_BAUD` environment variable. This can speed up `write_flash` and `read_flash` operations.
The baud rate is limited to 115200 when esptool.py establishes the initial connection, higher speeds are only used for data transfers.
Most hardware configurations will work with `-b 230400`, some with `-b 460800`, `-b 921600` and/or `-b 1500000` or higher.
If you have connectivity problems then you can also set baud rates below 115200. You can also choose 74880, which is the usual baud rate used by the ESP8266 to output [boot log](https://github.com/espressif/esptool/wiki/ESP8266-Boot-ROM-Log) information.
## Commands
### Write binary data to flash: write_flash
Binary data can be written to the ESP's flash chip via the serial `write_flash` command:
```
esptool.py --port COM4 write_flash 0x1000 my_app-0x01000.bin
```
Multiple flash addresses and file names can be given on the same command line:
```
esptool.py --port COM4 write_flash 0x00000 my_app.elf-0x00000.bin 0x40000 my_app.elf-0x40000.bin
```
The `--chip` argument is optional when writing to flash, esptool will detect the type of chip when it connects to the serial port.
The `--port` argument is documented under [Serial Port](#serial-port).
The next arguments to write_flash are one or more pairs of offset (address) and file name. When generating ESP8266 "version 1" images, the file names created by `elf2image` include the flash offsets as part of the file name. For other types of images, consult your SDK documentation to determine the files to flash at which offsets.
Numeric values passed to write_flash (and other commands) can be specified either in hex (ie 0x1000), or in decimal (ie 4096).
See the [Troubleshooting](#troubleshooting) section if the write_flash command is failing, or the flashed module fails to boot.
#### Setting flash mode and size
You may also need to specify arguments for [flash mode and flash size](#flash-modes), if you wish to override the defaults. For example:
```
esptool.py --port /dev/ttyUSB0 write_flash --flash_mode qio --flash_size 32m 0x0 bootloader.bin 0x1000 my_app.bin
```
Since esptool v2.0, these options are not often needed as the default is to keep the flash mode and size from the `.bin` image file. See the [Flash Modes](#flash-modes) section for more details.
#### Compression
By default, the serial transfer data is compressed for better performance. The `-u/--no-compress` option disables this behaviour.
#### Erasing flash before write
To successfully write data into flash, all 4096-byte memory sectors (the smallest erasable unit) affected by the operation have to be erased first. As a result, when the flashing offset address or the data are not 4096-byte aligned, more memory is erased than actually needed. Esptool will display information about which flash memory sectors will be erased.
Use the `-e/--erase-all` option to erase all flash sectors (not just write areas) before programming.
### Read Flash Contents: read_flash
The read_flash command allows reading back the contents of flash. The arguments to the command are an address, a size, and a filename to dump the output to. For example, to read a full 2MB of attached flash:
```
esptool.py -p PORT -b 460800 read_flash 0 0x200000 flash_contents.bin
```
(Note that if `write_flash` updated the boot image's [flash mode and flash size](#flash-modes) during flashing then these bytes may be different when read back.)
### Erase Flash: erase_flash & erase region
To erase the entire flash chip (all data replaced with 0xFF bytes):
```
esptool.py erase_flash
```
To erase a region of the flash, starting at address 0x20000 with length 0x4000 bytes (16KB):
```
esptool.py erase_region 0x20000 0x4000
```
The address and length must both be multiples of the SPI flash erase sector size. This is 0x1000 (4096) bytes for supported flash chips.
### Read built-in MAC address: read_mac
```
esptool.py read_mac
```
### Read SPI flash id: flash_id
```
esptool.py flash_id
```
Example output:
```
Manufacturer: e0
Device: 4016
Detected flash size: 4MB
```
Refer to [flashrom source code](https://review.coreboot.org/plugins/gitiles/flashrom/+/refs/heads/master/flashchips.h) for flash chip manufacturer name and part number.
### Convert ELF to Binary: elf2image
The `elf2image` command converts an ELF file (from compiler/linker output) into the binary executable images which can be flashed and then booted into:
```
esptool.py --chip esp8266 elf2image my_app.elf
```
This command does not require a serial connection.
`elf2image` also accepts the [Flash Modes](#flash-modes) arguments `--flash_freq` and `--flash_mode`, which can be used to set the default values in the image header. This is important when generating any image which will be booted directly by the chip. These values can also be overwritten via the `write_flash` command, see the [write_flash command](#write-binary-data-to-flash-write_flash) for details.
By default, `elf2image` uses the sections in the ELF file to generate each segment in the binary executable. To use segments (PHDRs) instead, pass the `--use_segments` option.
#### elf2image for ESP8266
The default command output is two binary files: `my_app.elf-0x00000.bin` and `my_app.elf-0x40000.bin`. You can alter the firmware file name prefix using the `--output/-o` option.
`elf2image` can also produce a "version 2" image file suitable for use with a software bootloader stub such as [rboot](https://github.com/raburton/rboot) or the Espressif bootloader program. You can't flash a "version 2" image without also flashing a suitable bootloader.
```
esptool.py --chip esp8266 elf2image --version=2 -o my_app-ota.bin my_app.elf
```
#### elf2image for ESP32
For ESP32, elf2image produces a single output binary "image file". By default this has the same name as the .elf file, with a .bin extension. ie:
```
esptool.py --chip esp32 elf2image my_esp32_app.elf
```
In the above example, the output image file would be called `my_esp32_app.bin`.
### Output .bin image details: image_info
The `image_info` command outputs some information (load addresses, sizes, etc) about a `.bin` file created by `elf2image`.
```
esptool.py --chip esp32 image_info my_esp32_app.bin
```
Note that `--chip esp32` is required when reading ESP32 images. Otherwise the default is `--chip esp8266` and the image will be interpreted as an invalid ESP8266 image.
### Advanced Commands
The following commands are less commonly used, or only of interest to advanced users. They are documented on the wiki:
* [verify_flash](https://github.com/espressif/esptool/wiki/Advanced-Commands#verify_flash)
* [dump_mem](https://github.com/espressif/esptool/wiki/Advanced-Commands#dump_mem)
* [load_ram](https://github.com/espressif/esptool/wiki/Advanced-Commands#load_ram)
* [read_mem & write_mem](https://github.com/espressif/esptool/wiki/Advanced-Commands#read_mem--write_mem)
* [read_flash_status](https://github.com/espressif/esptool/wiki/Advanced-Commands#read_flash_status)
* [write_flash_status](https://github.com/espressif/esptool/wiki/Advanced-Commands#write_flash_status)
* [chip_id](https://github.com/espressif/esptool/wiki/Advanced-Commands#chip_id)
* [make_image](https://github.com/espressif/esptool/wiki/Advanced-Commands#make_image)
* [run](https://github.com/espressif/esptool/wiki/Advanced-Commands#run)
## Additional ESP32 Tools
The following tools for ESP32, bundled with esptool.py, are documented on the wiki:
* [espefuse.py - for reading/writing ESP32 efuse region](https://github.com/espressif/esptool/wiki/espefuse)
* [espsecure.py - for working with ESP32 security features](https://github.com/espressif/esptool/wiki/espsecure)
## Serial Connections
The ESP8266 & ESP32 ROM serial bootloader uses a 3.3V UART serial connection. Many development boards make the serial connections for you onboard.
However, if you are wiring the chip yourself to a USB/Serial adapter or similar then the following connections must be made:
ESP32/ESP8266 Pin | Serial Port Pin
--------------------- | ----------------------------
TX (aka GPIO1) | RX (receive)
RX (aka GPIO3) | TX (transmit)
Ground | Ground
Note that TX (transmit) on the ESP8266 is connected to RX (receive) on the serial port connection, and vice versa.
Do not connect the chip to 5V TTL serial adapters, and especially not to "standard" RS-232 adapters! 3.3V serial only!
## Entering the Bootloader
Both ESP8266 and ESP32 have to be reset in a certain way in order to launch the serial bootloader.
On some development boards (including NodeMCU, WeMOS, HUZZAH Feather, Core Board, ESP32-WROVER-KIT), esptool.py can automatically trigger a reset into the serial bootloader - in which case you don't need to read this section.
For everyone else, three things must happen to enter the serial bootloader - a reset, required pins set correctly, and GPIO0 pulled low:
### Boot Mode
Both ESP8266 and ESP32 choose the boot mode each time they reset. A reset event can happen in one of several ways:
* Power applied to chip.
* The nRESET pin was low and is pulled high (on ESP8266 only).
* The CH_PD/EN pin ("enable") pin was low and is pulled high.
On ESP8266, both the nRESET and CH_PD pins must be pulled high for the chip to start operating.
For more details on selecting the boot mode, see the following Wiki pages:
* [ESP8266 Boot Mode Selection](https://github.com/espressif/esptool/wiki/ESP8266-Boot-Mode-Selection)
* [ESP32 Boot Mode Selection](https://github.com/espressif/esptool/wiki/ESP32-Boot-Mode-Selection)
## Flash Modes
`write_flash` and some other commands accept command line arguments to set bootloader flash mode, flash size and flash clock frequency. The chip needs correct mode, frequency and size settings in order to run correctly - although there is some flexibility. A header at the beginning of a bootable image contains these values.
To override these values, the options `--flash_mode`, `--flash_size` and/or `--flash_freq` must appear after `write_flash` on the command line, for example:
```
esptool.py --port /dev/ttyUSB1 write_flash --flash_mode dio --flash_size 4MB 0x0 bootloader.bin
```
These options are only consulted when flashing a bootable image to an ESP8266 at offset 0x0, or an ESP32 at offset 0x1000. These are addresses used by the ROM bootloader to load from flash. When flashing at all other offsets, these arguments are not used.
### Flash Mode (--flash_mode, -fm)
These set Quad Flash I/O or Dual Flash I/O modes. Valid values are `keep`, `qio`, `qout`, `dio`, `dout`. The default is `keep`, which keeps whatever value is already in the image file. This parameter can also be specified using the environment variable `ESPTOOL_FM`.
Most boards use `qio` mode. Some ESP8266 modules, including the ESP-12E modules on some (not all) NodeMCU boards, are dual I/O and the firmware will only boot when flashed with `--flash_mode dio`. Most ESP32 modules are also dual I/O.
In `qio` mode, two additional GPIOs (9 and 10) are used for SPI flash communications. If flash mode is set to `dio` then these pins are available for other purposes.
For a full explanation of these modes, see the [SPI Flash Modes wiki page](https://github.com/espressif/esptool/wiki/SPI-Flash-Modes).
### Flash Frequency (--flash_freq, -ff)
Clock frequency for SPI flash interactions. Valid values are `keep`, `40m`, `26m`, `20m`, `80m` (MHz). The default is `keep`, which keeps whatever value is already in the image file. This parameter can also be specified using the environment variable `ESPTOOL_FF`.
The flash chip connected to most chips works with 40MHz clock speeds, but you can try lower values if the device won't boot. The highest 80MHz flash clock speed will give the best performance, but may cause crashing if the flash or board design is not capable of this speed.
### Flash Size (--flash_size, -fs)
Size of the SPI flash, given in megabytes. Valid values vary by chip type:
Chip | flash_size values
---------|---------------------------------------------------------------
ESP32 | `keep`, `detect`, `1MB`, `2MB`, `4MB`, `8MB`, `16MB`
ESP8266 | `keep`, `detect`, `256KB`, `512KB`, `1MB`, `2MB`, `4MB`, `2MB-c1`, `4MB-c1`, `8MB`, `16MB`
For ESP8266, some [additional sizes & layouts for OTA "firmware slots" are available](#esp8266-and-flash-size).
The default `--flash_size` parameter is `keep`. This means that if no `--flash_size` argument is passed when flashing a bootloader, the value in the bootloader .bin file header is kept instead of detecting the actual flash size and updating the header.
To enable automatic flash size detection based on SPI flash ID, add the argument `esptool.py [...] write_flash [...] -fs detect`. If detection fails, a warning is printed and a default value of of `4MB` (4 megabytes) is used.
If flash size is not successfully detected, you can find the flash size by using the `flash_id` command and then looking up the ID from the output (see [Read SPI flash id](#read-spi-flash-id-flash_id)). Alternatively, read off the silkscreen labelling of the flash chip and search for its datasheet.
The default `flash_size` parameter can also be overridden using the environment variable `ESPTOOL_FS`.
#### ESP8266 and Flash Size
The ESP8266 SDK stores WiFi configuration at the "end" of flash, and it finds the end using this size. However there is no downside to specifying a smaller flash size than you really have, as long as you don't need to write an image larger than this size.
ESP-12, ESP-12E and ESP-12F modules (and boards that use them such as NodeMCU, HUZZAH, etc.) usually have at least 4 megabyte / `4MB` (sometimes labelled 32 megabit) flash.
If using OTA, some additional sizes & layouts for OTA "firmware slots" are available. If not using OTA updates then you can ignore these extra sizes:
|flash_size arg | Number of OTA slots | OTA Slot Size | Non-OTA Space |
|---------------|---------------------|---------------|---------------|
|256KB | 1 (no OTA) | 256KB | N/A |
|512KB | 1 (no OTA) | 512KB | N/A |
|1MB | 2 | 512KB | 0KB |
|2MB | 2 | 512KB | 1024KB |
|4MB | 2 | 512KB | 3072KB |
|2MB-c1 | 2 | 1024KB | 0KB |
|4MB-c1 | 2 | 1024KB | 2048KB |
|8MB [^] | 2 | 1024KB | 6144KB |
|16MB [^] | 2 | 1024KB | 14336KB |
* [^] Support for 8MB & 16MB flash size is not present in all ESP8266 SDKs. If your SDK doesn't support these flash sizes, use `--flash_size 4MB`.
#### ESP32 and Flash Size
The ESP-IDF flashes a partition table to the flash at offset 0x8000. All of the partitions in this table must fit inside the configured flash size, otherwise the ESP32 will not work correctly.
## Merging binaries
The `merge_bin` command will merge multiple binary files (of any kind) into a single file that can be flashed to a device later. Any gaps between the input files are padded with 0xFF bytes (same as unwritten flash contents).
For example:
```
esptool.py --chip esp32 merge_bin -o merged-flash.bin --flash_mode dio --flash_size 4MB 0x1000 bootloader.bin 0x8000 partition-table.bin 0x10000 app.bin
```
Will create a file `merged-flash.bin` with the contents of the other 3 files. This file can be later be written to flash with `esptool.py write_flash 0x0 merged-flash.bin`.
Note: Because gaps between the input files are padded with 0xFF bytes, when the merged binary is written then any flash sectors between the individual files will be erased. To avoid this, write the files individually.
### Options
* The `merge_bin` command supports the same `--flash_mode`, `--flash_size` and `--flash_freq` options as the `write_flash` command to override the bootloader flash header (see above for details). These options are applied to the output file contents in the same way as when writing to flash. Make sure to pass the `--chip` parameter if using these options, as the supported values and the bootloader offset both depend on the chip.
* The `--target-offset 0xNNN` option will create a merged binary that should be flashed at the specified offset, instead of at offset 0x0.
* The `--fill-flash-size SIZE` option will pad the merged binary with 0xFF bytes to the full flash specified size, for example `--fill-flash-size 4MB` will create a 4MB binary file.
* It is possible to append options from a text file with `@filename`. As an example, this can be conveniently used with the ESP-IDF build system, which produces a `flash_args` file in the build directory of a project:
```sh
cd build # The build directory of an ESP-IDF project
esptool.py --chip esp32 merge_bin -o merged-flash.bin @flash_args
```
## Advanced Options
See the [Advanced Options wiki page](https://github.com/espressif/esptool/wiki/Advanced-Options) for some of the more unusual esptool.py command line options.
## Remote Serial Ports
It is possible to connect to any networked remote serial port that supports [RFC2217](http://www.ietf.org/rfc/rfc2217.txt) (Telnet) protocol, or a plain TCP socket. See the [Remote Serial Ports wiki page](https://github.com/espressif/esptool/wiki/Remote-Serial-Ports) for details.
## Troubleshooting
Flashing problems can be fiddly to troubleshoot. Try the suggestions here if you're having problems:
### Bootloader won't respond
If you see errors like "Failed to connect" then your chip is probably not entering the bootloader properly:
* Check you are passing the correct serial port on the command line.
* Check you have permissions to access the serial port, and other software (such as modem-manager on Linux) is not trying to interact with it. A common pitfall is leaving a serial terminal accessing this port open in another window and forgetting about it.
* Check the chip is receiving 3.3V from a stable power source (see [Insufficient Power](#insufficient-power) for more details.)
* Check that all pins are connected as described in [Entering the bootloader](#entering-the-bootloader). Check the voltages at each pin with a multimeter, "high" pins should be close to 3.3V and "low" pins should be close to 0V.
* If you have connected other devices to GPIO pins mentioned above section, try removing them and see if esptool.py starts working.
* Try using a slower baud rate (`-b 9600` is a very slow value that you can use to verify it's not a baud rate problem.)
### write_flash operation fails part way through
If flashing fails with random errors part way through, retry with a lower baud rate.
Power stability problems may also cause this (see [Insufficient Power](#insufficient-power).)
### write_flash succeeds but program doesn't run
If esptool.py can flash your module with `write_flash` but your program doesn't run, try the following:
#### Wrong Flash Mode
Some devices only support the `dio` flash mode. Writing to flash with `qio` mode will succeed but the chip can't read the flash back to run - so nothing happens on boot. Try passing the `-fm dio` option to write_flash.
See the [SPI Flash Modes](https://github.com/espressif/esptool/wiki/SPI-Flash-Modes) wiki page for a full description of the flash modes and how to determine which ones are supported on your device.
#### Insufficient Power
The 3.3V power supply for the ESP8266 and ESP32 has to supply large amounts of current (up to 70mA continuous, 200-300mA peak, slightly higher for ESP32). You also need sufficient capacitance on the power circuit to meet large spikes of power demand.
##### Insufficient Capacitance
If you're using a pre-made development board or module then the built-in power regulator & capacitors are usually good enough, provided the input power supply is adequate.
*This is not true for some very simple pin breakout modules - [similar to this](https://user-images.githubusercontent.com/205573/30140831-9da417a6-93ba-11e7-95c3-f422744967de.jpg). These breakouts do not integrate enough capacitance to work reliably without additional components.*. Surface mount OEM modules like ESP-WROOM02 and ESP-WROOM32 require an external bulk capacitor on the PCB to be reliable, consult the module datasheet.
##### Power Supply Rating
It is possible to have a power supply that supplies enough current for the serial bootloader stage with esptool.py, but not enough for normal firmware operation. You may see the 3.3V VCC voltage droop down if you measure it with a multimeter, but you can have problems even if this isn't happening.
Try swapping in a 3.3V supply with a higher current rating, add capacitors to the power line, and/or shorten any 3.3V power wires.
The 3.3V output from FTDI FT232R chips/adapters or Arduino boards *do not* supply sufficient current to power an ESP8266 or ESP32 (it may seem to work sometimes, but it won't work reliably). Other USB TTL/serial adapters may also be marginal.
#### Missing bootloader
Recent ESP8266 SDKs and the ESP32 ESP-IDF both use a small firmware bootloader program. The hardware bootloader in ROM loads this firmware bootloader from flash, and then it runs the program. On ESP8266. firmware bootloader image (with a filename like `boot_v1.x.bin`) has to be flashed at offset 0. If the firmware bootloader is missing then the ESP8266 will not boot. On ESP32, the bootloader image should be flashed by ESP-IDF at offset 0x1000.
Refer to SDK or ESP-IDF documentation for details regarding which binaries need to be flashed at which offsets.
#### SPI Pins which must be disconnected
Compared to the ROM bootloader that esptool.py talks to, a running firmware uses more of the chip's pins to access the SPI flash.
If you set "Quad I/O" mode (`-fm qio`, the esptool.py default) then GPIOs 7, 8, 9 & 10 are used for reading the SPI flash and must be otherwise disconnected.
If you set "Dual I/O" mode (`-fm dio`) then GPIOs 7 & 8 are used for reading the SPI flash and must be otherwise disconnected.
Try disconnecting anything from those pins (and/or swap to Dual I/O mode if you were previously using Quad I/O mode but want to attach things to GPIOs 9 & 10). Note that if GPIOs 9 & 10 are also connected to input pins on the SPI flash chip, they may still be unsuitable for use as general purpose I/O.
In addition to these pins, GPIOs 6 & 11 are also used to access the SPI flash (in all modes). However flashing will usually fail completely if these pins are connected incorrectly.
### Early stage crash
Use a [serial terminal program](#serial-terminal-programs) to view the boot log. (ESP8266 baud rate is 74880bps, ESP32 is 115200bps). See if the program is crashing during early startup or outputting an error message.
## Serial Terminal Programs
There are many serial terminal programs suitable for debugging & serial interaction. The pyserial module (which is required for esptool.py) includes one such command line terminal program - miniterm.py. For more details [see this page](http://pyserial.readthedocs.org/en/latest/tools.html#module-serial.tools.miniterm) or run `miniterm -h`.
Note that not every serial program supports the unusual ESP8266 74880bps "boot log" baud rate. Support is especially sparse on Linux. `miniterm.py` supports this baud rate on all platforms. ESP32 uses the more common 115200bps.
## Tracing esptool.py interactions
Running `esptool.py --trace` will dump all serial interactions to the standard output (this is *a lot* of output). This can be helpful when debugging issues with the serial connection, or when providing information for bug reports.
## Using esptool from Python
esptool.py, espefuse.py, and espsecure.py can easily be integrated into Python applications or called from other Python scripts.
While it currently does have a poor Python API, something which [#208](https://github.com/espressif/esptool/issues/208) will address, it allows for passing CLI
arguments to `esptool.main()`. This workaround makes integration very straightforward as you can pass exactly the
same arguments as you would on the CLI.
```python
command = ['--baud', '460800', 'read_flash', '0', '0x200000', 'flash_contents.bin']
print('Using command %s' % ' '.join(command))
esptool.main(command)
```
## Internal Technical Documentation
The [repository wiki](https://github.com/espressif/esptool/wiki) contains some technical documentation regarding the serial protocol and file format used by the ROM bootloader. This may be useful if you're developing esptool.py or hacking system internals:
* [Firmware Image Format](https://github.com/espressif/esptool/wiki/Firmware-Image-Format)
* [Serial Protocol](https://github.com/espressif/esptool/wiki/Serial-Protocol)
* [ESP8266 Boot ROM Log](https://github.com/espressif/esptool/wiki/ESP8266-Boot-ROM-Log)
## Contribute
If you're interested in contributing to esptool.py, please check the [Contributions Guide](https://docs.espressif.com/projects/esptool/en/latest/contributing.html).
## About
esptool.py was initially created by Fredrik Ahlberg (@themadinventor, @kongo), and later maintained by Angus Gratton (@projectgus). It has also received improvements from many members of the community.
esptool.py was initially created by Fredrik Ahlberg (@[themadinventor](https://github.com/themadinventor/)), and later maintained by Angus Gratton (@[projectgus](https://github.com/projectgus/)). It is now supported by Espressif Systems. It has also received improvements from many members of the community.
This document and the attached source code are released under GNU General Public License Version 2. See the accompanying file LICENSE for a copy.
## License
This document and the attached source code are released as Free Software under GNU General Public License Version 2 or later. See the accompanying [LICENSE file](https://github.com/espressif/esptool/blob/master/LICENSE) for a copy.

View File

@@ -10,7 +10,7 @@ Use actual documentation generated within about 20 minutes on each commit:
* English: https://docs.espressif.com/projects/esptool/
The above URL is for the master branch latest version. Click the drop-down in the bottom left to choose a particular version or to download a PDF.
The above URL is for the master branch latest version. Click the drop-down in the bottom left to choose a particular version.
# Building Documentation

View File

@@ -2,9 +2,7 @@ var DOCUMENTATION_VERSIONS = {
DEFAULTS: { has_targets: false,
supported_targets: [ "esp32" ]
},
VERSIONS: [
{ name: "latest", has_targets: true, supported_targets: [ "esp8266", "esp32", "esp32s2", "esp32c3", "esp32s3" ] },
],
VERSIONS: [ ],
IDF_TARGETS: [
{ text: "ESP8266", value: "esp8266" },
{ text: "ESP32", value: "esp32" },

View File

@@ -15,4 +15,4 @@ html_static_path = ['../_static']
# Extra options required by sphinx_idf_theme
project_slug = 'esptool'
versions_url = '_static/esptool_versions.js'
versions_url = './_static/esptool_versions.js'

View File

@@ -1,6 +1,6 @@
About
=====
Esptool was started by Fredrik Ahlberg (@themadinventor) as an unofficial community project. Later, it was maintained by Angus Gratton (@projectgus). It is now supported by Espressif Systems.
Esptool was started by Fredrik Ahlberg (`themadinventor <https://github.com/themadinventor>`_) as an unofficial community project. Later, it was maintained by Angus Gratton (`projectgus <https://github.com/projectgus>`_). It is now supported by `Espressif Systems <https://espressif.com/>`_.
Esptool is Free Software under a GPLv2 license.
Esptool source code and this documentation are released as Free Software under GNU General Public License Version 2. See `the LICENSE <https://github.com/espressif/esptool/blob/master/LICENSE>`_ for a copy.

View File

@@ -0,0 +1,178 @@
.. _boot-mode-esp32:
ESP32 Boot Mode Selection
=========================
.. warning::
The ESP32 has a 45k ohm internal pull-up/pull-down resistor at GPIO00 (and other pins). If you want to connect a switch button to enter the boot mode, this has to be a strong pull-down. For example a 10k resistor to GND.
Guide to selecting boot mode correctly on ESP32.
Information about ESP32 strapping pins can also be found in the `ESP32 Datasheet <https://www.espressif.com/en/support/documents/technical-documents?keys=ESP32+datasheet>`__, section 2.4 "Strapping Pins".
On many development boards with built-in USB/Serial, this is all done for you and ``esptool.py`` can automatically reset the board into bootloader mode. For other configurations or custom hardware, you will need to check the orientation of some "strapping pins" to get the correct boot mode:
Select Bootloader Mode
----------------------
GPIO0
^^^^^
The ESP32 will enter the serial bootloader when GPIO0 is held low on reset. Otherwise it will run the program in flash.
+---------------+----------------------------------------+
| GPIO0 Input | Mode |
+===============+========================================+
| Low/GND | ROM serial bootloader for esptool |
+---------------+----------------------------------------+
| High/VCC | Normal execution mode |
+---------------+----------------------------------------+
GPIO0 has an internal pullup resistor, so if it is left unconnected then it will pull high.
Many boards use a button marked "Flash" (or "BOOT" on some Espressif development boards) that pulls GPIO0 low when pressed.
GPIO2
^^^^^
GPIO2 must also be either left unconnected/floating, or driven Low, in order to enter the serial bootloader.
In normal boot mode (GPIO0 high), GPIO2 is ignored.
Other Pins
^^^^^^^^^^
As well as GPIO0 and GPIO2, the following pins influence the serial bootloader mode:
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GPIO | Meaning |
+=============+============================================================================================================================================================================================================================================================================================+
| 12 (MTDI) | If driven High, flash voltage (VDD_SDIO) is 1.8V not default 3.3V. Has internal pull-down, so unconnected = Low = 3.3V. May prevent flashing and/or booting if 3.3V flash is used and this pin is pulled high, causing the flash to brownout. See the ESP32 datasheet for more details. |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 15 (MTDO) | If driven Low, silences boot messages printed by the ROM bootloader. Has an internal pull-up, so unconnected = High = normal output. |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Automatic Bootloader
--------------------
``esptool`` can automatically enter the bootloader on many boards by using the RTS and DTR modem status lines to toggle GPIO0 and EN automatically.
Make the following connections for ``esptool`` to automatically enter the bootloader:
+-------------+--------------+
| ESP32 Pin | Serial Pin |
+=============+==============+
| EN | RTS |
+-------------+--------------+
| GPIO0 | DTR |
+-------------+--------------+
Note that some serial terminal programs (not esptool) will assert both RTS and DTR when opening the serial port, pulling them low together and holding the ESP32 in reset. If RTS is wired directly to EN then RTS/CTS "hardware flow control" needs to be disabled in the serial program to avoid this.
Development boards (including all Espressif boards) usually use additional circuitry to avoid this problem - if both RTS and DTR are both asserted together, this doesn't reset the chip. Consult Espressif development board schematics for the specific details.
(Some third party ESP32 development boards use an automatic reset circuit for EN & GPIO pins, but don't add a capacitor on the EN pin. This results in unreliable automatic reset, especially on Windows. Adding a 1uF (or higher) value capacitor between EN pin and GND may make automatic reset more reliable..)
ESP32 Boot Log
==============
Boot Mode Message
-----------------
After reset, the second line printed by the ESP32 ROM (at 115200bps) is a reset & boot mode message:
::
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x3 (DOWNLOAD_BOOT(UART0/UART1/SDIO_REI_REO_V2))
``rst:0xNN (REASON)`` is an enumerated value (and description) of the reason for the reset. `A mapping between the hex value and each reason can be found in the ESP-IDF source <https://github.com/espressif/esp-idf/blob/release/v3.0/components/esp32/include/rom/rtc.h#L80>`__.
The value can be read in ESP32 code via the `get_reset_reason() ROM function <https://github.com/espressif/esp-idf/blob/release/v3.0/components/esp32/include/rom/rtc.h#L147>`__.
``boot:0xNN (DESCRIPTION)`` is the hex value of the strapping pins, as represented in the `GPIO_STRAP register <https://github.com/espressif/esp-idf/blob/3cad00fdcca7dd4b7939d7862407c000c29657c1/components/soc/esp32/include/soc/gpio_reg.h#L130>`__.
The individual bit values are as follows:
- ``0x01`` - GPIO5
- ``0x02`` - MTDO (GPIO15)
- ``0x04`` - GPIO4
- ``0x08`` - GPIO2
- ``0x10`` - GPIO0
- ``0x20`` - MTDI (GPIO12)
If the pin was high on reset, the bit value will be set. If it was low on reset, the bit will be cleared.
A number of boot mode strings can be shown depending on which bits are set:
- ``DOWNLOAD_BOOT(UART0/UART1/SDIO_REI_REO_V2)`` - ESP32 is in download flashing mode (suitable for esptool)
- ``SPI_FAST_FLASH_BOOT`` - This is the normal SPI flash boot mode.
- Other modes (including ``HSPI_FLASH_BOOT``, ``SPI_FLASH_BOOT``, ``SDIO_REI_FEO_V1_BOOT``, ``ATE_BOOT``) may be shown here. This indicates an unsupported boot mode has been selected.
Consult the strapping pins shown above (in most cases, one of these modes is selected if GPIO2 has been pulled high when GPIO0 is low).
.. note::
``GPIO_STRAP`` register includes GPIO 4 but this pin is not used by any supported boot mode and be set either high or low for all supported boot modes.
Later Boot Messages
-------------------
Later output from the ROM bootloader depends on the strapping pins and
the boot mode. Some common output includes:
Early Flash Read Error
^^^^^^^^^^^^^^^^^^^^^^
::
flash read err, 1000
This fatal error indicates that the bootloader tried to read the software bootloader header at address 0x1000 but failed to read valid data. Possible reasons for this include:
- There isn't actually a bootloader at offset 0x1000 (maybe the bootloader was flashed to the wrong offset by mistake, or the flash has been erased and no bootloader has been flashed yet.)
- Physical problem with the connection to the flash chip, or flash chip power.
- Boot mode accidentally set to ``HSPI_FLASH_BOOT``, which uses different SPI flash pins. Check GPIO2 (see above).
- VDDSDIO has been enabled at 1.8V (due to MTDI/GPIO12, see above), but this flash chip requires 3.3V so it's browning out.
- Flash encryption is enabled but the bootloader is plaintext. Alternatively, flash encryption is disabled but the bootloader is encrypted ciphertext.
Software Bootloader Header Info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
configsip: 0, SPIWP:0x00
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
This is normal boot output based on a combination of efuse values and information read from the bootloader header at flash offset 0x1000:
- ``configsip: N`` indicates SPI flash config:
- 0 for default SPI flash
- 1 if booting from the HSPI bus (due to EFUSE configuration)
- Any other value indicates that SPI flash pins have been remapped via efuse (the value is the value read from efuse, consult :ref:`espefuse docs <espefuse>` to get an easier to read representation of these pin mappings).
- ``SPIWP:0xNN`` indicates a custom ``WP`` pin value, which is stored in the bootloader header. This pin value is only used if SPI flash pins have been remapped via efuse (as shown in the ``configsip`` value).
All custom pin values but WP are encoded in the configsip byte loaded from efuse, and WP is supplied in the bootloader header.
- ``clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00`` Custom GPIO drive strength values for SPI flash pins. These are read from the bootloader header in flash. Not currently supported.
- ``mode: AAA, clock div: N``. SPI flash access mode. Read from the bootloader header, correspond to the ``--flash_mode`` and ``--flash_freq`` arguments supplied to ``esptool.py write_flash`` or ``esptool.py elf2image``.
- ``mode`` can be DIO, DOUT, QIO, or QOUT. *QIO and QOUT are not supported here*, to boot in a Quad I/O mode the ROM bootloader should load the software bootloader in a Dual I/O mode and then the ESP-IDF software bootloader enables Quad I/O based on the detected flash chip mode.
- ``clock div: N`` is the SPI flash clock frequency divider. This is an integer clock divider value from an 80MHz APB clock, based on the supplied ``--flash_freq`` argument (ie 80MHz=1, 40MHz=2, etc).
The ROM bootloader actually loads the software bootloader at a lower frequency than the flash_freq value: The initial APB clock frequency is equal to the crystal frequency, so with a 40MHz crystal the SPI clock used to load the software bootloader will be half the configured value (40MHz/2=20MHz).
When the software bootloader starts it sets the APB clock to 80MHz causing the SPI clock frequency to match the value set when flashing.
Software Bootloader Load Segments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
load:0x3fff0008,len:8
load:0x3fff0010,len:3680
load:0x40078000,len:8364
load:0x40080000,len:252
entry 0x40080034
These entries are printed as the ROM bootloader loads each segment in the software bootloader image. The load address and length of each segment is printed.
You can compare these values to the software bootloader image by running ``esptool.py --chip esp32 image_info /path/to/bootloader.bin`` to dump image info including a summary of each segment. Corresponding details will also be found in the bootloader ELF file headers.
If there is a problem with the SPI flash chip addressing mode, the values printed by the bootloader here may be corrupted.
The final line shows the entry point address of the software bootloader, where the ROM bootloader will call as it hands over control.

View File

@@ -0,0 +1,117 @@
.. _boot-mode-esp8266:
ESP8266 Boot Mode Selection
===========================
Guide to selecting boot mode correctly on ESP8266.
On many development boards with built-in USB/Serial, this is done for you and ``esptool`` can automatically reset the board into bootloader mode. For other configurations, you will need to follow these steps:
Required Pins
-------------
The following ESP8266 pins must be in a known state for either normal (flash boot) or serial bootloader operation. Most development boards or modules make necessary connections already, internally:
+--------+--------------------------------------------------------------------------------------------------------------------+
| GPIO | State |
+========+====================================================================================================================+
| 15 | Pulled Low/GND (directly connected to GND, or external pull-down resistor) |
+--------+--------------------------------------------------------------------------------------------------------------------+
| 2 | Pull-up resistor High/VCC, or No Connection (pin has internal weak pullup, external pullup resistor is optional) |
+--------+--------------------------------------------------------------------------------------------------------------------+
If these pins are set differently to shown, nothing on the ESP8266 will work as expected. See `ESP8266 Pin List document <https://www.espressif.com/en/support/documents/technical-documents?keys=ESP8266+Pin+List>`__ to see what boot modes are enabled for different pin combinations.
When the ESP8266 goes into serial bootloader mode, the Boot ROM switches GPIO2 to an output and the UART TX signal is also output to this pin. For this reason GPIO2 should not be directly connected to VCC. Similarly, make sure GPIO2 is not connected to another peripheral where this may cause an issue when in download mode.
Select Bootloader Mode
----------------------
The ESP8266 will enter the serial bootloader when GPIO0 is held low on reset. Otherwise it will run the program in flash.
+---------------+----------------------------------------+
| GPIO0 Input | Mode |
+===============+========================================+
| Low/GND | ROM serial bootloader for esptool |
+---------------+----------------------------------------+
| High/VCC | Normal execution mode |
+---------------+----------------------------------------+
Many configurations use a "Flash" button that pulls GPIO0 low when pressed.
Automatic Bootloader
--------------------
``esptool`` can automatically enter the bootloader on many boards by using the RTS and DTR modem status lines to toggle GPIO0 and EN automatically.
Make the following connections for ``esptool`` to automatically enter the bootloader:
+---------------------------------+--------------+
| ESP8266 Pin | Serial Pin |
+=================================+==============+
| CH_PD ("enable") *or* nRESET | RTS |
+---------------------------------+--------------+
| GPIO0 | DTR |
+---------------------------------+--------------+
Note that some serial terminal programs (not esptool) will assert both RTS and DTR when opening the serial port, pulling them low together and holding the ESP8266 in reset. If you've wired RTS to the ESP8266 then you should disable RTS/CTS "hardware flow control" in the program.
Development boards like NodeMCU use additional circuitry to avoid this problem - if both RTS and DTR are asserted together, this doesn't reset the chip.
In Linux serial ports by default will assert RTS when nothing is attached to them. This can hold the ESP8266 in a reset loop which may cause some serial adapters to subsequently reset loop. This functionality can be disabled by disabling ``HUPCL`` (ie ``sudo stty -F /dev/ttyUSB0 -hupcl``).
.. _boot-log-esp8266:
ESP8266 Boot Log
================
The ESP8266 boot rom writes a log to the UART when booting. The timing is a little bit unusual: ``74880 baud``
::
ets Jan 8 2014,rst cause 1, boot mode:(3,7)
load 0x40100000, len 24236, room 16
tail 12
chksum 0xb7
ho 0 tail 12 room 4
load 0x3ffe8000, len 3008, room 12
tail 4
chksum 0x2c
load 0x3ffe8bc0, len 4816, room 4
tail 12
chksum 0x46
csum 0x46
Boot ROM Log Explanation:
-------------------------
**rst_cause:**
+---------------+----------------------------------------+
| Value | Meaning |
+===============+========================================+
| 1 | power-on |
+---------------+----------------------------------------+
| 2 | external-reset |
+---------------+----------------------------------------+
| 4 | hardware watchdog-reset |
+---------------+----------------------------------------+
**The first parameter of boot_mode:**
+-------------------------+----------------------------------------------+
| Value | Meaning |
+=========================+==============================================+
| 1 (eg. boot mode:(1,x)) | UART download mmode (download FW into Flash) |
+-------------------------+----------------------------------------------+
| 2 (eg. boot mode:(3,x)) | Boot from flash mode |
+-------------------------+----------------------------------------------+
**chksum:**
If value of “chksum” == value of “csum”, it means flash has been read correctly during booting.
The rest of boot messages are used internally by Espressif.

View File

@@ -0,0 +1,10 @@
Boot Mode Selection
===================
This guide explains how to select the boot mode correctly and describes the boot log messages of Espressif chips. Please select your target:
.. toctree::
:maxdepth: 1
ESP32 Boot Mode Selection <boot-mode-esp32>
ESP8266 Boot Mode Selection <boot-mode-esp8266>

View File

@@ -0,0 +1,50 @@
Firmware Image Format
=====================
.. note::
Currently this document refers to ESP8266 only. ESP32 has some additional headers.
This is technical documentation for the firmware image format used by the ROM bootloader. These are the images created by ``esptool.py elf2image``.
The firmware file consists of a header, a variable number of data segments and a footer. Multi-byte fields are little-endian.
File Header
-----------
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Byte | Description |
+========+================================================================================================================================================================+
| 0 | Always ``0xE9`` |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 1 | Number of segments |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 2 | SPI Flash Interface (``0`` = QIO, ``1`` = QOUT, ``2`` = DIO, ``0x3`` = DOUT) |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 3 | High four bits: ``0`` = 512K, ``1`` = 256K, ``2`` = 1M, ``3`` = 2M, ``4`` = 4M, Low four bits: ``0`` = 40MHz, ``1``\ = 26MHz, ``2`` = 20MHz, ``0xf`` = 80MHz |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 4-7 | Entry point |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 8-n | Segments |
+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+
esptool overrides the 2nd and 3rd (start from 0) bytes according to the SPI flash info provided through command line option, regardless of corresponding bytes from the input .bin file that will be written to address 0x00000.
So you must provide SPI flash info when running ``esptool write_flash`` command. For example ``esptool write_flash -ff 80m -fm qio -fs 8m 0x00000 boot.bin 0x01000 user1.bin``
Segment
-------
+---------+-----------------+
| Byte | Description |
+=========+=================+
| 0-3 | Memory offset |
+---------+-----------------+
| 4-7 | Segment size |
+---------+-----------------+
| 8...n | Data |
+---------+-----------------+
Footer
------
The file is padded with zeros until its size is one byte less than a multiple of 16 bytes. A last byte (thus making the file size a multiple of 16) is the checksum of the data of all segments. The checksum is defined as the xor-sum of all bytes and the byte ``0xEF``.

View File

@@ -0,0 +1,12 @@
Advanced Topics
===============
This sections contains advanced topics and technical documentation useful if you're developing ``esptool`` or hacking system internals:
.. toctree::
:maxdepth: 1
Firmware Image Format <firmware-image-format>
Serial Protocol <serial-protocol>
SPI Flash Modes <spi-flash-modes>
Boot Mode Selection <boot-mode-selection>

View File

@@ -0,0 +1,369 @@
Serial Protocol
===============
This is technical documentation for the serial protocol used by the UART bootloader in the ESP chip ROM and the esptool software "stub loader" program.
The UART bootloader runs on chip reset if certain strapping pins are set. See :ref:`entering-the-bootloader` for details of this process.
The ESP8266 & ESP32 ROM loader serial protocols are similar, although ESP32 adds some additional commands and some slightly different behaviour.
By default, esptool uploads a stub "software loader" to the IRAM of the chip. The software loader then replaces the ROM loader for all future interactions. This standardizes much of the behaviour. Pass ``--no-stub`` to esptool in order to disable the software stub loader.
Packet Description
------------------
The host computer sends a SLIP encoded command request to the ESP chip. The ESP chip responds to the request with a SLIP encoded response packet, including status information and any data as a payload.
Low Level Protocol
^^^^^^^^^^^^^^^^^^
The bootloader protocol uses `SLIP <http://en.wikipedia.org/wiki/SLIP>`_ packet framing for data transmissions in both directions.
Each SLIP packet begins and ends with ``0xC0``. Within the packet, all occurrences of ``0xC0`` and ``0xDB`` are replaced with ``0xDB 0xDC`` and ``0xDB 0xDD``, respectively. The replacing is to be done **after** the checksum and lengths are calculated, so the packet length may be longerthan the ``size`` field below.
Command
^^^^^^^
Each command is a SLIP packet initiated by the host and results in a response packet. Inside the packet, the packet consists of a header and a variable-length body. All multi-byte fields are little-endian.
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
| Byte | Name | Comment |
+========+=============+====================================================================================================================+
| 0 | Direction | Always ``0x00`` for requests |
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
| 1 | Command | Command identifier (see `Command Opcodes`_). |
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
| 2-3 | Size | Length of Data field, in bytes. |
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
| 4-7 | Checksum | Simple checksum of part of the data field (only used for some commands, see `Checksum`_). |
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
| 8..n | Data | Variable length data payload (0-65535 bytes, as indicated by Size parameter). Usage depends on specific command. |
+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
Response
^^^^^^^^
Each received command will result in a response SLIP packet sent from the ESP chip to the host. Contents of the response packet is:
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
| Byte | Name | Comment |
+========+=============+==============================================================================================================+
| 0 | Direction | Always ``0x01`` for responses |
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
| 1 | Command | Same value as Command identifier in the request packet that trigged the response |
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
| 2-3 | Size | Size of data field. At least the length of the `Status Bytes`_ (2 or 4 bytes, see below). |
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
| 4-7 | Value | Response value used by READ_REG command (see below). Zero otherwise. |
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
| 8..n | Data | Variable length data payload. Length indicated by "Size" field. |
+--------+-------------+--------------------------------------------------------------------------------------------------------------+
Status bytes
""""""""""""
The final bytes of the Data payload indicate command status:
For software loaders and ESP8266 ROM loader the final two bytes indicate status (most commands return at least a two byte Data payload):
+----------+----------+-----------------------------------------------------+
| Byte | Name | Comment |
+==========+==========+=====================================================+
| Size-2 | Status | Status flag, success (``0``) or failure (``1``) |
+----------+----------+-----------------------------------------------------+
| Size-1 | Error | If Status is 1, this indicates the type of error. |
+----------+----------+-----------------------------------------------------+
For ESP32 ROM (only, not the software loader) the final four bytes are used, but only the first two bytes contain status information:
+----------+------------+---------------------------------------------------+
| Byte | Name | Comment |
+==========+============+===================================================+
| Size-4 | Status | Status flag, success (``0``) or failure (``1``) |
+----------+------------+---------------------------------------------------+
| Size-3 | Error | If Status 1, this indicates the type of error. |
+----------+------------+---------------------------------------------------+
| Size-2 | Reserved | |
+----------+------------+---------------------------------------------------+
| Size-1 | Reserved | |
+----------+------------+---------------------------------------------------+
ROM Loader Error Codes
""""""""""""""""""""""
The ROM loader sends the following error values
- 0x05 - "Received message is invalid" (parameters or length field is invalid)
- 0x06 - "Failed to act on received message"
- 0x07 - "Invalid CRC in message"
- 0x08 - "flash write error" - after writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned.
- 0x09 - "flash read error" - SPI read failed
- 0x0a - "flash read length error" - SPI read request length is too long
- 0x0b - "Deflate error" (compressed uploads only)
Software Loader Status & Error
""""""""""""""""""""""""""""""
If the software loader is used:
- The status response is always 2 bytes regardless of chip type.
- Stub loader error codes are entirely different to the ROM loader codes. They all take the form ``0xC*``, or ``0xFF`` for "unimplemented command". (`Full list here <https://github.com/espressif/esptool/blob/master/flasher_stub/include/stub_flasher.h#L95>`_).
After sending a command, the host should continue to read response packets until one is received where the Command field matches the request's Command field, or a timeout is exceeded.
Command Opcodes
^^^^^^^^^^^^^^^
Supported by software loader and ROM loaders
""""""""""""""""""""""""""""""""""""""""""""
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| Byte | Name | Description | Input Data | Output Data |
+============+================+=======================================================+====================================================================================================================================+================================================+
| ``0x02`` | FLASH_BEGIN | `Begin Flash Download <#writing-data>`__ | Four 32-bit words: size to erase, number of data packets, data size in one packet, flash offset. | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x03`` | FLASH_DATA | `Flash Download Data <#writing-data>`__ | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_. | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x04`` | FLASH_END | `Finish Flash Download <#writing-data>`__ | One 32-bit word: ``0`` to reboot, ``1`` "run to user code". Not necessary to send this command if you wish to stay in the loader | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x05`` | MEM_BEGIN | `Begin RAM Download Start <#writing-data>`__ | total size, number of data packets, data size in one packet, memory offset | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x06`` | MEM_END | `Finish RAM Download <#writing-data>`__ | Two 32-bit words: execute flag, entry point address | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x07`` | MEM_DATA | `RAM Download Data <#writing-data>`__ | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_. | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x08`` | SYNC | `Sync Frame <#initial-synchronisation>`__ | 36 bytes: ``0x07 0x07 0x12 0x20``, followed by 32 x ``0x55`` | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x09`` | WRITE_REG | `Write 32-bit memory address <#32-bit-readwrite>`__ | Four 32-bit words: address, value, mask and delay (in microseconds) | |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
| ``0x0a`` | READ_REG | `Read 32-bit memory address <#32-bit-readwrite>`__ | Address as 32-bit word | Read data as 32-bit word in ``value`` field. |
+------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
Supported by software loader and ESP32 ROM Loader
"""""""""""""""""""""""""""""""""""""""""""""""""
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| Byte | Name | Description | Input Data | Output Data |
+============+======================+================================================================+================================================================================================================================================================================================================================================+===================================================================================================================================+
| ``0x0b`` | SPI_SET_PARAMS | `Configure SPI flash <#spi-set-parameters>`__ | Six 32-bit words: id, total size in bytes, block size, sector size, page size, status mask. | |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x0d`` | SPI_ATTACH | `Attach SPI flash <#spi-attach-command>`__ | 32-bit word: Zero for normal SPI flash. A second 32-bit word (should be ``0``) is passed to ESP32 ROM loader only. | |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x0f`` | CHANGE_BAUDRATE | `Change Baud rate <#initial-synchronisation>`__ | Two 32-bit words: new baud rate, ``0`` if we are talking to the ROM flasher or the current/old baud rate if we are talking to the software stub flasher. | |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x10`` | FLASH_DEFL_BEGIN | `Begin compressed flash download <#writing-data>`__ | Four 32-bit words: uncompressed size, number of data packets, data packet size, flash offset.With stub loader the uncompressed size is exact byte count to be written, whereas on ROM bootloader it is rounded up to flash erase block size. | |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x11`` | FLASH_DEFL_DATA | `Compressed flash download data <#writing-data>`__ | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_. | Error code ``0xC1`` on checksum error. |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x12`` | FLASH_DEFL_END | `End compressed flash download <#writing-data>`__ | One 32-bit word: ``0`` to reboot, ``1`` to "run user code". Not necessary to send this command if you wish to stay in the loader. | |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
| ``0x13`` | SPI_FLASH_MD5 | `Calculate MD5 of flash region <#verifying-uploaded-data>`__ | Four 32-bit words: address, size, ``0``, ``0`` | Body contains 16 raw bytes of MD5 followed by 2 status bytes (stub loader) or 32 hex-coded ASCII (ROM loader) of calculated MD5 |
+------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
Supported by software loader only (ESP8266 & ESP32)
"""""""""""""""""""""""""""""""""""""""""""""""""""
ROM loaders will not recognise these commands.
+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
| Byte | Name | Descripton | Input | Output |
+============+===================+===================================+=========================================================================================================================+==========+
| ``0xd0`` | ERASE_FLASH | Erase entire flash chip | | |
+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
| ``0xd1`` | ERASE_REGION | Erase flash region | Two 32-bit words: flash offset to erase, erase size in bytes. Both must be multiples of flash sector size. | |
+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
| ``0xd2`` | READ_FLASH | `Read flash <#reading-flash>`__ | Four 32-bit words: flash offset, read length, flash sector size, read packet size, maximum number of un-acked packets | |
+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
| ``0xd3`` | RUN_USER_CODE | Exits loader and runs user code | | |
+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
Checksum
^^^^^^^^
The checksum field is ignored (can be zero) for all comands except for MEM_DATA, FLASH_DATA, and FLASH_DEFL_DATA.
Each of the ``_DATA`` command packets has the same "data payload" format:
+---------+--------------------------+----------------------------------------------------------------+
| Bytes | Name | Format |
+=========+==========================+================================================================+
| 0-3 | "Data to write" length | Little endian 32-bit word. |
+---------+--------------------------+----------------------------------------------------------------+
| 4-7 | Sequence number | Little endian 32-bit word. The sequence numbers are 0 based. |
+---------+--------------------------+----------------------------------------------------------------+
| 8-15 | 0 | Two words of all zeroes, unused. |
+---------+--------------------------+----------------------------------------------------------------+
| 16- | "Data to write" | Length given at beginning of payload. |
+---------+--------------------------+----------------------------------------------------------------+
The checksum is only applied to this final "data to write" section, not the first 16 bytes of data.
To calculate checksum, start with seed value 0xEF and XOR each individual byte in the "data to write". The 8-bit result is stored in the checksum field of the packet header (as a little endian 32-bit value).
.. note::
Because this checksum is not adequate to ensure valid data, the SPI_FLASH_MD5 command was added to validate flash contents after flashing. It is recommended that this command is always used. See `Verifying Uploaded Data`_, below.
Functional Description
----------------------
Initial Synchronisation
^^^^^^^^^^^^^^^^^^^^^^^
* The ESP chip is reset into UART bootloader mode. The host starts by sending SYNC commands. These commands have a large data payload which is also used by the ESP chip to detect the configured baud rate.
The ESP8266 will initialise at 74800bps with a 26MHz crystal and 115200bps with a 40MHz crystal, and ESP32 always initialises at 115200bps. However the sync packets can be sent at any baud rate, and the UART peripheral will detect this.
* The host should wait until it sees a valid response to a SYNC command, indicating the ESP chip is correctly communicating.
* esptool then (by default) uses the "RAM Download" sequence to upload software stub loader code to IRAM of the chip. The MEM_END command contains the entry-point address to run the software loader.
The software loader then sends a custom SLIP packet of the sequence OHAI (``0xC0 0x4F 0x48 0x41 0x49 0xC0``), indicating that it is now running. This is the only unsolicited packet ever sent by the ESP.
If the ``--no-stub`` argument is supplied to esptool, this entire step is skipped.
* esptool then uses READ_REG commands to read various addresses on the chip, to identify chip subtype, revision, etc.
* For commands which need to use the flash, the ESP32 ROM loader requires (and software loader on both chips support) the SPI_ATTACH and SPI_SET_PARAMS commands. See `SPI Configuration Commands`_.
* For software loader and/or ESP32 ROM loader, the host can send a CHANGE_BAUD command to set the baud rate to an explicit value. Compared to auto-detecting during the SYNC pulse, this can be more reliable for setting very high baud rate.
esptool tries to sync at (maximum) 115200bps and then sends this command to go to a higher baud rate, if requested.
Writing Data
^^^^^^^^^^^^
(Includes RAM Download, Flash Download, Compressed Flash Download.)
* RAM Download (MEM_BEGIN, MEM_DATA, MEM_END) loads data into the ESP chip memory space and (optionally) executes it.
* Flash Download (FLASH_BEGIN, FLASH_DATA) flashes data into the ESP SPI flash.
* Compressed Flash Download is the same, only the data is compressed using the gzip Deflate algorithm to reduce serial overhead. Not supported on ESP8266 ROM loader.
All three of these sequences follow a similar pattern:
* A _BEGIN command (FLASH_BEGIN, etc) is sent which contains basic parameters for the flash erase size, start address to write to, etc.The uploader also needs to specify how many "blocks" of data (ie individual data packets) will be sent, and how big each packet is.
* One or more _DATA commands (FLASH_DATA, etc) is sent where the data payload contains the actual data to write to flash/RAM. In the case of Compressed Flash Downloads, the data is compressed using the gzip deflate algorithm. The number of _DATA commands is specified in the _BEGIN command, as is the size of each _DATA payload.
The last data block should be padded to the block size with 0xFF bytes.
* An _END command (FLASH_END, etc) is sent to exit the bootloader and optionally reset the chip (or jump to an address in RAM, in the case of MEM_END). Not necessary to send after flashing if you wish to continue sending other or different commands.
It's not necessary to send flash erase commands before sending commands to write to flash, etc. The ROM loaders erase the to-be-written region in response to the FLASH_BEGIN command.
The software loaders do just-in-time erasing as they write data, to maximise overall flashing performance (each block of data is read into RAM via serial while the previous block is simultaneously being written to flash, and 4KB and 64KB erases are done as needed before writing to flash).
The block size chosen should be small enough to fit into RAM of the device. esptool uses 16KB which gives good performance when used with the stub loader.
Erase Size Bug
""""""""""""""
On ESP8266 ROM loader only (not software loader), there is a bug in the interpretation of the FLASH_BEGIN "erase size" parameter. Consult the ``ESP8266ROM.get_erase_size()`` function in esptool for the algorithm which works around this bug and provides the correct erase size parameter to send to the ESP8266.
This workaround is not needed on ESP32, or if the ESP8266 is running the software loader.
Verifying Uploaded Data
"""""""""""""""""""""""
The 8-bit checksum used in the upload protocol is not sufficient to ensure valid flash contents after upload. The uploader should send the SPI_FLASH_MD5 command (not supported on ESP8266 ROM loader) or use another method to verify flash contents.
The SPI_FLASH_MD5 command passes the start address in flash and the size of data to calculate. The MD5 value is returned in the response payload, before the status bytes.
Note that the ESP32 ROM loader returns the md5sum as 32 hex encoded ASCII bytes, whereas the software loader returns the md5sum as 16 raw data bytes of MD5 followed by 2 status bytes.
SPI Configuration Commands
^^^^^^^^^^^^^^^^^^^^^^^^^^
SPI Attach command
""""""""""""""""""
The SPI _ATTACH command enables the SPI flash interface. It takes a 32-bit data payload which is used to determine which SPI peripheral and pins should be used to connect to SPI flash.
On the ESP8266 software loader sending this command before interacting with SPI flash is optional, on ESP32 it is required. On ESP8266 ROM loader this command is not supported (SPI flash is enabled when the FLASH_BEGIN command is sent).
+------------------+----------------------------------------------------------------------------------------------------------------------------------+
| Value | Meaning |
+==================+==================================================================================================================================+
| 0 | Default SPI flash interface |
+------------------+----------------------------------------------------------------------------------------------------------------------------------+
| 1 | HSPI interface |
+------------------+----------------------------------------------------------------------------------------------------------------------------------+
| (other values) | (ESP32 only) Pin numbers as 6-bit values, packed into a 30-bit value. Order (from MSB): HD pin, Q pin, D pin, CS pin, CLK pin. |
+------------------+----------------------------------------------------------------------------------------------------------------------------------+
ESP32 Only Details
""""""""""""""""""
The "Default SPI flash interface" uses pins configured via the ``SPI_PAD_CONFIG_xxx`` efuses (if unset, these efuses are all zero and the default SPI flash pins given in the datasheet are used.)
When writing the values of each pin as 6-bit numbers packed into the data word, each 6-bit value uses the following representation:
* Pin numbers 0 through 30 are represented as themselves.
* Pin numbers 32 & 33 are represented as values 30 & 31.
* It is not possible to represent pins 30 & 31 or pins higher than 33. This is the same 6-bit representation used by the ``SPI_PAD_CONFIG_xxx`` efuses.
On ESP32 ROM loader only, there is an additional 4 bytes in the data payload of this command. These bytes should all be set to zero.
SPI Set Parameters
""""""""""""""""""
The SPI_SET_PARAMS command sets some parameters of the attached SPI flash chip (sizes, etc). This command is not supported by the ESP8266 ROM loader.
All the values which are passed except total size are hardcoded, and most are not used when writing to flash. See `flash_set_parameters function <https://github.com/espressif/esptool/blob/da31d9d7a1bb496995f8e30a6be259689948e43e/esptool.py#L655>`__ in esptool for the values which it sends.
32-bit Read/Write
^^^^^^^^^^^^^^^^^
The 32-bit read/write commands (READ_REG, WRITE_REG) allow word-oriented reading and writing of memory and register data.
These commands can be used to manipulate peripherals in arbitrary ways. For example, the esptool "flash id" functionality is implemented by manipulating the SPI peripheral registers to send a JEDEC flash ID command to the flash chip and read the response.
Reading Flash
^^^^^^^^^^^^^
The software loader implements a READ_FLASH command. This command behaves differently to other commands, including the ROM loader's READ_FLASH command:
* The host sends the READ_FLASH command and the data payload contains the offset, read size, size of each individual packet of data, and the maximum number of "un-acknowledged" data packets which can be in flight at one time.
* The software loader will send a standard response packet, with no additional data payload.
* Now the software loader will start sending SLIP packets with raw data (of the size requested in the command). There is no metadata included with these SLIP packets.
* After each SLIP packet is received, the host should send back a 4 byte raw SLIP acknowledgement packet with the total number of bytes which have been received. There is no header or other metadata included with these SLIP packets.
* The software loader may send up to a maximum number (specified by the host in the READ_FLASH commands) of data packets before waiting for the first acknowledgement packet. No more than this "max in flight" limit can be un-acknowledged at any one time.
* After all data packets are acknowledged received, the software loader sends a 16 byte MD5 digest of all the data which was read from flash. This is also sent as a raw SLIP packet, with no metadata.
After the read flash process is complete, the software loader goes back to normal command/response operation.
The ROM loader read flash command is more normal but also much slower to read data.
.. _tracing-communications:
Tracing Esptool Serial Communications
-------------------------------------
esptool has a ``--trace`` option which can be supplied in the first group of arguments (before the command). This will dump all traffic sent and received via the serial port to the console.
Here is a sample extract, showing a READ_REG command and response:
::
TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=1400f43f
TRACE +0.000 Write 14 bytes: c0000a0400000000001400f43fc0
TRACE +0.005 Read 1 bytes: c0
TRACE +0.000 Read 11 bytes: 010a0200620100000000c0
TRACE +0.000 Received full packet: 010a0200620100000000
The +X.XXX value is the time delta (in seconds) since the last trace line.
Values are printed in hexadecimal. If more than 16 bytes is printed at one time, a split display is used with hexadecimal bytes on the left and ASCII on the right. Non-printable characters are represented as ``.`` in ASCII:
Note that multiple protocol layers are represented in the logs. The "Write X bytes" lines show exactly which bytes are being sent "over the wire", including SLIP framing. Similarly the "Read X bytes" lines show what bytes are being read over the wire, including any SLIP framing.
Once a full SLIP packet is read, the same bytes - as a SLIP payload with any escaping removed - appear in the "Received full packet" log lines.
Here is a second example showing part of the initial synchronization sequence (lots of 0x55 bytes which are ``U`` in ASCII):
::
TRACE +0.000 Write 46 bytes:
c000082400000000 0007071220555555 | ...$........ UUU
5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
5555555555555555 5555555555c0 | UUUUUUUUUUUUU.
TRACE +0.011 Read 1 bytes: c0
TRACE +0.000 Read 63 bytes:
0108040007122055 00000000c0c00108 | ...... U........
0400071220550000 0000c0c001080400 | .... U..........
0712205500000000 c0c0010804000712 | .. U............
205500000000c0c0 01080400071220 | U............
TRACE +0.000 Received full packet: 010804000712205500000000
TRACE +0.000 Received full packet: 010804000712205500000000
.. note::
**IMPORTANT**: If you don't plan to use the esptool stub loader, pass ``--no-stub --trace`` to see interactions with the chip's built-in ROM loader only. Otherwise, the trace will show the full binary upload of the loader.
In addition to this trace feature, most operating systems have "system call trace" or "port trace" features which can be used to dump serial interactions.

View File

@@ -0,0 +1,114 @@
.. _spi-flash-modes:
SPI Flash Modes
===============
The ESP chips support four different SPI flash access modes: DIO, DOUT, QIO & QOUT. These can be set via the ``--flash_mode`` option of ``esptool.py write_flash``.
These options control how many I/O pins are used for communication with the attached SPI flash chip, and which SPI commands are used.
ESP chips use these commands when reading or executing code and data from the SPI flash chip. Data is read and then cached internally to the chip.
Summary
-------
In order of performance:
+------------+---------------+----------------------------------+-----------------------------------+
| Option | Mode Name | Pins Used | Speed (ESP8266 & ESP32) |
+============+===============+==================================+===================================+
| ``qio`` | Quad I/O | 4 pins used for address & data | Fastest. |
+------------+---------------+----------------------------------+-----------------------------------+
| ``qout`` | Quad Output | 4 pins used for data. | Approx 15% slower than ``qio``. |
+------------+---------------+----------------------------------+-----------------------------------+
| ``dio`` | Dual I/O | 2 pins used for address & data | Approx 45% slower than ``qio``. |
+------------+---------------+----------------------------------+-----------------------------------+
| ``dout`` | Dual Output | 2 pins used for data. | Approx 50% slower than ``qio``. |
+------------+---------------+----------------------------------+-----------------------------------+
In general, choose the fastest option for flash_mode that works with your device. Not all devices support all modes. See FAQ below for details.
Mode Descriptions
-----------------
Normal SPI
^^^^^^^^^^
A traditional "single" SPI (Serial Peripheral Interface) bus uses 4 pins for communication:
* Clock (CLK)
* Master Out Slave In (MOSI)
* Master In Slave Out (MISO)
* Chip Select (CS)
`Wikipedia has a fairly complete description <https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus>`__.
All of these signals are unidirectional. In single SPI mode, data is sent from the device to the host using the MISO pin and from the host to the device using the MOSI pin.
The maximum data rate for normal SPI is the clock rate in bits - so a 40MHz clock = 40Mbits/sec = 5Mbytes/sec.
Dual SPI
^^^^^^^^
To improve performance, SPI flash manufacturers introduced "Dual SPI". In Dual SPI modes, the MOSI & MISO pins are both used to read or write data simultaneously with two bits per clock cycle. This doubles the data rate for some commands, compared to single SPI.
In ``dout`` mode, the host uses the "Dual Output Fast Read" (3BH) command to read data. Each read command and the read address is sent from the host to the flash chip via normal SPI, but then the host reads the data via both the MOSI & MISO pins simultaneously with two bits per clock.
This doubles the data transfer rate compared to single SPI which only uses MISO to read data.
In ``dio`` mode, the host uses the "Dual I/O Fast Read" (BBH) command to read data. Each read command is sent from the host to the flash chip via normal SPI, but then the address is sent to the flash chip via both the MOSI & MISO pins with two bits per clock.
After this, the host reads the data bits with two bits per clock in the same way as "Dual Output Fast Read".
For ESP chips, 32 bytes is read per command and ``dio`` mode is approximately 5% faster than ``dout``.
Consult the datasheet for your particular SPI flash chip to determine if it supports either or both of these commands.
Quad SPI
^^^^^^^^
To further improve the performance of SPI flash data transfers, SPI flash manufacturers introduced "Quad SPI" mode. This mode added two additional pins (otherwise used for flash chip ``WP`` and ``HOLD`` signals) for data transfers. This allows double the data rate of dual SPI.
Not all flash chips support Quad SPI modes, and not all ESP chips have these pins wired up to the SPI flash chip. Some flash chips require special commands to enable quad modes (see below).
In ``qout`` mode, the host uses the "Quad Output Fast Read" (6BH) command to read data. This command is the same as "Dual Output Fast Read", only data is read on 4 pins instead of 2 with 4 bits per clock cycle. This makes the data transfer exactly twice as fast as "Dual Output Fast Read".
In ``qio`` mode, the host uses the "Quad I/O Fast Read" (EBH) command to read data. This command is the same as "Dual I/O Fast Read", only both address & data are transferred on 4 pins instead of 2 with 4 bits per clock cycle.
This makes both the address & data transfer exactly twice as fast as "Dual I/O Fast Read".
Frequently Asked Questions
--------------------------
Why don't qio & qout modes work with my Espressif chip/module?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It is usually one of the following reasons:
* The WP and HOLD pins of the SPI flash chip are not wired to the correct GPIOs of the Espressif chip. These pins must be connected correctly for quad modes to work, and not all boards/modules connect them at all.
* The SPI flash chip does not support quad modes. Look up the flash chip datasheet to see which modes it supports. You can identify the flash chip visually, or by using the :ref:`esptool.py flash_id <read-spi-flash-id>` command.
* Quad mode is not enabled correctly for this chip model. SPI flash is not a standard, so every manufacturer implements their chip differently. Most flash chips require certain commands to be sent in order to enable Quad SPI modes, and these commands vary.
For Espressif chips, this often means that the chip first boots in a Dual SPI mode and then software (bootloader for ESP32 and later or SDK for ESP8266) detects the chip type and tries to enable Quad SPI mode.
If the particular chip model is not supported by the software then it won't be able to enter quad mode.
Why does qout/dout mode work but qio/dio mode doesn't work?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Some SPI flash chip models only support the "Dual Output Fast Read" and/or "Quad Output Fast Read" commands, not their Dual I/O & Quad I/O equivalents.
Will my code run half as fast in Dual SPI mode compared to Quad SPI?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
No. Espressif chips execute code directly from flash, however because reading from flash is slow the data is cached transparently in RAM. Flash read commands are only sent went a cache miss occurs.
However, refilling the cache with a Dual SPI read is approximately half as fast as its Quad SPI equivalent.
If you can't use the Quad SPI modes, make sure you are configuring the fastest SPI Flash clock rate that works reliably on your board/module. An 80MHz SPI clock in Dual I/O mode is faster than a 40MHz SPI clock in Quad I/O mode.
How is flash mode communicated to the Espressif chip?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The bootloader .bin file, flashed to the SPI flash, contains a header which has flash speed, flash mode, and some other metadata. The initial host mode is determined by ROM code when it reads this header after reset.
Passing the ``-flash_mode`` argument to esptool will update this header when the file is being written to flash.
This only determines the mode which is used for the initial boot from reset. Software may then configure the flash mode differently as part of the boot process.
For example, on ESP32 if ESP-IDF is configured for qio/qout mode then the IDF software bootloader is actually flashed with a dio/dout mode.
When ROM code boots this bootloader from flash, the bootloader software checks the flash chip model and enables the correct Quad SPI mode for the rest of the boot process.
This is because of the multiple different ways to enable Quad SPI on different chip models.

View File

@@ -8,16 +8,28 @@ How to Contribute
Contributions to esptool - fixing bugs, adding features, adding documentation - are welcome. We accept contributions via `Github Pull Requests <https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests>`_.
.. _development-setup:
Development Setup
-----------------
To also install additional tools needed for actually developing and
testing esptool, run this command to install a development copy of
esptool *plus* packages useful for development:
Development mode allows you to run the latest development version from the `esptool repository on GitHub <https://github.com/espressif/esptool>`_.
.. code-block:: sh
$ git clone https://github.com/espressif/esptool.git
$ cd esptool
$ pip install --user -e .
This will install esptools dependencies and create some executable script wrappers in the users ``bin`` directory. The wrappers will run the scripts found in the git working directory directly, so any time the working directory contents change it will pick up the new versions.
Its also possible to run the scripts directly from the working directory with this Development Mode installation.
To also install additional tools needed for actually developing and testing esptool, run this command to install a development copy of esptool *plus* packages useful for development:
::
pip install --user -e .[dev]
$ pip install --user -e .[dev]
(This command uses the “extras” feature of setuptools.)
@@ -26,21 +38,18 @@ Reporting Issues
Please report bugs in esptool if you find them. However, before reporting a bug please check through the following:
* `Troubleshooting Section`_ - common problems and known issues
* :ref:`troubleshooting` - common problems and known issues
* `Existing Open Issues`_ - someone might have already encountered
this.
* `Existing Open Issues <https://github.com/espressif/esptool/issues>`_ - someone might have already encountered this.
If you dont find anything, please `open a new issue`_.
If you dont find anything, please `open a new issue <https://github.com/espressif/esptool/issues/new/choose>`_.
Sending Feature Requests
------------------------
Feel free to post feature requests. Its helpful if you can explain
exactly why the feature would be useful.
Feel free to post feature requests. Its helpful if you can explain exactly why the feature would be useful.
There are usually some outstanding feature requests in the `existing
issues list`_, feel free to add comments to them.
There are usually some outstanding feature requests in the `existing issues list <https://github.com/espressif/esptool/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement>`_, feel free to add comments to them.
Before Contributing
-------------------
@@ -62,44 +71,32 @@ Before sending us a Pull Request, please consider this list of points:
Code Style & Static Analysis
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
esptool complies with Flake 8 and is valid Python 2 & Python 3 code
(in the same source file.)
esptool complies with Flake 8 and is valid Python 2 & Python 3 code (in the same source file.)
When you submit a Pull Request, the GitHub Actions automated build
system will run automated checks for this, using the `flake8 tool`_. To
check your code locally before submitting, run ``python -m flake8`` (the
flake8 tool is installed as part of the development requirements shown
at the beginning of this document.)
When you submit a Pull Request, the GitHub Actions automated build system will run automated checks for this, using the `flake8 tool <http://flake8.readthedocs.io/en/latest/>`_. To check your code locally before submitting, run ``python -m flake8`` (the flake8 tool is installed as part of the development requirements shown at the beginning of this document.)
Automated Integration Tests
^^^^^^^^^^^^^^^^^^^^^^^^^^^
The test directory contains an integration suite with some integration
tests for esptool.py:
The test directory contains an integration suite with some integration tests for ``esptool.py``:
* ``test_imagegen.py`` tests the elf2image command and is run
automatically by GitHub Actions for each Pull Request. You can run
this command locally to check for regressions in the elf2image
functionality.
* ``test_imagegen.py`` tests the elf2image command and is run automatically by GitHub Actions for each Pull Request. You can run this command locally to check for regressions in the elf2image functionality.
* ``test_esptool.py`` is a `Python unittest`_ file that contains
integration tests to be run against real Espressif hardware.
These tests need real hardware so are not run automatically by GitHub
Actions, they need to be run locally in a command line with the following format:
* ``test_esptool.py`` is a `Python unittest <https://docs.python.org/3/library/unittest.html>`_ file that contains integration tests to be run against real Espressif hardware. These tests need real hardware so are not run automatically by GitHub Actions, they need to be run locally in a command line with the following format:
``./test_esptool.py <serial port> <name of chip> <baud rate> [optional test name(s)]``
``./test_esptool.py <serial port> <name of chip> <baud rate> [optional test name(s)]``
For example, to run all tests on an ESP32 board connected to
/dev/ttyUSB0, at 230400bps:
For example, to run all tests on an ESP32 board connected to /dev/ttyUSB0, at 230400bps:
``./test_esptool.py /dev/ttyUSB0 esp32 230400``
``./test_esptool.py /dev/ttyUSB0 esp32 230400``
Or to run the TestFlashing suite only on an ESP8266 board connected to
/dev/ttyUSB2\` at 460800bps:
Or to run the TestFlashing suite only on an ESP8266 board connected to /dev/ttyUSB2, at 460800bps:
``./test_esptool.py /dev/ttyUSB2 esp8266 460800 TestFlashing``
``./test_esptool.py /dev/ttyUSB2 esp8266 460800 TestFlashing``
(Note that some tests will fail at higher baud rates on some hardware.)
.. note::
Some tests might fail at higher baud rates on some hardware.
Pull Request Process
--------------------
@@ -108,11 +105,4 @@ After you open the Pull Request, there will probably be some discussion in the c
Once the Pull Request is ready to merge, it will first be merged into our internal git system for in-house automated testing.
If this process passes, it will be merged onto the public github repository.
.. _Troubleshooting Section: https://github.com/espressif/esptool/#troubleshooting
.. _Existing Open Issues: https://github.com/espressif/esptool/issues
.. _open a new issue: https://github.com/espressif/esptool/issues/new
.. _existing issues list: https://github.com/espressif/esptool/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement
.. _flake8 tool: http://flake8.readthedocs.io/en/latest/
.. _Python unittest: https://docs.python.org/3/library/unittest.html
If this process passes, it will be merged onto the public github repository, hooray!

View File

@@ -1,32 +1,26 @@
.. _espefuse:
espefuse.py
===========
``espefuse.py`` is a tool for communicating with an Espressif chip and
reading/writing ("burning") the one-time-programmable efuses values.
``espefuse.py`` is a tool for communicating with an Espressif chip and reading/writing ("burning") the one-time-programmable efuses values.
.. warning::
**IMPORTANT: Because efuse is one-time-programmable, it is possible to
permanently damage or "brick" your ESP32 using this tool. Use it with
great care.**
IMPORTANT: Because efuse is one-time-programmable, it is possible to permanently damage or "brick" your ESP32 using this tool. Use it with great care.
For more details about ESP32 efuse features, see the `Technical
Reference
Manual <http://espressif.com/en/support/download/documents>`__.
For more details about Espressif chips efuse features, see the `Technical Reference Manual <http://espressif.com/en/support/download/documents>`__.
``espefuse.py`` is installed alongside ``esptool.py``, so if
``esptool.py`` (v2.0 or newer) is available on the PATH then
``espefuse.py`` should be as well.
``espefuse.py`` is installed alongside ``esptool.py``, so if ``esptool.py`` (v2.0 or newer) is available on the PATH then ``espefuse.py`` should be as well.
Display efuse summary
Display Efuse Summary
---------------------
::
espefuse.py --port /dev/ttyUSB1 summary
The options ``--port`` and ``--before`` can be supplied, and are
identical to the equivalent ``esptool.py`` options.
The options ``--port`` and ``--before`` can be supplied, and are identical to the :ref:`equivalent esptool options <options>`.
Output from the summary command will look like this:
@@ -85,14 +79,11 @@ Output from the summary command will look like this:
On relatively new chip, most efuses are unburned (value 0).
In espefuse.py v2.6 and newer, read-protected efuse values are displayed
as question marks (??). On earlier versions, they are displayed as
zeroes.
In espefuse.py v2.6 and newer, read-protected efuse values are displayed as question marks (??). On earlier versions, they are displayed as zeroes.
For details on the meaning of each efuse value, refer to the Technical
Reference Manual.
For details on the meaning of each efuse value, refer to the `Technical Reference Manual <http://espressif.com/en/support/download/documents>`__.
Dump raw efuse registers
Dump Raw Efuse Registers
------------------------
To display raw efuse register values, use the ``dump`` subcommand:
@@ -111,13 +102,14 @@ To display raw efuse register values, use the ``dump`` subcommand:
EFUSE block 3:
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
Output corresponds directly to efuse register values in the `register
space <https://github.com/espressif/esp-idf/blob/master/components/soc/esp32/include/soc/efuse_reg.h#L19>`__.
Output corresponds directly to efuse register values in the `register space <https://github.com/espressif/esp-idf/blob/master/components/soc/esp32/include/soc/efuse_reg.h#L19>`__.
Burning an efuse
Burning an Efuse
----------------
**This command can brick your ESP32**
.. warning::
This command can brick your ESP32 if used incorrectly!
To burn an efuse to a new value, use the ``burn_efuse`` command:
@@ -125,26 +117,18 @@ To burn an efuse to a new value, use the ``burn_efuse`` command:
espefuse.py --port /dev/DONOTDOTHIS burn_efuse JTAG_DISABLE 1
The arguments to ``burn_efuse`` are the name of the efuse (as shown in
summary output) and the new value.
The arguments to ``burn_efuse`` are the name of the efuse (as shown in summary output) and the new value.
New values can be a numeric value in decimal or hex (with 0x prefix).
Efuse bits can only be burned from to 0 to 1, attempting to set any back
to 0 will have no effect. Most efuses have a limited bit width (many are
only 1-bit flags).
New values can be a numeric value in decimal or hex (with 0x prefix). Efuse bits can only be burned from to 0 to 1, attempting to set any back to 0 will have no effect. Most efuses have a limited bit width (many are only 1-bit flags).
Longer efuses (MAC addresses, keys) cannot be set via this command.
By default, ``espefuse.py`` will ask you to type BURN before it
permanently sets an efuse. The ``--do-not-confirm`` option allows you to
bypass this.
By default, ``espefuse.py`` will ask you to type BURN before it permanently sets an efuse. The ``--do-not-confirm`` option allows you to bypass this.
Setting Flash Voltage (VDD\_SDIO)
---------------------------------
Setting Flash Voltage (VDD_SDIO)
--------------------------------
After reset, the default ESP32 behaviour is to enable and configure the
flash voltage regulator (VDD\_SDIO) based on the level of the MTDI pin
(GPIO12).
After reset, the default ESP32 behaviour is to enable and configure the flash voltage regulator (VDD_SDIO) based on the level of the MTDI pin (GPIO12).
The default behaviour on reset is:
@@ -156,183 +140,147 @@ The default behaviour on reset is:
| High | Enabled at 1.8V |
+----------------------+--------------------------------+
Consult ESP32 Technical Reference Manual chapter 4.8.1 "VDD\_SDIO Power
Domain" for details.
Consult ESP32 Technical Reference Manual chapter 4.8.1 "VDD_SDIO Power Domain" for details.
A combination of 3 efuses (``XPD_SDIO_FORCE``, ``XPD_SDIO_REG``,
``XPD_SDIO_TIEH``) can be burned in order to override this behaviour and
disable VDD\_SDIO regulator, or set it to a fixed voltage. These efuses
can be burned with individual ``burn_efuse`` commands, but the
``set_flash_voltage`` command makes it easier:
A combination of 3 efuses (``XPD_SDIO_FORCE``, ``XPD_SDIO_REG``, ``XPD_SDIO_TIEH``) can be burned in order to override this behaviour and disable VDD_SDIO regulator, or set it to a fixed voltage. These efuses can be burned with individual ``burn_efuse`` commands, but the ``set_flash_voltage`` command makes it easier:
Disable VDD\_SDIO regulator
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Disable VDD_SDIO Regulator
^^^^^^^^^^^^^^^^^^^^^^^^^^
::
espefuse.py set_flash_voltage OFF
Once set: \* VDD\_SDIO regulator always disabled. \* MTDI pin (GPIO12)
is ignored. \* Flash must be powered externally and voltage supplied to
VDD\_SDIO pin of ESP32. \* Efuse ``XPD_SDIO_FORCE`` is burned.
Once set:
Fixed 1.8V VDD\_SDIO
* VDD_SDIO regulator always disabled.
* MTDI pin (GPIO12) is ignored.
* Flash must be powered externally and voltage supplied to VDD_SDIO pin of ESP32.
* Efuse ``XPD_SDIO_FORCE`` is burned.
Fixed 1.8V VDD_SDIO
^^^^^^^^^^^^^^^^^^^^
::
espefuse.py set_flash_voltage 1.8V
Once set: \* VDD\_SDIO regulator always enables at 1.8V. \* MTDI pin
(GPIO12) is ignored. \* External voltage should not be supplied to
VDD\_SDIO. \* Efuses ``XPD_SDIO_FORCE`` and ``XPD_SDIO_REG`` are burned.
Once set:
Fixed 3.3V VDD\_SDIO
* VDD_SDIO regulator always enables at 1.8V.
* MTDI pin (GPIO12) is ignored.
* External voltage should not be supplied to VDD_SDIO.
* Efuses ``XPD_SDIO_FORCE`` and ``XPD_SDIO_REG`` are burned.
Fixed 3.3V VDD_SDIO
^^^^^^^^^^^^^^^^^^^^
::
espefuse.py set_flash_voltage 3.3V
Once set: \* VDD\_SDIO regulator always enables at 3.3V. \* MTDI pin
(GPIO12) is ignored. \* External voltage should not be supplied to
VDD\_SDIO. \* Efuses ``XPD_SDIO_FORCE``, ``XPD_SDIO_REG``,
``XPD_SDIO_TIEH`` are burned.
Once set:
Subsequent changes
* VDD_SDIO regulator always enables at 3.3V.
* MTDI pin (GPIO12) is ignored.
* External voltage should not be supplied to VDD_SDIO.
* Efuses ``XPD_SDIO_FORCE``, ``XPD_SDIO_REG``, ``XPD_SDIO_TIEH`` are burned.
Subsequent Changes
^^^^^^^^^^^^^^^^^^
Once an efuse is burned it cannot be un-burned. However, changes can be
made by burning additional efuses:
Once an efuse is burned it cannot be un-burned. However, changes can be made by burning additional efuses:
- ``set_flash_voltage OFF`` can be changed to ``1.8V`` or ``3.3V``.
- ``set_flash_voltage 1.8V`` can be changed to ``3.3V``
* ``set_flash_voltage OFF`` can be changed to ``1.8V`` or ``3.3V``
* ``set_flash_voltage 1.8V`` can be changed to ``3.3V``
Burning a key
Burning a Key
-------------
**This command can brick your ESP32**
.. warning::
The efuse key blocks BLK1, BLK2 and BLK3 can all hold encryption keys.
The ``burn_key`` subcommand loads a key (stored as a raw binary file)
and burns it to a key block.
This command can brick your ESP32 if used incorrectly!
"flash\_encryption" can be used as an alias for BLK1, and "secure\_boot"
can be used as an alias for BLK2.
The efuse key blocks BLK1, BLK2 and BLK3 can all hold encryption keys. The ``burn_key`` subcommand loads a key (stored as a raw binary file) and burns it to a key block.
- The ``burn_key`` command should only be used for hardware flash
encryption or secure boot keys. See `Burning non-key
data <#burning-non-key-data>`__ for a command that works for data
read by software.
``flash_encryption`` can be used as an alias for BLK1, and ``secure_boot`` can be used as an alias for BLK2.
* The ``burn_key`` command should only be used for hardware flash encryption or secure boot keys. See `Burning non-key data <#burning-non-key-data>`__ for a command that works for data read by software.
Key Coding Scheme
^^^^^^^^^^^^^^^^^
When the "None" coding scheme is in use, keys are 256-bits (32 bytes)
long. When 3/4 Coding Scheme is in use (``CODING_SCHEME`` efuse has
value 1 not 0), keys are 192-bits (24 bytes) long and an additional 64
bits of error correction data are also written. espefuse.py v2.6 or
newer is required to burn keys with 3/4 Coding Scheme. The key file must
be the appropriate length for the coding scheme currently in use.
When the "None" coding scheme is in use, keys are 256-bits (32 bytes) long. When 3/4 Coding Scheme is in use (``CODING_SCHEME`` efuse has value 1 not 0), keys are 192-bits (24 bytes) long and an additional 64 bits of error correction data are also written.
``espefuse.py`` v2.6 or newer is required to burn keys with 3/4 Coding Scheme. The key file must be the appropriate length for the coding scheme currently in use.
When keys are stored in ESP32 Efuse blocks, they are stored in reverse
byte order (last byte of the key is written to the first byte of efuse,
etc.)
When keys are stored in ESP32 Efuse blocks, they are stored in reverse byte order (last byte of the key is written to the first byte of efuse, etc.)
Unprotected Keys
^^^^^^^^^^^^^^^^
By default, when an encryption key block is burned it is also read and
write protected. The ``--no-protect-key`` option will disable this
behaviour (you can separately read- or write-protect the key later.)
Note that leaving a key unprotected may compromise its use as a security
feature.
By default, when an encryption key block is burned it is also read and write protected. The ``--no-protect-key`` option will disable this behaviour (you can separately read- or write-protect the key later.)
.. note::
Leaving a key unprotected may compromise its use as a security feature.
::
espefuse.py --port /dev/DONOTDOTHIS burn_key secure_boot keyfile.bin
Note that the hardware flash encryption and secure boot features require
the key to be written to the efuse block in reversed byte order,
compared to the order used by the AES algorithm on the host.
``burn_key`` automatically reverses the bytes when writing. For this
reason, an unprotected key will read back in the reverse order to the
``keyfile.bin`` on the host.
Note that the hardware flash encryption and secure boot features require the key to be written to the efuse block in reversed byte order, compared to the order used by the AES algorithm on the host. ``burn_key`` automatically reverses the bytes when writing.
For this reason, an unprotected key will read back in the reverse order to the ``keyfile.bin`` on the host.
force-write-always
^^^^^^^^^^^^^^^^^^
Force Writing a Key
^^^^^^^^^^^^^^^^^^^
Normally, a key will only be burned if the efuse block has not been
previously written to. The ``--force-write-always`` option can be used
to ignore this and try to burn the key anyhow. Note that this option is
still limited by the efuse hardware - hardware doesn't allow any efuse
bits to be cleared 1->0, and can't write anything to write protected
efuse blocks.
Normally, a key will only be burned if the efuse block has not been previously written to. The ``--force-write-always`` option can be used to ignore this and try to burn the key anyhow.
Note that this option is still limited by the efuse hardware - hardware doesn't allow any efuse bits to be cleared 1->0, and can't write anything to write protected efuse blocks.
Confirmation
^^^^^^^^^^^^
The ``--do-not-confirm`` option can be used with ``burn_key``, otherwise
a manual confirmation step is required.
The ``--do-not-confirm`` option can be used with ``burn_key``, otherwise a manual confirmation step is required.
Limitations of the burn\_key command
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Limitations
^^^^^^^^^^^
The ``burn_key`` command is only suitable for flash encryption and
secure boot keys:
The ``burn_key`` command is only suitable for flash encryption and secure boot keys:
- Complete block is always written. (This means 256-bits for "None"
coding Scheme or 192-bits for 3/4 Coding Scheme).
- The data is written in reverse byte order for compatibility with
encryption hardware (see `above <#unprotected-keys>`__).
- By default, the data is read- and write-protected so it can only be
used by hardware.
* Complete block is always written. (This means 256-bits for "None" coding Scheme or 192-bits for 3/4 Coding Scheme).
* The data is written in reverse byte order for compatibility with encryption hardware (see `above <#unprotected-keys>`__).
* By default, the data is read- and write-protected so it can only be used by hardware.
Burning non-key data
Burning non-Key Data
--------------------
The ``burn_block_data`` command allows writing arbitrary data from a
file into an efuse block, for software use.
The ``burn_block_data`` command allows writing arbitrary data from a file into an efuse block, for software use.
This command is available in espefuse.py v2.6 and newer.
Example
^^^^^^^
Write to Efuse BLK3 from binary file ``device_id.bin``, starting at
efuse byte offset 6:
**Example:** Write to Efuse BLK3 from binary file ``device_id.bin``, starting at efuse byte offset 6:
::
espefuse.py -p PORT burn_block_data --offset 6 BLK3 device_id.bin
- Data is written to the Efuse block in normal byte order (treating the
Efuse block as if it was an array of bytes). It can be read back in
firmware from the efuse read registers, but these reads must be
always be complete register words (4-byte aligned).
- Part of the Efuse block can be written at a time. The ``--offset``
argument allows writing to a byte offset inside the Efuse block
itself.
- This command is not suitable for writing key data which will be used
by flash encryption or secure boot hardware. Use
`burn\_key <#burning-a-key>`__ for this.
- Data is written to the Efuse block in normal byte order (treating the efuse block as if it was an array of bytes). It can be read back in firmware from the efuse read registers, but these reads must be always be complete register words (4-byte aligned).
- Part of the Efuse block can be written at a time. The ``--offset`` argument allows writing to a byte offset inside the Efuse block itself.
- This command is not suitable for writing key data which will be used by flash encryption or secure boot hardware. Use `burn_key <#burning-a-key>`__ for this.
burn\_block\_data restrictions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Limitations
^^^^^^^^^^^
For "None" Coding Scheme, there are no restrictions on the range of
bytes which can be written in the Efuse block (but any bit in efuse can
only be set 0->1, never cleared 1->0).
For "None" Coding Scheme, there are no restrictions on the range of bytes which can be written in the Efuse block (but any bit in efuse can only be set 0->1, never cleared 1->0).
For "3/4" Coding Scheme, the length of the data file and the offset must
both be a multiple of 6 bytes. Each 6 byte span can only be written one
time.
For "3/4" Coding Scheme, the length of the data file and the offset must both be a multiple of 6 bytes. Each 6 byte span can only be written one time.
SPI flash pins
.. _espefuse-spi-flash-pins:
SPI Flash Pins
--------------
The following efuses configure the SPI flash pins which are used to
boot:
The following efuses configure the SPI flash pins which are used to boot:
::
@@ -342,144 +290,116 @@ boot:
SPI_PAD_CONFIG_HD Override SD_DATA_2 pad (GPIO9/SPIHD) = 0 R/W (0x0)
SPI_PAD_CONFIG_CS0 Override SD_CMD pad (GPIO11/SPICS0) = 0 R/W (0x0)
On ESP32 chips without integrated SPI flash, these efuses are set to
zero in the factory. This causes the default GPIO pins (shown in the
summary output above) to be used for the SPI flash.
On ESP32 chips without integrated SPI flash, these efuses are set to zero in the factory. This causes the default GPIO pins (shown in the summary output above) to be used for the SPI flash.
On ESP32 chips with integrated internal SPI flash, these efuses are
burned in the factory to the GPIO numbers where the flash is connected.
These values override the defaults on boot.
On ESP32 chips with integrated internal SPI flash, these efuses are burned in the factory to the GPIO numbers where the flash is connected. These values override the defaults on boot.
In order to change the SPI flash pin configuration, these efuses can be
burned to the GPIO numbers where the flash is connected. If at least one
of these efuses is burned, all of of them must be set to the correct
values.
In order to change the SPI flash pin configuration, these efuses can be burned to the GPIO numbers where the flash is connected. If at least one of these efuses is burned, all of of them must be set to the correct values.
If these efuses are burned, GPIO1 (U0TXD pin) is no longer consulted to
set the boot mode from SPI to HSPI flash on reset.
If these efuses are burned, GPIO1 (U0TXD pin) is no longer consulted to set the boot mode from SPI to HSPI flash on reset.
These pins can be set to any GPIO number in the range 0-29, 32 or 33.
Values 30 and 31 cannot be set. The "raw" hex value for pins 32,33 is
30,31 (this is visible in the summary output if these pins are
configured for any SPI I/Os.)
These pins can be set to any GPIO number in the range 0-29, 32 or 33. Values 30 and 31 cannot be set. The "raw" hex value for pins 32, 33 is 30, 31 (this is visible in the summary output if these pins are configured for any SPI I/Os.)
ie:
For example:
::
SPI_PAD_CONFIG_CS0 Override SD_CMD pad (GPIO11/SPICS0) = 32 R/W (0x1e)
If using the ``burn_efuse`` command to configure these pins, always
specify the actual GPIO number you wish to set.
If using the ``burn_efuse`` command to configure these pins, always specify the actual GPIO number you wish to set.
Read- and Write- protecting efuses
Read- and Write- Protecting Efuses
----------------------------------
**This command can severely limit your ESP32 options**
.. warning::
Some efuses can be read- or write-protected, preventing further changes.
``burn_key`` subcommand read and write protects new keys by default, but
other efuses can be protected iwth the ``read_protect_efuse`` and
``write_protect_efuse`` commands.
This command can severely limit your ESP32 options.
The ``R/W`` output in the summary display will change to indicate
protected efuses: \* ``-/W`` indicates read protected (value will always
show all-zeroes, even though hardware may use the correct value.) \*
``R/-`` shows write protected (no further bits can be set), \* ``-/-``
means read and write protected.
Some efuses can be read- or write-protected, preventing further changes. ``burn_key`` subcommand read and write protects new keys by default, but other efuses can be protected iwth the ``read_protect_efuse`` and ``write_protect_efuse`` commands.
Sample:
The ``R/W`` output in the summary display will change to indicate protected efuses:
* ``-/W`` indicates read protected (value will always show all-zeroes, even though hardware may use the correct value)
* ``R/-`` shows write protected (no further bits can be set)
* ``-/-`` means read and write protected
Example:
::
espefuse.py --port /dev/SOMEPORT read_protect_efuse KEY_STATUS
The ``--do-not-confirm`` option can be used with ``burn_key``, otherwise
a manual confirmation step is required.
The ``--do-not-confirm`` option can be used with ``burn_key``, otherwise a manual confirmation step is required.
**NOTE that efuses are often read/write protected as a group, so
protecting one will cause some related efuses to become protected.
espefuse.py will confirm the full list of efuses that will become
protected.**
.. note::
Efuses are often read/write protected as a group, so protecting one will cause some related efuses to become protected. ``espefuse.py`` will confirm the full list of efuses that will become protected.
The following efuses can be read protected:
* FLASH\_CRYPT\_CONFIG
* CODING\_SCHEME
* KEY\_STATUS
* FLASH_CRYPT_CONFIG
* CODING_SCHEME
* KEY_STATUS
* BLK1
* BLK2
* BLK3
The following efuses can be write protected:
* WR\_DIS,RD\_DIS
* FLASH\_CRYPT\_CNT
* WR_DIS, RD_DIS
* FLASH_CRYPT_CNT
* MAC
* XPD\_SDIO\_FORCE
* XPD\_SDIO\_REG
* XPD\_SDIO\_TIEH
* SPI\_PAD\_CONFIG\_CLK
* SPI\_PAD\_CONFIG\_Q
* SPI\_PAD\_CONFIG\_D
* SPI\_PAD\_CONFIG\_HD
* SPI\_PAD\_CONFIG\_CS0
* FLASH\_CRYPT\_CONFIG
* CODING\_SCHEME
* CONSOLE\_DEBUG\_DISABLE
* DISABLE\_SDIO\_HOST
* ABS\_DONE\_0
* ABS\_DONE\_1
* JTAG\_DISABLE
* DISABLE\_DL\_ENCRYPT
* DISABLE\_DL\_DECRYPT
* DISABLE\_DL\_CACHE
* KEY\_STATUS
* XPD_SDIO_FORCE
* XPD_SDIO_REG
* XPD_SDIO_TIEH
* SPI_PAD_CONFIG_CLK
* SPI_PAD_CONFIG_Q
* SPI_PAD_CONFIG_D
* SPI_PAD_CONFIG_HD
* SPI_PAD_CONFIG_CS0
* FLASH_CRYPT_CONFIG
* CODING_SCHEME
* CONSOLE_DEBUG_DISABLE
* DISABLE_SDIO_HOST
* ABS_DONE_0
* ABS_DONE_1
* JTAG_DISABLE
* DISABLE_DL_ENCRYPT
* DISABLE_DL_DECRYPT
* DISABLE_DL_CACHE
* KEY_STATUS
* BLK1
* BLK2
* BLK3
Execute eFuse python script
Execute Efuse Python Script
---------------------------
::
espefuse.py execute_scripts efuse_script1.py efuse_script2.py ...
This command allows burning all needed eFuses at one time based on your
own python script and control issues during the burn process if so it
will abort the burn process. This command has a few arguments:
This command allows burning all needed efuses at one time based on your own python script and control issues during the burn process if so it will abort the burn process. This command has a few arguments:
- ``scripts`` is a list of scripts. The special format of python
scripts can be executed inside espefuse.py.
* ``scripts`` is a list of scripts. The special format of python scripts can be executed inside ``espefuse.py``.
Below you can see some examples of the script. This script file is run
from espefuse.py as ``exec(open(file.name).read())`` it means that some
functions and imported libs are available for using like ``os``. Please
use only provided functions. If you want to use other libs in the script
you can add them manually.
Below you can see some examples of the script. This script file is run from ``espefuse.py`` as ``exec(open(file.name).read())`` it means that some functions and imported libs are available for using like ``os``. Please use only provided functions.
If you want to use other libs in the script you can add them manually.
Inside this script, you can call all commands which are available in
CLI, see ``espefuse.py --help``. To run a efuse command you need to call
``espefuse(esp, efuses, args, 'burn_efuse DISABLE_DL_DECRYPT 1')``. This
command will not burn eFuses immediately, the burn occurs at the end of
all scripts. But if necessary, you can call ``efuses.burn_all()`` which
asks you ``Type 'BURN' (all capitals) to continue.``. To skip this
question and go without confirmation just add the ``--do-not-confirm``
flag to the ``execute_scripts`` command.
Inside this script, you can call all commands which are available in CLI, see ``espefuse.py --help``. To run a efuse command you need to call ``espefuse(esp, efuses, args, 'burn_efuse DISABLE_DL_DECRYPT 1')``. This command will not burn eFuses immediately, the burn occurs at the end of all scripts.
If necessary, you can call ``efuses.burn_all()`` which prompts ``Type 'BURN' (all capitals) to continue.``. To skip this check and go without confirmation just add the ``--do-not-confirm`` flag to the ``execute_scripts`` command.
::
espefuse.py execute_scripts efuse_script1.py --do-not-confirm
Additionally, you can implement some checks based on the value of
eFuses. To get value of a eFuse use -
``efuses['FLASH_CRYPT_CNT'].get()``. Some eFuses have a dictionary to
convert from a value to a human-readable as it looks in the table is
printed by the ``summary`` command. See how it is done for
``CODING_SCHEME`` it calls ``get_meaning()`` 0: "NONE (BLK1-3 len=256
bits)", 1: "3/4 (BLK1-3 len=192 bits)", 2: "REPEAT (BLK1-3 len=128 bits)
not supported", 3: "NONE (BLK1-3 len=256 bits)".
Additionally, you can implement some checks based on the value of efuses. To get value of an efuse use ``efuses['FLASH_CRYPT_CNT'].get()``. Some eFuses have a dictionary to convert from a value to a human-readable as it looks in the table is printed by the ``summary`` command.
See how it is done for ``CODING_SCHEME`` when ``get_meaning()`` is called:
* 0: "NONE (BLK1-3 len=256 bits)"
* 1: "3/4 (BLK1-3 len=192 bits)"
* 2: "REPEAT (BLK1-3 len=128 bits) not supported"
* 3: "NONE (BLK1-3 len=256 bits)"
.. code:: python
@@ -504,17 +424,7 @@ not supported", 3: "NONE (BLK1-3 len=256 bits)".
espefuse(esp, efuses, args, 'burn_efuse JTAG_DISABLE 1')
...
After ``efuses.burn_all()``, all needed eFuses will be burnt to chip in
order BLK\_MAX to BLK\_0. This order prevents cases when protection is
set before the value goes to a block. Please note this while developing
your scripts. Upon completion, the new eFuses will be read back, and
will be done some checks of written eFuses by espefuse.py. In
production, you might need to check that all written eFuses are set
properly, see the example below to get how to check it.
After ``efuses.burn_all()``, all needed efuses will be burnt to chip in order ``BLK_MAX`` to ``BLK_0``. This order prevents cases when protection is set before the value goes to a block. Please note this while developing your scripts.
Upon completion, the new eFuses will be read back, and will be done some checks of written eFuses by ``espefuse.py``. In production, you might need to check that all written efuses are set properly, see the example below.
The script below burns some eFuses and checks them after reading back.
To check read and write protection using ``is_readable()`` and
``is_writeable()``.
See
`test\_efuse\_script.py <https://github.com/espressif/esptool/blob/master/test/efuse_scripts/esp32xx/test_efuse_script.py>`__
The script `test_efuse_script.py <https://github.com/espressif/esptool/blob/master/test/efuse_scripts/esp32xx/test_efuse_script.py>`__ burns some efuses and checks them after reading back. To check read and write protection, ``is_readable()`` and ``is_writeable()`` are called.

View File

@@ -1,11 +1,11 @@
.. _espsecure:
espsecure.py
============
``espsecure.py`` is a tool for manipulating data that relates to the
ESP32' secure boot and flash encryption features.
``espsecure.py`` is a tool for manipulating data that relates to the secure boot and flash encryption features of ESP32 and later Espressif chips.
For more details, see the ESP-IDF documentation which explains this tool
and how to use it to enable the relevant ESP32 features:
For more details, see the ESP-IDF documentation which explains this tool and how to use it to enable the relevant features:
* `Secure Boot <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/secure-boot-v2.html>`__
* `Flash Encryption <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html>`__
* `Secure Boot <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/secure-boot-v2.html>`_
* `Flash Encryption <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html>`_

View File

@@ -0,0 +1,157 @@
.. _advanced-commands:
Advanced Commands
=================
The ``write_flash``, ``read_flash``, ``erase_flash``, ``erase_region``, ``read_mac``, ``flash_id``, ``elf2image``, ``image_info`` and ``merge_bin`` commands are all documented in the :ref:`commands` section.
The following less common commands are for more advanced users.
.. _verify-flash:
Verify Flash Data: verify_flash
-------------------------------
The ``verify_flash`` command allows you to verify that data in flash matches a local file.
The ``write_flash`` command always verifies the MD5 hash of data which is written to flash, so additional verification is not usually needed. However, if you wish to perform a byte-by-byte verification of the flash contents (and optionally print the differences to the console) then you can do so with this command:
::
esptool.py verify_flash --diff yes 0x40000 my_app.elf-0x40000.bin
The ``--diff yes`` option specifies that if the files are different, the details should be printed to the console.
.. note::
* If verifying a default boot image (offset 0 for ESP8266 or offset 0x1000 for ESP32) then any ``--flash_mode``, ``--flash_size`` and ``--flash_freq`` arguments which were passed to `write_flash` must also be passed to ``verify_flash``. Otherwise, ``verify_flash`` will detect mismatches in the header of the image file.
* Another way to compare flash contents is to use the ``read_flash`` command, and then use binary diffing tools on the host.
.. _dump-mem:
Dump a Memory Region to File: dump_mem
--------------------------------------
The ``dump_mem`` command will dump a region from the chip's memory space to a file. For example, to dump the ROM (64 kB) from an ESP8266:
::
esptool.py dump_mem 0x40000000 65536 iram0.bin
.. _load-ram:
Load a Binary to RAM: load_ram
------------------------------
The ``load_ram`` command allows the loading of an executable binary image (created with the ``elf2image`` or ``make_image`` commands) directly into RAM, and then immediately executes the program contained within it.
::
esptool.py --no-stub load_ram ./test/images/helloworld-esp8266.bin
.. note::
* The binary image must only contain IRAM- and DRAM-resident segments. Any SPI flash mapped segments will not load correctly and the image will probably crash. The ``image_info`` command can be used to check the binary image contents.
* Because the software loader is resident in IRAM and DRAM, this limits the region where a new program may be loaded. An error will be printed if the new program overlaps with the software loader in RAM. Older esptool versions may hang. Pass ``esptool.py --no-stub`` to avoid this problem.
* Due to a limitation in the ROM loader, when using ``--no-stub`` any very early serial output from a program may be lost if the program resets or reconfigures the UART. To avoid this problem, a program can be compiled with ``ets_delay_us(1)`` as the very first statement after the entry point.
.. _read-mem-write-mem:
Read or Write RAM: read_mem / write_mem
---------------------------------------
The ``read_mem`` & ``write_mem`` commands allow reading and writing single words (4 bytes) of RAM. This can be used to "peek" and "poke" at registers.
::
esptool.py write_mem 0x400C0000 0xabad1dea
::
esptool.py read_mem 0x400C0000
.. _read-flash-status:
Read Flash Chip Registers: read_flash_status
--------------------------------------------
This command is intended for use when debugging hardware flash chip-related problems. It allows sending a ``RDSR``, ``RDSR2`` and/or ``RDSR3`` commands to the flash chip to read the status register contents. This can be used to check write protection status, for example:
::
esptool.py read_flash_status --bytes 2
The ``--bytes`` argument determines how many status register bytes are read.
* ``--bytes 1`` sends the most common ``RDSR`` command (05h) and returns a single byte of status.
* ``--bytes 2`` sends both ``RDSR`` (05h) and ``RDSR2`` (35h), reads one byte of status from each, and returns a two byte status.
* ``--bytes 3`` sends ``RDSR`` (05h), ``RDSR2`` (35h), and ``RDSR3`` (15h), reads one byte of status from each, and returns a 3 byte status.
.. note::
Not all flash chips support all of these comands. Consult the specific flash chip datasheet for details.
.. _write-flash-status:
Write Flash Chip Registers: write_flash_status
-----------------------------------------------
This command is intended for use when debugging hardware flash chip-related problems. It allows sending ``WRSR``, ``WRSR2`` and/or ``WRSR3`` commands to the flash chip to write the status register contents. This can be used to clear write protection bits, for example:
::
esptool.py write_flash_status --bytes 2 --non-volatile 0
The ``--bytes`` option is similar to the corresponding option for ``read_flash_status`` and causes a mix of ``WRSR`` (01h), ``WRSR2`` (31h), and ``WRSR3`` (11h) commands to be sent to the chip. If ``--bytes 2`` is used then ``WRSR`` is sent first with a 16-bit argument and then with an 8-bit argument, as different flash chips use this command differently.
Otherwise, each command is accompanied by 8-bits of the new status register value.
A second option ``--non-volatile`` can be used in order to send a ``WREN`` (06h) command before writing the status. This may allow non-volatile status register bits to be set or cleared. If the ``--non-volatile`` option is not supplied, a ``WEVSR`` (50h) command is sent instead of ``WREN``.
.. note::
Consult the specific flash chip datasheet for details about which commands are recognised by a particular chip.
.. warning::
Setting status bits (particularly non-volatile ones) can have permanent side effects for some flash chips, so check carefully before using this command to set any bits!
.. _chip-id:
Read the Chip ID: chip_id
-------------------------
The ``chip_id`` command allows you to read a 4 byte ID which forms part of the MAC address. It is usually better to use ``read_mac`` to identify a chip.
::
esptool.py chip_id
On ESP8266, output is the same as the ``system_get_chip_id()`` SDK function. The chip ID is four bytes long, the lower three bytes are the final bytes of the MAC address. The upper byte is zero.
On ESP32, there is no ``system_get_chip_id()`` function and this command is the same as ``esptool.py read_mac``.
.. _make-image:
Assemble a Firmware Image: make_image
-------------------------------------
``make_image`` allows you to manually assemble a firmware image from binary segments (such as those extracted from objcopy). For example:
::
esptool.py --chip esp8266 make_image -f app.text.bin -a 0x40100000 -f app.data.bin -a 0x3ffe8000 -f app.rodata.bin -a 0x3ffe8c00 app.flash.bin
This command does not require a serial connection.
.. note::
* ``make_image`` is currently only supported for ESP8266, not ESP32 or later.
* In general, it is better to create an ELF image (including any binary data as part of the ELF, by using objcopy or other tools) and then use ``elf2image`` to generate the ``.bin`` file.
.. _run:
Boot Application Code: run
--------------------------
The ``run`` command immediately exits the bootloader and attempts to boot the normal application code. This command is of limited use, and only works as intended on ESP8266.

View File

@@ -0,0 +1,98 @@
.. _advanced-options:
Advanced Options
================
The following advanced configuration options can be used for all esptool commands (they are placed before the command name on the command line).
For basic/fundamental configuration options, see the :ref:`options` page.
Reset Modes
-----------
By default, esptool tries to hard reset the chip into bootloader mode before it starts and hard resets the chip to run the normal program once it is complete. The ``--before`` and ``--after`` options allow this behavior to be changed:
Reset Before Operation
^^^^^^^^^^^^^^^^^^^^^^
The ``--before`` argument allows you to specify whether the chip needs resetting into bootloader mode before esptool talks to it.
* ``--before default_reset`` is the default, which uses DTR & RTS serial control lines (see :ref:`entering-the-bootloader`) to try to reset the chip into bootloader mode.
* ``--before no_reset`` will skip DTR/RTS control signal assignments and just start sending a serial synchronisation command to the chip. This is useful if your chip doesn't have DTR/RTS, or for some serial interfaces (like Arduino board onboard serial) which behave differently when DTR/RTS are toggled.
* ``--before no_reset_no_sync`` will skip DTR/RTS control signal assignments and skip also the serial synchronization command. This is useful if your chip is already running the stub bootloader and you want to avoid resetting the chip and uploading the stub again.
* ``--before usb_reset`` will use custom reset sequence for USB-JTAG-Serial (used for example for ESP32-C3 connected through the USB-JTAG-Serial peripheral). Usually, this option doesn't have to be used directly. Esptool should be able to detect connection through USB-JTAG-Serial.
Reset After Operation
^^^^^^^^^^^^^^^^^^^^^
The ``--after`` argument allows you to specify whether the chip should be reset after the esptool operation completes:
* ``--after hard_reset`` is the default. The DTR serial control line is used to reset the chip into a normal boot sequence.
* ``--after soft_reset`` is currently only supported on ESP8266. This runs the user firmware, but any subsequent reset will return to the serial bootloader. This was the reset behaviour in esptool v1.x.
* ``--after no_reset`` leaves the chip in the serial bootloader, no reset is performed.
* ``--after no_reset_stub`` leaves the chip in the stub bootloader, no reset is performed.
Disabling the Stub Loader
-------------------------
The ``--no-stub`` option disables uploading of a software "stub loader" that manages flash operations, and only talks directly to the loader in ROM.
Passing ``--no-stub`` will disable certain options, as not all options are implemented in every chip's ROM loader.
Overriding SPI Flash Connections
--------------------------------
The optional ``--spi-connection`` argument overrides the SPI flash connection configuration on ESP32. This means that the SPI flash can be connected to other pins, or esptool can be used to communicate with a different SPI flash chip to the default.
Supply the ``--spi-connection`` argument after the ``esptool.py`` command, ie ``esptool.py flash_id --spi-connection HSPI``.
Default Behavior
^^^^^^^^^^^^^^^^
If the ``--spi-connection`` argument is not provided, the SPI flash is configured to use :ref:`pin numbers set in efuse <espefuse-spi-flash-pins>`. These are the same SPI flash pins that are used during a normal boot.
The only exception to this is if the ``--no-stub`` option is also provided. In this case, efuse values are ignored and ``--spi-connection`` will default to ``--spi-connection SPI`` unless set to a different value.
SPI Mode
^^^^^^^^
``--spi-connection SPI`` uses the default SPI pins:
* CLK = GPIO 6
* Q = GPIO 7
* D = GPIO 8
* HD = GPIO 9
* CS = GPIO 11
During normal booting, this configuration is selected if all SPI pin efuses are unset and GPIO1 (U0TXD) is not pulled low (default).
This is the normal pin configuration for ESP32 chips that do not contain embedded flash.
HSPI Mode
^^^^^^^^^
``--spi-connection HSPI`` uses the HSPI peripheral instead of the SPI peripheral for SPI flash communications, via the following HSPI pins:
* CLK = GPIO 14
* Q = GPIO 12
* D = GPIO 13
* HD = GPIO 4
* CS = GPIO 15
During normal booting, this configuration is selected if all SPI pin efuses are unset and GPIO1 (U0TXD) is pulled low on reset.
Custom SPI Pin Configuration
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``--spi-connection <CLK>,<Q>,<D>,<HD>,<CS>`` allows a custom list of pins to be configured for the SPI flash connection. This can be used to emulate the flash configuration equivalent to a particular set of SPI pin efuses being burned. The values supplied are GPIO numbers.
For example, ``--spi-connection 6,17,8,11,16`` sets an identical configuration to the factory efuse configuration for ESP32s with embedded flash.
When setting a custom pin configuration, the SPI peripheral (not HSPI) will be used unless the ``CLK`` pin value is set to 14 (HSPI CLK), in which case the HSPI peripheral will be used.
Specifying Arguments via File
-----------------------------
Anywhere on the esptool command line, you can specify a file name as ``@filename.txt`` to read one or more arguments from text file ``filename.txt``. Arguments can be separated by newlines or spaces, quotes can be used to enclose arguments that span multiple words. Arguments read from the text file are expanded exactly as if they had appeared in that order on the esptool command line.
An example of this is available in the :ref:`merge_bin <merge-bin>` command description.

View File

@@ -0,0 +1,206 @@
.. _commands:
Basic Commands
==============
Write Binary Data to Flash: write_flash
----------------------------------------
Binary data can be written to the ESP's flash chip via the serial ``write_flash`` command:
::
esptool.py --port COM4 write_flash 0x1000 my_app-0x01000.bin
Multiple flash addresses and file names can be given on the same command line:
::
esptool.py --port COM4 write_flash 0x00000 my_app.elf-0x00000.bin 0x40000 my_app.elf-0x40000.bin
The ``--chip`` argument is optional when writing to flash, esptool will detect the type of chip when it connects to the serial port.
The ``--port`` argument is documented under :ref:`serial-port`.
The next arguments to ``write_flash`` are one or more pairs of offset (address) and file name. When generating ESP8266 "version 1" images, the file names created by ``elf2image`` include the flash offsets as part of the file name.
For other types of images, consult your SDK documentation to determine the files to flash at which offsets.
Numeric values passed to write_flash (and other commands) can be specified either in hex (ie 0x1000), or in decimal (ie 4096).
See the :ref:`troubleshooting` section if the ``write_flash`` command is failing, or the flashed module fails to boot.
Setting Flash Mode and Size
^^^^^^^^^^^^^^^^^^^^^^^^^^^
You may also need to specify arguments for :ref:`flash mode and flash size <flash-modes>`, if you wish to override the defaults. For example:
::
esptool.py --port /dev/ttyUSB0 write_flash --flash_mode qio --flash_size 32m 0x0 bootloader.bin 0x1000 my_app.bin
Since esptool v2.0, these options are not often needed as the default is to keep the flash mode and size from the ``.bin`` image file. See the :ref:`flash-modes` section for more details.
Compression
^^^^^^^^^^^
By default, the serial transfer data is compressed for better performance. The ``-u/--no-compress`` option disables this behaviour.
Erasing Flash Before Write
^^^^^^^^^^^^^^^^^^^^^^^^^^
To successfully write data into flash, all 4096-byte memory sectors (the smallest erasable unit) affected by the operation have to be erased first. As a result, when the flashing offset address or the data are not 4096-byte aligned, more memory is erased than actually needed.
Esptool will display information about which flash memory sectors will be erased.
Use the ``-e/--erase-all`` option to erase all flash sectors (not just the write areas) before programming.
Read Flash Contents: read_flash
--------------------------------
The read_flash command allows reading back the contents of flash. The arguments to the command are an address, a size, and a filename to dump the output to. For example, to read a full 2MB of attached flash:
::
esptool.py -p PORT -b 460800 read_flash 0 0x200000 flash_contents.bin
.. note::
If ``write_flash`` updated the boot image's :ref:`flash mode and flash size <flash-modes>` during flashing then these bytes may be different when read back.
Erase Flash: erase_flash & erase_region
---------------------------------------
To erase the entire flash chip (all data replaced with 0xFF bytes):
::
esptool.py erase_flash
To erase a region of the flash, starting at address 0x20000 with length 0x4000 bytes (16KB):
::
esptool.py erase_region 0x20000 0x4000
The address and length must both be multiples of the SPI flash erase sector size. This is 0x1000 (4096) bytes for supported flash chips.
Read Built-in MAC Address: read_mac
------------------------------------
::
esptool.py read_mac
.. _read-spi-flash-id:
Read SPI Flash ID: flash_id
---------------------------
::
esptool.py flash_id
Example output:
::
Manufacturer: e0
Device: 4016
Detected flash size: 4MB
Refer to `flashrom source code <https://review.coreboot.org/plugins/gitiles/flashrom/+/refs/heads/master/flashchips.h>`__ for flash chip manufacturer name and part number.
Convert ELF to Binary: elf2image
--------------------------------
The ``elf2image`` command converts an ELF file (from compiler/linker output) into the binary executable images which can be flashed and then booted into:
::
esptool.py --chip esp8266 elf2image my_app.elf
This command does not require a serial connection.
``elf2image`` also accepts the `Flash Modes <#flash-modes>`__ arguments ``--flash_freq`` and ``--flash_mode``, which can be used to set the default values in the image header. This is important when generating any image which will be booted directly by the chip.
These values can also be overwritten via the ``write_flash`` command, see the `write_flash command <#write-binary-data-to-flash-write-flash>`__ for details.
By default, ``elf2image`` uses the sections in the ELF file to generate each segment in the binary executable. To use segments (PHDRs) instead, pass the ``--use_segments`` option.
elf2image for ESP8266
^^^^^^^^^^^^^^^^^^^^^
The default command output is two binary files: ``my_app.elf-0x00000.bin`` and ``my_app.elf-0x40000.bin``. You can alter the firmware file name prefix using the ``--output/-o`` option.
``elf2image`` can also produce a "version 2" image file suitable for use with a software bootloader stub such as `rboot <https://github.com/raburton/rboot>`__ or the Espressif bootloader program. You can't flash a "version 2" image without also flashing a suitable bootloader.
::
esptool.py --chip esp8266 elf2image --version=2 -o my_app-ota.bin my_app.elf
elf2image for ESP32
^^^^^^^^^^^^^^^^^^^
For ESP32, elf2image produces a single output binary "image file". By default this has the same name as the .elf file, with a .bin extension. For example:
::
esptool.py --chip esp32 elf2image my_esp32_app.elf
In the above example, the output image file would be called ``my_esp32_app.bin``.
Output .bin Image Details: image_info
-------------------------------------
The ``image_info`` command outputs some information (load addresses, sizes, etc) about a ``.bin`` file created by ``elf2image``.
::
esptool.py --chip esp32 image_info my_esp32_app.bin
Note that ``--chip esp32`` is required when reading ESP32 images. Otherwise the default is ``--chip esp8266`` and the image will be interpreted as an invalid ESP8266 image.
.. _merge-bin:
Merge Binaries for Flashing: merge_bin
--------------------------------------
The ``merge_bin`` command will merge multiple binary files (of any kind) into a single file that can be flashed to a device later. Any gaps between the input files are padded with 0xFF bytes (same as unwritten flash contents).
For example:
::
esptool.py --chip esp32 merge_bin -o merged-flash.bin --flash_mode dio --flash_size 4MB 0x1000 bootloader.bin 0x8000 partition-table.bin 0x10000 app.bin
Will create a file ``merged-flash.bin`` with the contents of the other 3 files. This file can be later be written to flash with ``esptool.py write_flash 0x0 merged-flash.bin``.
.. note:
Because gaps between the input files are padded with 0xFF bytes, when the merged binary is written then any flash sectors between the individual files will be erased. To avoid this, write the files individually.
**Options:**
* The ``merge_bin`` command supports the same ``--flash_mode``, ``--flash_size`` and ``--flash_freq`` options as the ``write_flash`` command to override the bootloader flash header (see above for details).
These options are applied to the output file contents in the same way as when writing to flash. Make sure to pass the ``--chip`` parameter if using these options, as the supported values and the bootloader offset both depend on the chip.
* The ``--target-offset 0xNNN`` option will create a merged binary that should be flashed at the specified offset, instead of at offset 0x0.
* The ``--fill-flash-size SIZE`` option will pad the merged binary with 0xFF bytes to the full flash specified size, for example ``--fill-flash-size 4MB`` will create a 4MB binary file.
* It is possible to append options from a text file with ``@filename``. As an example, this can be conveniently used with the ESP-IDF build system, which produces a ``flash_args`` file in the build directory of a project:
.. code:: sh
cd build # The build directory of an ESP-IDF project
esptool.py --chip esp32 merge_bin -o merged-flash.bin @flash_args
Advanced Commands
-----------------
The following commands are less commonly used, or only of interest to advanced users. They are documented in the :ref:`advanced-commands` section:
* :ref:`verify-flash`
* :ref:`dump-mem`
* :ref:`load-ram`
* :ref:`read-mem-write-mem`
* :ref:`read-flash-status`
* :ref:`write-flash-status`
* :ref:`chip-id`
* :ref:`make-image`
* :ref:`run`

View File

@@ -0,0 +1,38 @@
.. _options:
Basic Options
=============
These are the basic/fundamental esptool options needed to define the communication with an ESP target. For advanced configuration options, see the :ref:`advanced-options` page.
.. _serial-port:
Serial Port
-----------
* The serial port is selected using the ``-p`` option, like ``-p /dev/ttyUSB0`` (Linux and macOS) or ``-p COM1`` (Windows).
* A default serial port can be specified by setting the ``ESPTOOL_PORT`` environment variable.
* If no ``-p`` option or ``ESPTOOL_PORT`` value is specified, ``esptool.py`` will enumerate all connected serial ports and try each one until it finds an Espressif device connected.
.. note::
Windows and macOS may require drivers to be installed for a particular USB/serial adapter, before a serial port is available. Consult the documentation for your particular device.
On macOS, you can also consult `System Information <https://support.apple.com/en-us/HT203001>`__'s list of USB devices to identify the manufacturer or device ID when the adapter is plugged in.
On Windows, you can use `Windows Update or Device Manager <https://support.microsoft.com/en-us/help/15048/windows-7-update-driver-hardware-not-working-properly>`__ to find a driver.
If using Cygwin or WSL on Windows, you have to convert the Windows-style name into a Unix-style path (``COM1`` -> ``/dev/ttyS0``, and so on). (This is not necessary if using ESP-IDF for ESP32 with the supplied Windows MSYS2 environment,
this environment uses a native Windows Python which accepts COM ports as-is.)
In Linux, the current user may not have access to serial ports and a "Permission Denied" error will appear. On most Linux distributions, the solution is to add the user to the ``dialout`` group with a command like ``sudo usermod -a -G dialout <USERNAME>``.
Check your Linux distribution's documentation for more information.
Baud Rate
---------
The default esptool baud rate is 115200bps. Different rates may be set using ``-b 921600`` (or another baud rate of your choice). A default baud rate can also be specified using the ``ESPTOOL_BAUD`` environment variable. This can speed up ``write_flash`` and ``read_flash`` operations.
The baud rate is limited to 115200 when esptool establishes the initial connection, higher speeds are only used for data transfers.
Most hardware configurations will work with ``-b 230400``, some with ``-b 460800``, ``-b 921600`` and/or ``-b 1500000`` or higher.
If you have connectivity problems then you can also set baud rates below 115200. You can also choose 74880, which is the usual baud rate used by the ESP8266 to output :ref:`boot-log-esp8266` information.

View File

@@ -0,0 +1,26 @@
.. _entering-the-bootloader:
Entering the Bootloader
=======================
Espressif chips have to be reset in a certain way in order to launch the serial bootloader.
On some development boards (including NodeMCU, WeMOS, HUZZAH Feather, Core Board, ESP32-WROVER-KIT), esptool can automatically trigger a reset into the serial bootloader - in which case you don't need to read this section.
For everyone else, three things must happen to enter the serial bootloader - a reset, required pins set correctly, and GPIO0 pulled low:
Boot Mode
---------
Espressif chips choose the boot mode each time they reset. A reset event can happen in one of several ways:
* Power applied to chip.
* The nRESET pin was low and is pulled high (on ESP8266 only).
* The CH_PD/EN pin ("enable") pin was low and is pulled high.
On ESP8266, both the nRESET and CH_PD pins must be pulled high for the chip to start operating.
For more details on selecting the boot mode, see the following Advanced Topics pages:
* :ref:`ESP8266 Boot Mode Selection <boot-mode-esp8266>`
* :ref:`ESP32 Boot Mode Selection <boot-mode-esp32>`

View File

@@ -0,0 +1,95 @@
.. _flash-modes:
Flash Modes
===========
``write_flash`` and some other commands accept command line arguments to set bootloader flash mode, flash size and flash clock frequency. The chip needs correct mode, frequency and size settings in order to run correctly - although there is some flexibility.
A header at the beginning of a bootable image contains these values.
To override these values, the options ``--flash_mode``, ``--flash_size`` and/or ``--flash_freq`` must appear after ``write_flash`` on the command line, for example:
::
esptool.py --port /dev/ttyUSB1 write_flash --flash_mode dio --flash_size 4MB 0x0 bootloader.bin
These options are only consulted when flashing a bootable image to an ESP8266 at offset 0x0, or an ESP32 at offset 0x1000. These are addresses used by the ROM bootloader to load from flash. When flashing at all other offsets, these arguments are not used.
Flash Mode (--flash\_mode, -fm)
-------------------------------
These set Quad Flash I/O or Dual Flash I/O modes. Valid values are ``keep``, ``qio``, ``qout``, ``dio``, ``dout``. The default is ``keep``, which keeps whatever value is already in the image file. This parameter can also be specified using the environment variable ``ESPTOOL_FM``.
Most boards use ``qio`` mode. Some ESP8266 modules, including the ESP-12E modules on some (not all) NodeMCU boards, are dual I/O and the firmware will only boot when flashed with ``--flash_mode dio``. Most ESP32 modules are also dual I/O.
In ``qio`` mode, two additional GPIOs (9 and 10) are used for SPI flash communications. If flash mode is set to ``dio`` then these pins are available for other purposes.
For a full explanation of these modes, see the :ref:`SPI Flash Modes page <spi-flash-modes>`.
Flash Frequency (--flash\_freq, -ff)
------------------------------------
Clock frequency for SPI flash interactions. Valid values are ``keep``, ``40m``, ``26m``, ``20m``, ``80m`` (MHz). The default is ``keep``, which keeps whatever value is already in the image file. This parameter can also be specified using the environment variable ``ESPTOOL_FF``.
The flash chip connected to most chips works with 40MHz clock speeds, but you can try lower values if the device won't boot. The highest 80MHz flash clock speed will give the best performance, but may cause crashing if the flash or board design is not capable of this speed.
Flash Size (--flash\_size, -fs)
-------------------------------
Size of the SPI flash, given in megabytes. Valid values vary by chip type:
+------------------+--------------------------------------------------------------------------------------------------------------------+
| Chip | flash\_size values |
+==================+====================================================================================================================+
| ESP32 and later | ``keep``, ``detect``, ``1MB``, ``2MB``, ``4MB``, ``8MB``, ``16MB`` |
+------------------+--------------------------------------------------------------------------------------------------------------------+
| ESP8266 | ``keep``, ``detect``, ``256KB``, ``512KB``, ``1MB``, ``2MB``, ``4MB``, ``2MB-c1``, ``4MB-c1``, ``8MB``, ``16MB`` |
+------------------+--------------------------------------------------------------------------------------------------------------------+
For ESP8266, some `additional sizes & layouts for OTA "firmware slots" are available <#esp8266-and-flash-size>`_.
The default ``--flash_size`` parameter is ``keep``. This means that if no ``--flash_size`` argument is passed when flashing a bootloader, the value in the bootloader .bin file header is kept instead of detecting the actual flash size and updating the header.
To enable automatic flash size detection based on SPI flash ID, add the argument ``esptool.py [...] write_flash [...] -fs detect``. If detection fails, a warning is printed and a default value of of ``4MB`` (4 megabytes) is used.
If flash size is not successfully detected, you can find the flash size by using the ``flash_id`` command and then looking up the ID from the output (see :ref:`Read SPI flash id <read-spi-flash-id>`).
Alternatively, read off the silkscreen labelling of the flash chip and search for its datasheet.
The default ``flash_size`` parameter can also be overridden using the environment variable ``ESPTOOL_FS``.
ESP8266 and Flash Size
^^^^^^^^^^^^^^^^^^^^^^
The ESP8266 SDK stores WiFi configuration at the "end" of flash, and it finds the end using this size. However there is no downside to specifying a smaller flash size than you really have, as long as you don't need to write an image larger than this size.
ESP-12, ESP-12E and ESP-12F modules (and boards that use them such as NodeMCU, HUZZAH, etc.) usually have at least 4 megabyte / ``4MB`` (sometimes labelled 32 megabit) flash.
If using OTA, some additional sizes & layouts for OTA "firmware slots" are available. If not using OTA updates then you can ignore these extra sizes:
+-------------------+-----------------------+-----------------+-----------------+
| flash_size arg | Number of OTA slots | OTA Slot Size | Non-OTA Space |
+===================+=======================+=================+=================+
| 256KB | 1 (no OTA) | 256KB | N/A |
+-------------------+-----------------------+-----------------+-----------------+
| 512KB | 1 (no OTA) | 512KB | N/A |
+-------------------+-----------------------+-----------------+-----------------+
| 1MB | 2 | 512KB | 0KB |
+-------------------+-----------------------+-----------------+-----------------+
| 2MB | 2 | 512KB | 1024KB |
+-------------------+-----------------------+-----------------+-----------------+
| 4MB | 2 | 512KB | 3072KB |
+-------------------+-----------------------+-----------------+-----------------+
| 2MB-c1 | 2 | 1024KB | 0KB |
+-------------------+-----------------------+-----------------+-----------------+
| 4MB-c1 | 2 | 1024KB | 2048KB |
+-------------------+-----------------------+-----------------+-----------------+
| 8MB [^] | 2 | 1024KB | 6144KB |
+-------------------+-----------------------+-----------------+-----------------+
| 16MB [^] | 2 | 1024KB | 14336KB |
+-------------------+-----------------------+-----------------+-----------------+
- [^] Support for 8MB & 16MB flash size is not present in all ESP8266 SDKs. If your SDK doesn't support these flash sizes, use ``--flash_size 4MB``.
ESP32 and Flash Size
^^^^^^^^^^^^^^^^^^^^
The ESP-IDF flashes a partition table to the flash at offset 0x8000. All of the partitions in this table must fit inside the configured flash size, otherwise the ESP32 will not work correctly.

24
docs/en/esptool/index.rst Normal file
View File

@@ -0,0 +1,24 @@
esptool.py
==========
Use ``esptool.py -h`` to see a summary of all available commands and command line options.
To see all options for a particular command, append ``-h`` to the command name. ie ``esptool.py write_flash -h``.
.. toctree::
:maxdepth: 1
Basic Options <basic-options>
Basic Commands <basic-commands>
Advanced Options <advanced-options>
Advanced Commands <advanced-commands>
Flash Modes <flash-modes>
Entering the Bootloader <entering-bootloader>
Serial Connection <serial-connection>
Remote Serial Ports <remote-serial-ports>
Scripting <scripting>
Instructions for other tools bundled with esptool:
* :ref:`espefuse`
* :ref:`espsecure`

View File

@@ -0,0 +1,62 @@
Remote Serial Ports
===================
It is possible to connect to any networked remote serial port that supports `RFC2217 <http://www.ietf.org/rfc/rfc2217.txt>`__ (Telnet) protocol. To do this, specify the serial port to esptool as ``rfc2217://<host>:<port>``. For example:
::
esptool.py --port rfc2217://192.168.1.77:4000 flash_id
Custom baud rates and DTR/RTS automatic resetting are supported over the RFC2217 protocol, the same as for a local serial port.
Pyserial Example Servers
------------------------
PySerial (which is a dependency of esptool) includes two RFC2217 example programs - `a single-port example <http://pyserial.readthedocs.io/en/latest/examples.html#single-port-tcp-ip-serial-bridge-rfc-2217>`__ and a `multi-port example <http://pyserial.readthedocs.io/en/latest/examples.html#multi-port-tcp-ip-serial-bridge-rfc-2217>`__.
These example servers can run on any OS that supports pyserial, and are the simplest way to connect to an Espressif SoC over the network.
There is an issue with `automatic resetting due to network latency <https://github.com/espressif/esptool/issues/383>`__. In order to work around this issue, a modified version of the single-port server example called ``esp_rfc2217_server.py`` is provided with esptool.
On server:
::
esp_rfc2217_server.py -p 4000 /dev/ttyUSB1
On client:
::
esptool.py --port rfc2217://ADDRESS_OF_SERVER:4000?ign_set_control flash_id
Raw Sockets
-----------
For servers or hardware network/serial adapters which don't support the full RFC2217, it is also possible to specify ``--port socket://<host>:<port>`` syntax for a simple "raw TCP socket" protocol.
These raw sockets don't support setting the baud rate or automatic resetting into the bootloader. If using this mode, don't pass the ``--baud`` option to esptool. You need to set the baud rate manually on the server, and manually reset the chip into the bootloader mode (or use some other signalling/control method to tell the server to do so).
Here's a very basic example using the common Linux/OSX command line "netcat" and "stty" commands:
On server:
::
stty -F /dev/ttyUSB1 230400 # set baud rate
nc -p 4000 -lk < /dev/ttyUSB1 > /dev/ttyUSB1
On client:
::
esptool.py -p socket://localhost:4000 flash_id
.. note::
Using RFC2217 is strongly recommended where possible.
More Details
------------
All of the remote serial port support comes via pyserial. Read more `here <http://pyserial.readthedocs.io/en/latest/url_handlers.html>`__. (Please keep in mind that the link points to documentation for the most recent pyserial version. You may have an older version.)

View File

@@ -0,0 +1,12 @@
Embedding into custom scripts
=============================
``esptool.py``, ``espefuse.py``, and ``espsecure.py`` can easily be integrated into Python applications or called from other Python scripts.
While it currently does have a poor Python API, something which `#208 <https://github.com/espressif/esptool/issues/208>`_ will address, it allows for passing CLI arguments to ``esptool.main()``. This workaround makes integration very straightforward as you can pass exactly the same arguments as you would on the CLI:
.. code-block:: python
command = ['--baud', '460800', 'read_flash', '0', '0x200000', 'flash_contents.bin']
print('Using command %s' % ' '.join(command))
esptool.main(command)

View File

@@ -0,0 +1,20 @@
Serial Connection
=================
The ROM serial bootloader of Espressif chips uses a 3.3V UART serial connection. Many development boards make the serial connections for you onboard.
However, if you are wiring the chip yourself to a USB/Serial adapter or similar then the following connections must be made:
+---------------------+-------------------+
| ESP Chip Pin | Serial Port Pin |
+=====================+===================+
| TX (aka GPIO1) | RX (receive) |
+---------------------+-------------------+
| RX (aka GPIO3) | TX (transmit) |
+---------------------+-------------------+
| Ground | Ground |
+---------------------+-------------------+
Note that TX (transmit) on the ESP chip is connected to RX (receive) on the serial port connection, and vice versa.
Do not connect the chip to 5V TTL serial adapters, and especially not to "standard" RS-232 adapters! 3.3V serial only!

View File

@@ -1,20 +1,51 @@
Esptool Documentation
=========================
=====================
This is the documentation for esptool - a Python-based, open source, platform independent, utility to communicate with the ROM bootloader in Espressif `ESP8266, ESP32, ESP32-S and ESP32-C Series SoCs <https://www.espressif.com/en/products/hardware/socs>`_.
This is the documentation for esptool - a Python-based, open source, platform independent utility to communicate with the ROM bootloader in `Espressif SoCs <https://www.espressif.com/en/products/hardware/socs>`_.
esptool, espefuse and espsecure are a complete toolset for working with Espressif chips. They can do a number of things, for example:
* Read, write, erase, and verify binary data stored in flash.
* Read chip features and other related data such as MAC address or flash chip ID.
* Read and write the one-time-programmable efuses.
* Prepare binary executable images ready for flashing.
* Analyze, assemble, and merge binary images.
Quick Start
-----------
Getting started is easy:
1) Install esptool:
::
$ pip install esptool
For detailed instructions, see :ref:`installation`.
.. warning::
2) Connect an Espressif chip to your computer.
Documentation is currently under construction.
3) Run esptool commands:
::
$ esptool.py -p PORT flash_id
Replace ``PORT`` with the name of used serial port. If connection fails, see :ref:`troubleshooting`.
More Information
----------------
.. toctree::
:hidden:
:maxdepth: 1
Installation <installation>
Usage <usage>
Esptool <esptool/index>
Espefuse <espefuse/index>
Espsecure <espsecure/index>
Advanced Topics <advanced-topics/index>
Troubleshooting <troubleshooting>
Contribute <contributing>
About <about>

View File

@@ -1,58 +1,22 @@
Installation / dependencies
===========================
.. _installation:
Easy Installation
-----------------
Installation and Dependencies
=============================
You will need `either Python 2.7 or Python 3.4 or newer`_ installed on
your system.
You will need `either Python 2.7 or Python 3.4 or newer <https://www.python.org/downloads/>`_ installed on your system.
The latest stable esptool.py release can be installed from `pypi`_ via
pip:
The latest stable esptool release can be installed from `PyPI <https://pypi.org/project/esptool/>`_ via pip:
::
$ pip install esptool
With some Python installations this may not work and youll receive an
error, try ``python -m pip install esptool`` or
``pip2 install esptool``, or consult your `Python installation manual`_
for information about how to access pip.
With some Python installations this may not work and youll receive an error, try ``python -m pip install esptool`` or ``pip3 install esptool``, or consult your `Python installation manual <https://pip.pypa.io/en/stable/installation/>`_ for information about how to access pip.
`Setuptools`_ is also a requirement which is not available on all
systems by default. You can install it by a package manager of your
operating system, or by ``pip install setuptools``.
`Setuptools <https://setuptools.pypa.io/en/latest/userguide/quickstart.html>`_ is also a requirement which is not available on all systems by default. You can install it by a package manager of your operating system, or by ``pip install setuptools``.
After installing, you will have ``esptool.py`` installed into the
default Python executables directory and you should be able to run it
with the command ``esptool.py`` or ``python -m esptool``. Please note
that probably only ``python -m esptool`` will work for Pythons installed
from Windows Store.
After installing, you will have ``esptool.py`` installed into the default Python executables directory and you should be able to run it with the command ``esptool.py`` or ``python -m esptool``. Please note that probably only ``python -m esptool`` will work for Pythons installed from Windows Store.
Development Mode Installation
-----------------------------
.. note::
Development mode allows you to run the latest development version from
this repository.
.. code:: sh
$ git clone https://github.com/espressif/esptool.git
$ cd esptool
$ pip install --user -e .
This will install esptools dependencies and create some executable
script wrappers in the users ``bin`` directory. The wrappers will run
the scripts found in the git working directory directly, so any time the
working directory contents change it will pick up the new versions.
Its also possible to run the scripts directly from the working
directory with this Development Mode installation.
(Note: if you actually plan to do development work with esptool itself,
see the CONTRIBUTING.md file.)
.. _either Python 2.7 or Python 3.4 or newer: https://www.python.org/downloads/
.. _pypi: http://pypi.python.org/pypi/esptool
.. _Python installation manual: https://pip.pypa.io/en/stable/installing/
.. _Setuptools: https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html
If you actually plan to do development work with esptool itself, see :ref:`development-setup` for more information.

View File

@@ -1,142 +1,101 @@
.. _troubleshooting:
Troubleshooting
===============
Flashing problems can be fiddly to troubleshoot. Try the suggestions
here if you're having problems:
Flashing problems can be fiddly to troubleshoot. Try the suggestions here if you're having problems:
Bootloader won't respond
Bootloader Won't Respond
------------------------
If you see errors like "Failed to connect" then your chip is probably
not entering the bootloader properly:
If you see errors like "Failed to connect" then your chip is probably not entering the bootloader properly:
- Check you are passing the correct serial port on the command line.
- Check you have permissions to access the serial port, and other
software (such as modem-manager on Linux) is not trying to interact
with it. A common pitfall is leaving a serial terminal accessing this
port open in another window and forgetting about it.
- Check the chip is receiving 3.3V from a stable power source (see
`Insufficient Power`_ for more details.)
- Check that all pins are connected as described in `Entering the
bootloader`_. Check the voltages at each pin with a multimeter,
"high" pins should be close to 3.3V and "low" pins should be close to
0V.
- If you have connected other devices to GPIO pins mentioned above
section, try removing them and see if esptool.py starts working.
- Try using a slower baud rate (``-b 9600`` is a very slow value that
you can use to verify it's not a baud rate problem.)
* Check you are passing the correct serial port on the command line.
* Check you have permissions to access the serial port, and other software (such as modem-manager on Linux) is not trying to interact with it. A common pitfall is leaving a serial terminal accessing this port open in another window and forgetting about it.
* Check the chip is receiving 3.3V from a stable power source (see `Insufficient Power`_ for more details.)
* Check that all pins are connected as described in :ref:`entering-the-bootloader`. Check the voltages at each pin with a multimeter, "high" pins should be close to 3.3V and "low" pins should be close to 0V.
* If you have connected other devices to GPIO pins, try removing them and see if esptool starts working.
* Try using a slower baud rate (``-b 9600`` is a very slow value that you can use to verify it's not a baud rate problem).
write_flash operation fails part way through
--------------------------------------------
Writing to Flash Fails Part Way Through
---------------------------------------
If flashing fails with random errors part way through, retry with a
lower baud rate.
If flashing fails with random errors part way through, retry with a lower baud rate.
Power stability problems may also cause this (see `Insufficient
Power`_.)
Power stability problems may also cause this (see `Insufficient Power`_.)
write_flash succeeds but program doesn't run
--------------------------------------------
Writing to Flash Succeeds but Program Doesn't Run
-------------------------------------------------
If esptool.py can flash your module with ``write_flash`` but your
program doesn't run, try the following:
If esptool can flash your module with ``write_flash`` but your program doesn't run, check the following:
Wrong Flash Mode
^^^^^^^^^^^^^^^^
Some devices only support the ``dio`` flash mode. Writing to flash with
``qio`` mode will succeed but the chip can't read the flash back to run
- so nothing happens on boot. Try passing the ``-fm dio`` option to
write_flash.
Some devices only support the ``dio`` flash mode. Writing to flash with ``qio`` mode will succeed but the chip can't read the flash back to run - so nothing happens on boot. Try passing the ``-fm dio`` option to ``write_flash``.
See the `SPI Flash Modes`_ wiki page for a full description of the flash
modes and how to determine which ones are supported on your device.
See the :ref:`spi-flash-modes` page for a full description of the flash modes and how to determine which ones are supported on your device.
Insufficient Power
^^^^^^^^^^^^^^^^^^
The 3.3V power supply for the ESP8266 and ESP32 has to supply large
amounts of current (up to 70mA continuous, 200-300mA peak, slightly
higher for ESP32). You also need sufficient capacitance on the power
circuit to meet large spikes of power demand.
The 3.3V power supply for the ESP chip has to supply large amounts of current (up to 70mA continuous, 200-300mA peak, might be slightly higher). You also need sufficient capacitance on the power circuit to meet large spikes of power demand.
Insufficient Capacitance
''''''''''''''''''''''''
If you're using a pre-made development board or module then the built-in
power regulator & capacitors are usually good enough, provided the input
power supply is adequate.
If you're using a pre-made development board or module then the built-in power regulator & capacitors are usually good enough, provided the input power supply is adequate.
*This is not true for some very simple pin breakout modules -*\ `similar
to this`_\ *. These breakouts do not integrate enough capacitance to
work reliably without additional components.*. Surface mount OEM modules
like ESP-WROOM02 and ESP-WROOM32 require an external bulk capacitor on
the PCB to be reliable, consult the module datasheet.
.. note::
This is not true for some very simple pin breakout modules - `similar to this <https://user-images.githubusercontent.com/205573/30140831-9da417a6-93ba-11e7-95c3-f422744967de.jpg>`_. These breakouts do not integrate enough capacitance to work reliably without additional components.
Surface mount OEM modules like ESP-WROOM02 and ESP-WROOM32 require an external bulk capacitor on the PCB to be reliable, consult the module datasheet.
Power Supply Rating
'''''''''''''''''''
It is possible to have a power supply that supplies enough current for
the serial bootloader stage with esptool.py, but not enough for normal
firmware operation. You may see the 3.3V VCC voltage droop down if you
measure it with a multimeter, but you can have problems even if this
isn't happening.
It is possible to have a power supply that supplies enough current for the serial bootloader stage with esptool, but not enough for normal firmware operation. You may see the 3.3V VCC voltage droop down if you measure it with a multimeter, but you can have problems even if this isn't happening.
Try swapping in a 3.3V supply with a higher current rating, add
capacitors to the power line, and/or shorten any 3.3V power wires.
Try swapping in a 3.3V supply with a higher current rating, add capacitors to the power line, and/or shorten any 3.3V power wires.
The 3.3V output from FTDI FT232R chips/adapters or Arduino boards *do
not* supply sufficient current to power an ESP8266 or ESP32 (it may seem
to work sometimes, but it won't work reliably). Other USB TTL/serial
adapters may also be marginal.
The 3.3V output from FTDI FT232R chips/adapters or Arduino boards *do not* supply sufficient current to power an ESP chip (it may seem to work sometimes, but it won't work reliably). Other USB TTL/serial adapters may also be marginal.
Missing bootloader
Missing Bootloader
^^^^^^^^^^^^^^^^^^
Recent ESP8266 SDKs and the ESP32 ESP-IDF both use a small firmware
bootloader program. The hardware bootloader in ROM loads this firmware
bootloader from flash, and then it runs the program. On ESP8266.
firmware bootloader image (with a filename like ``boot_v1.x.bin``) has
to be flashed at offset 0. If the firmware bootloader is missing then
the ESP8266 will not boot. On ESP32, the bootloader image should be
flashed by ESP-IDF at offset 0x1000.
`ESP-IDF <https://github.com/espressif/esp-idf>`_ and the `ESP8266 SDK <https://github.com/espressif/ESP8266_RTOS_SDK>`_ both use a small firmware bootloader program. The hardware bootloader in ROM loads this firmware bootloader from flash, and then it runs the program.
On ESP8266, firmware bootloader image (with a filename like ``boot_v1.x.bin``) has to be flashed at offset 0. If the firmware bootloader is missing then the ESP8266 will not boot. On ESP32 and later chips, the bootloader image should be flashed by ESP-IDF at offset 0x1000.
Refer to SDK or ESP-IDF documentation for details regarding which
binaries need to be flashed at which offsets.
Refer to ESP-IDF or ESP8266 SDK documentation for details regarding which binaries need to be flashed at which offsets.
SPI Pins which must be disconnected
SPI Pins Which Must Be Disconnected
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Compared to the ROM bootloader that esptool.py talks to, a running
firmware uses more of the chip's pins to access the SPI flash.
Compared to the ROM bootloader that esptool talks to, a running firmware uses more of the chip's pins to access the SPI flash.
If you set "Quad I/O" mode (``-fm qio``, the esptool.py default) then
GPIOs 7, 8, 9 & 10 are used for reading the SPI flash and must be
otherwise disconnected.
If you set "Quad I/O" mode (``-fm qio``, the esptool default) then GPIOs 7, 8, 9 & 10 are used for reading the SPI flash and must be otherwise disconnected.
If you set "Dual I/O" mode (``-fm dio``) then GPIOs 7 & 8 are used for
reading the SPI flash and must be otherwise disconnected.
If you set "Dual I/O" mode (``-fm dio``) then GPIOs 7 & 8 are used for reading the SPI flash and must be otherwise disconnected.
Try disconnecting anything from those pins (and/or swap to Dual I/O mode
if you were previously using Quad I/O mode but want to attach things to
GPIOs 9 & 10). Note that if GPIOs 9 & 10 are also connected to input
pins on the SPI flash chip, they may still be unsuitable for use as
general purpose I/O.
Try disconnecting anything from those pins (and/or swap to Dual I/O mode if you were previously using Quad I/O mode but want to attach things to GPIOs 9 & 10). Note that if GPIOs 9 & 10 are also connected to input pins on the SPI flash chip, they may still be unsuitable for use as general purpose I/O.
In addition to these pins, GPIOs 6 & 11 are also used to access the SPI
flash (in all modes). However flashing will usually fail completely if
these pins are connected incorrectly.
In addition to these pins, GPIOs 6 & 11 are also used to access the SPI flash (in all modes). However flashing will usually fail completely if these pins are connected incorrectly.
Early stage crash
Early Stage Crash
-----------------
Use a `serial terminal program`_ to view the boot log. (ESP8266 baud
rate is 74880bps, ESP32 is 115200bps). See if the program is crashing
during early startup or outputting an error message.
Use any of `Serial terminal programs`_ to view the boot log. (ESP8266 baud rate is 74880bps, ESP32 and later is 115200bps). See if the program is crashing during early startup or outputting an error message.
.. _serial terminal program: #serial-terminal-programs
Serial Terminal Programs
------------------------
.. _Insufficient Power: #insufficient-power
.. _Entering the bootloader: #entering-the-bootloader
.. _SPI Flash Modes: https://github.com/espressif/esptool/wiki/SPI-Flash-Modes
.. _similar to this: https://user-images.githubusercontent.com/205573/30140831-9da417a6-93ba-11e7-95c3-f422744967de.jpg
There are many serial terminal programs suitable for debugging & serial interaction. The pyserial module (which is required for esptool) includes one such command line terminal program - miniterm.py. For more details `see this page <https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.miniterm>`_ or run ``miniterm -h``.
Note that not every serial program supports the unusual ESP8266 74880bps "boot log" baud rate. Support is especially sparse on Linux. miniterm.py supports this baud rate on all platforms. ESP32 or later chips use the more common 115200bps.
Tracing Esptool Interactions
----------------------------
Running ``esptool.py --trace`` will dump all serial interactions to the standard output (this is *a lot* of output). This can be helpful when debugging issues with the serial connection, or when providing information for bug reports.
See :ref:`the related Advanced Topics page <tracing-communications>` for more information.

View File

@@ -1,561 +0,0 @@
Usage
=====
Use ``esptool.py -h`` to see a summary of all available commands and
command line options.
To see all options for a particular command, append ``-h`` to the
command name. ie ``esptool.py write_flash -h``.
Common Options
--------------
Serial Port
~~~~~~~~~~~
* The serial port is selected using the ``-p`` option, like
``-p /dev/ttyUSB0`` (Linux and macOS) or ``-p COM1`` (Windows).
* A default serial port can be specified by setting the
``ESPTOOL_PORT`` environment variable.
* If no ``-p`` option or ``ESPTOOL_PORT`` value is specified,
``esptool.py`` will enumerate all connected serial ports and try each
one until it finds an Espressif device connected (new behaviour in
v2.4.0).
Note: Windows and macOS may require drivers to be installed for a
particular USB/serial adapter, before a serial port is available.
Consult the documentation for your particular device. On macOS, you can
also consult `System
Information <https://support.apple.com/en-us/HT203001>`__'s list of USB
devices to identify the manufacturer or device ID when the adapter is
plugged in. On Windows, you can use `Windows Update or Device
Manager <https://support.microsoft.com/en-us/help/15048/windows-7-update-driver-hardware-not-working-properly>`__
to find a driver.
If using Cygwin or WSL on Windows, you have to convert the Windows-style
name into a Unix-style path (``COM1`` -> ``/dev/ttyS0``, and so on).
(This is not necessary if using ESP-IDF for ESP32 with the supplied
Windows MSYS2 environment, this environment uses a native Windows Python
which accepts COM ports as-is.)
In Linux, the current user may not have access to serial ports and a
"Permission Denied" error will appear. On most Linux distributions, the
solution is to add the user to the ``dialout`` group with a command like
``sudo usermod -a -G dialout <USERNAME>``. Check your Linux
distribution's documentation for more information.
Baud rate
~~~~~~~~~
The default esptool.py baud rate is 115200bps. Different rates may be
set using ``-b 921600`` (or another baud rate of your choice). A default
baud rate can also be specified using the ``ESPTOOL_BAUD`` environment
variable. This can speed up ``write_flash`` and ``read_flash``
operations.
The baud rate is limited to 115200 when esptool.py establishes the
initial connection, higher speeds are only used for data transfers.
Most hardware configurations will work with ``-b 230400``, some with
``-b 460800``, ``-b 921600`` and/or ``-b 1500000`` or higher.
If you have connectivity problems then you can also set baud rates below
115200. You can also choose 74880, which is the usual baud rate used by
the ESP8266 to output `boot
log <https://github.com/espressif/esptool/wiki/ESP8266-Boot-ROM-Log>`__
information.
Commands
--------
Write binary data to flash: write\_flash
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Binary data can be written to the ESP's flash chip via the serial
``write_flash`` command:
::
esptool.py --port COM4 write_flash 0x1000 my_app-0x01000.bin
Multiple flash addresses and file names can be given on the same command
line:
::
esptool.py --port COM4 write_flash 0x00000 my_app.elf-0x00000.bin 0x40000 my_app.elf-0x40000.bin
The ``--chip`` argument is optional when writing to flash, esptool will
detect the type of chip when it connects to the serial port.
The ``--port`` argument is documented under `Serial
Port <#serial-port>`__.
The next arguments to write\_flash are one or more pairs of offset
(address) and file name. When generating ESP8266 "version 1" images, the
file names created by ``elf2image`` include the flash offsets as part of
the file name. For other types of images, consult your SDK documentation
to determine the files to flash at which offsets.
Numeric values passed to write\_flash (and other commands) can be
specified either in hex (ie 0x1000), or in decimal (ie 4096).
See the `Troubleshooting <#troubleshooting>`__ section if the
write\_flash command is failing, or the flashed module fails to boot.
Setting flash mode and size
^^^^^^^^^^^^^^^^^^^^^^^^^^^
You may also need to specify arguments for `flash mode and flash
size <#flash-modes>`__, if you wish to override the defaults. For
example:
::
esptool.py --port /dev/ttyUSB0 write_flash --flash_mode qio --flash_size 32m 0x0 bootloader.bin 0x1000 my_app.bin
Since esptool v2.0, these options are not often needed as the default is
to keep the flash mode and size from the ``.bin`` image file. See the
`Flash Modes <#flash-modes>`__ section for more details.
Compression
^^^^^^^^^^^
By default, the serial transfer data is compressed for better
performance. The ``-u/--no-compress`` option disables this behaviour.
Erasing flash before write
^^^^^^^^^^^^^^^^^^^^^^^^^^
To successfully write data into flash, all 4096-byte memory sectors (the
smallest erasable unit) affected by the operation have to be erased
first. As a result, when the flashing offset address or the data are not
4096-byte aligned, more memory is erased than actually needed. Esptool
will display information about which flash memory sectors will be
erased.
Use the ``-e/--erase-all`` option to erase all flash sectors (not just
write areas) before programming.
Read Flash Contents: read\_flash
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The read\_flash command allows reading back the contents of flash. The
arguments to the command are an address, a size, and a filename to dump
the output to. For example, to read a full 2MB of attached flash:
::
esptool.py -p PORT -b 460800 read_flash 0 0x200000 flash_contents.bin
(Note that if ``write_flash`` updated the boot image's `flash mode and
flash size <#flash-modes>`__ during flashing then these bytes may be
different when read back.)
Erase Flash: erase\_flash & erase region
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To erase the entire flash chip (all data replaced with 0xFF bytes):
::
esptool.py erase_flash
To erase a region of the flash, starting at address 0x20000 with length
0x4000 bytes (16KB):
::
esptool.py erase_region 0x20000 0x4000
The address and length must both be multiples of the SPI flash erase
sector size. This is 0x1000 (4096) bytes for supported flash chips.
Read built-in MAC address: read\_mac
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
esptool.py read_mac
Read SPI flash id: flash\_id
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
esptool.py flash_id
Example output:
::
Manufacturer: e0
Device: 4016
Detected flash size: 4MB
Refer to `flashrom source
code <https://review.coreboot.org/plugins/gitiles/flashrom/+/refs/heads/master/flashchips.h>`__
for flash chip manufacturer name and part number.
Convert ELF to Binary: elf2image
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``elf2image`` command converts an ELF file (from compiler/linker
output) into the binary executable images which can be flashed and then
booted into:
::
esptool.py --chip esp8266 elf2image my_app.elf
This command does not require a serial connection.
``elf2image`` also accepts the `Flash Modes <#flash-modes>`__ arguments
``--flash_freq`` and ``--flash_mode``, which can be used to set the
default values in the image header. This is important when generating
any image which will be booted directly by the chip. These values can
also be overwritten via the ``write_flash`` command, see the
`write\_flash command <#write-binary-data-to-flash-write_flash>`__ for
details.
By default, ``elf2image`` uses the sections in the ELF file to generate
each segment in the binary executable. To use segments (PHDRs) instead,
pass the ``--use_segments`` option.
elf2image for ESP8266
^^^^^^^^^^^^^^^^^^^^^
The default command output is two binary files:
``my_app.elf-0x00000.bin`` and ``my_app.elf-0x40000.bin``. You can alter
the firmware file name prefix using the ``--output/-o`` option.
``elf2image`` can also produce a "version 2" image file suitable for use
with a software bootloader stub such as
`rboot <https://github.com/raburton/rboot>`__ or the Espressif
bootloader program. You can't flash a "version 2" image without also
flashing a suitable bootloader.
::
esptool.py --chip esp8266 elf2image --version=2 -o my_app-ota.bin my_app.elf
elf2image for ESP32
^^^^^^^^^^^^^^^^^^^
For ESP32, elf2image produces a single output binary "image file". By
default this has the same name as the .elf file, with a .bin extension.
ie:
::
esptool.py --chip esp32 elf2image my_esp32_app.elf
In the above example, the output image file would be called
``my_esp32_app.bin``.
Output .bin image details: image\_info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``image_info`` command outputs some information (load addresses,
sizes, etc) about a ``.bin`` file created by ``elf2image``.
::
esptool.py --chip esp32 image_info my_esp32_app.bin
Note that ``--chip esp32`` is required when reading ESP32 images.
Otherwise the default is ``--chip esp8266`` and the image will be
interpreted as an invalid ESP8266 image.
Advanced Commands
~~~~~~~~~~~~~~~~~
The following commands are less commonly used, or only of interest to
advanced users. They are documented on the wiki:
* `verify\_flash <https://github.com/espressif/esptool/wiki/Advanced-Commands#verify_flash>`__
* `dump\_mem <https://github.com/espressif/esptool/wiki/Advanced-Commands#dump_mem>`__
* `load\_ram <https://github.com/espressif/esptool/wiki/Advanced-Commands#load_ram>`__
* `read\_mem &
write\_mem <https://github.com/espressif/esptool/wiki/Advanced-Commands#read_mem--write_mem>`__
* `read\_flash\_status <https://github.com/espressif/esptool/wiki/Advanced-Commands#read_flash_status>`__
* `write\_flash\_status <https://github.com/espressif/esptool/wiki/Advanced-Commands#write_flash_status>`__
* `chip\_id <https://github.com/espressif/esptool/wiki/Advanced-Commands#chip_id>`__
* `make\_image <https://github.com/espressif/esptool/wiki/Advanced-Commands#make_image>`__
* `run <https://github.com/espressif/esptool/wiki/Advanced-Commands#run>`__
Additional ESP32 Tools
----------------------
The following tools for ESP32, bundled with esptool.py, are documented
on the wiki:
* `espefuse.py - for reading/writing ESP32 efuse
region <https://github.com/espressif/esptool/wiki/espefuse>`__
* `espsecure.py - for working with ESP32 security
features <https://github.com/espressif/esptool/wiki/espsecure>`__
Serial Connections
------------------
The ESP8266 & ESP32 ROM serial bootloader uses a 3.3V UART serial
connection. Many development boards make the serial connections for you
onboard.
However, if you are wiring the chip yourself to a USB/Serial adapter or
similar then the following connections must be made:
+---------------------+-------------------+
| ESP32/ESP8266 Pin | Serial Port Pin |
+=====================+===================+
| TX (aka GPIO1) | RX (receive) |
+---------------------+-------------------+
| RX (aka GPIO3) | TX (transmit) |
+---------------------+-------------------+
| Ground | Ground |
+---------------------+-------------------+
Note that TX (transmit) on the ESP8266 is connected to RX (receive) on
the serial port connection, and vice versa.
Do not connect the chip to 5V TTL serial adapters, and especially not to
"standard" RS-232 adapters! 3.3V serial only!
Entering the Bootloader
-----------------------
Both ESP8266 and ESP32 have to be reset in a certain way in order to
launch the serial bootloader.
On some development boards (including NodeMCU, WeMOS, HUZZAH Feather,
Core Board, ESP32-WROVER-KIT), esptool.py can automatically trigger a
reset into the serial bootloader - in which case you don't need to read
this section.
For everyone else, three things must happen to enter the serial
bootloader - a reset, required pins set correctly, and GPIO0 pulled low:
Boot Mode
~~~~~~~~~
Both ESP8266 and ESP32 choose the boot mode each time they reset. A
reset event can happen in one of several ways:
* Power applied to chip.
* The nRESET pin was low and is pulled high (on ESP8266 only).
* The CH\_PD/EN pin ("enable") pin was low and is pulled high.
On ESP8266, both the nRESET and CH\_PD pins must be pulled high for the
chip to start operating.
For more details on selecting the boot mode, see the following Wiki
pages:
* `ESP8266 Boot Mode
Selection <https://github.com/espressif/esptool/wiki/ESP8266-Boot-Mode-Selection>`__
* `ESP32 Boot Mode
Selection <https://github.com/espressif/esptool/wiki/ESP32-Boot-Mode-Selection>`__
Flash Modes
-----------
``write_flash`` and some other commands accept command line arguments to
set bootloader flash mode, flash size and flash clock frequency. The
chip needs correct mode, frequency and size settings in order to run
correctly - although there is some flexibility. A header at the
beginning of a bootable image contains these values.
To override these values, the options ``--flash_mode``, ``--flash_size``
and/or ``--flash_freq`` must appear after ``write_flash`` on the command
line, for example:
::
esptool.py --port /dev/ttyUSB1 write_flash --flash_mode dio --flash_size 4MB 0x0 bootloader.bin
These options are only consulted when flashing a bootable image to an
ESP8266 at offset 0x0, or an ESP32 at offset 0x1000. These are addresses
used by the ROM bootloader to load from flash. When flashing at all
other offsets, these arguments are not used.
Flash Mode (--flash\_mode, -fm)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These set Quad Flash I/O or Dual Flash I/O modes. Valid values are
``keep``, ``qio``, ``qout``, ``dio``, ``dout``. The default is ``keep``,
which keeps whatever value is already in the image file. This parameter
can also be specified using the environment variable ``ESPTOOL_FM``.
Most boards use ``qio`` mode. Some ESP8266 modules, including the
ESP-12E modules on some (not all) NodeMCU boards, are dual I/O and the
firmware will only boot when flashed with ``--flash_mode dio``. Most
ESP32 modules are also dual I/O.
In ``qio`` mode, two additional GPIOs (9 and 10) are used for SPI flash
communications. If flash mode is set to ``dio`` then these pins are
available for other purposes.
For a full explanation of these modes, see the `SPI Flash Modes wiki
page <https://github.com/espressif/esptool/wiki/SPI-Flash-Modes>`__.
Flash Frequency (--flash\_freq, -ff)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Clock frequency for SPI flash interactions. Valid values are ``keep``,
``40m``, ``26m``, ``20m``, ``80m`` (MHz). The default is ``keep``, which
keeps whatever value is already in the image file. This parameter can
also be specified using the environment variable ``ESPTOOL_FF``.
The flash chip connected to most chips works with 40MHz clock speeds,
but you can try lower values if the device won't boot. The highest 80MHz
flash clock speed will give the best performance, but may cause crashing
if the flash or board design is not capable of this speed.
Flash Size (--flash\_size, -fs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Size of the SPI flash, given in megabytes. Valid values vary by chip
type:
+-----------+--------------------------------------------------------------------------------------------------------------------+
| Chip | flash\_size values |
+===========+====================================================================================================================+
| ESP32 | ``keep``, ``detect``, ``1MB``, ``2MB``, ``4MB``, ``8MB``, ``16MB`` |
+-----------+--------------------------------------------------------------------------------------------------------------------+
| ESP8266 | ``keep``, ``detect``, ``256KB``, ``512KB``, ``1MB``, ``2MB``, ``4MB``, ``2MB-c1``, ``4MB-c1``, ``8MB``, ``16MB`` |
+-----------+--------------------------------------------------------------------------------------------------------------------+
For ESP8266, some `additional sizes & layouts for OTA "firmware slots"
are available <#esp8266-and-flash-size>`__.
The default ``--flash_size`` parameter is ``keep``. This means that if
no ``--flash_size`` argument is passed when flashing a bootloader, the
value in the bootloader .bin file header is kept instead of detecting
the actual flash size and updating the header.
To enable automatic flash size detection based on SPI flash ID, add the
argument ``esptool.py [...] write_flash [...] -fs detect``. If detection
fails, a warning is printed and a default value of of ``4MB`` (4
megabytes) is used.
If flash size is not successfully detected, you can find the flash size
by using the ``flash_id`` command and then looking up the ID from the
output (see `Read SPI flash id <#read-spi-flash-id-flash_id>`__).
Alternatively, read off the silkscreen labelling of the flash chip and
search for its datasheet.
The default ``flash_size`` parameter can also be overridden using the
environment variable ``ESPTOOL_FS``.
ESP8266 and Flash Size
^^^^^^^^^^^^^^^^^^^^^^
The ESP8266 SDK stores WiFi configuration at the "end" of flash, and it
finds the end using this size. However there is no downside to
specifying a smaller flash size than you really have, as long as you
don't need to write an image larger than this size.
ESP-12, ESP-12E and ESP-12F modules (and boards that use them such as
NodeMCU, HUZZAH, etc.) usually have at least 4 megabyte / ``4MB``
(sometimes labelled 32 megabit) flash.
If using OTA, some additional sizes & layouts for OTA "firmware slots"
are available. If not using OTA updates then you can ignore these extra
sizes:
+-------------------+-----------------------+-----------------+-----------------+
| flash\_size arg | Number of OTA slots | OTA Slot Size | Non-OTA Space |
+===================+=======================+=================+=================+
| 256KB | 1 (no OTA) | 256KB | N/A |
+-------------------+-----------------------+-----------------+-----------------+
| 512KB | 1 (no OTA) | 512KB | N/A |
+-------------------+-----------------------+-----------------+-----------------+
| 1MB | 2 | 512KB | 0KB |
+-------------------+-----------------------+-----------------+-----------------+
| 2MB | 2 | 512KB | 1024KB |
+-------------------+-----------------------+-----------------+-----------------+
| 4MB | 2 | 512KB | 3072KB |
+-------------------+-----------------------+-----------------+-----------------+
| 2MB-c1 | 2 | 1024KB | 0KB |
+-------------------+-----------------------+-----------------+-----------------+
| 4MB-c1 | 2 | 1024KB | 2048KB |
+-------------------+-----------------------+-----------------+-----------------+
| 8MB [^] | 2 | 1024KB | 6144KB |
+-------------------+-----------------------+-----------------+-----------------+
| 16MB [^] | 2 | 1024KB | 14336KB |
+-------------------+-----------------------+-----------------+-----------------+
- [^] Support for 8MB & 16MB flash size is not present in all ESP8266
SDKs. If your SDK doesn't support these flash sizes, use
``--flash_size 4MB``.
ESP32 and Flash Size
^^^^^^^^^^^^^^^^^^^^
The ESP-IDF flashes a partition table to the flash at offset 0x8000. All
of the partitions in this table must fit inside the configured flash
size, otherwise the ESP32 will not work correctly.
Merging binaries
----------------
The ``merge_bin`` command will merge multiple binary files (of any kind)
into a single file that can be flashed to a device later. Any gaps
between the input files are padded with 0xFF bytes (same as unwritten
flash contents).
For example:
::
esptool.py --chip esp32 merge_bin -o merged-flash.bin --flash_mode dio --flash_size 4MB 0x1000 bootloader.bin 0x8000 partition-table.bin 0x10000 app.bin
Will create a file ``merged-flash.bin`` with the contents of the other 3
files. This file can be later be written to flash with
``esptool.py write_flash 0x0 merged-flash.bin``.
Note: Because gaps between the input files are padded with 0xFF bytes,
when the merged binary is written then any flash sectors between the
individual files will be erased. To avoid this, write the files
individually.
Options
~~~~~~~
- The ``merge_bin`` command supports the same ``--flash_mode``,
``--flash_size`` and ``--flash_freq`` options as the ``write_flash``
command to override the bootloader flash header (see above for
details). These options are applied to the output file contents in
the same way as when writing to flash. Make sure to pass the
``--chip`` parameter if using these options, as the supported values
and the bootloader offset both depend on the chip.
- The ``--target-offset 0xNNN`` option will create a merged binary that
should be flashed at the specified offset, instead of at offset 0x0.
- The ``--fill-flash-size SIZE`` option will pad the merged binary with
0xFF bytes to the full flash specified size, for example
``--fill-flash-size 4MB`` will create a 4MB binary file.
- It is possible to append options from a text file with ``@filename``.
As an example, this can be conveniently used with the ESP-IDF build
system, which produces a ``flash_args`` file in the build directory
of a project:
.. code:: sh
cd build # The build directory of an ESP-IDF project
esptool.py --chip esp32 merge_bin -o merged-flash.bin @flash_args
Advanced Options
----------------
See the `Advanced Options wiki
page <https://github.com/espressif/esptool/wiki/Advanced-Options>`__ for
some of the more unusual esptool.py command line options.
Remote Serial Ports
-------------------
It is possible to connect to any networked remote serial port that
supports `RFC2217 <http://www.ietf.org/rfc/rfc2217.txt>`__ (Telnet)
protocol, or a plain TCP socket. See the `Remote Serial Ports wiki
page <https://github.com/espressif/esptool/wiki/Remote-Serial-Ports>`__
for details.

View File

@@ -1 +1 @@
esp-docs==0.1.1
esp-docs==0.2.0

View File

@@ -659,8 +659,9 @@ class ESPLoader(object):
print('') # end 'Connecting...' line
if last_error is not None:
raise FatalError('Failed to connect to %s: %s'
'\nFor troubleshooting steps visit: https://github.com/espressif/esptool#troubleshooting' % (self.CHIP_NAME, last_error))
raise FatalError('Failed to connect to {}: {}'
'\nFor troubleshooting steps visit: '
'https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html'.format(self.CHIP_NAME, last_error))
if not detecting:
try:

View File

@@ -40,33 +40,18 @@ long_description = """
==========
esptool.py
==========
A command line utility to communicate with the ROM bootloader in Espressif ESP8266 & ESP32 microcontrollers.
A Python-based, open-source, platform-independent utility to communicate with the ROM bootloader in Espressif chips.
Allows flashing firmware, reading back firmware, querying chip parameters, etc.
The esptool.py project is `hosted on github <https://github.com/espressif/esptool>`_.
The esptool.py project is hosted on github: https://github.com/espressif/esptool
Documentation
-------------
Installation
------------
esptool can be installed via pip:
$ pip install --upgrade esptool
Since version 1.3, esptool supports both Python 2.7 and Python 3.4 or newer.
Since version 2.0, esptool supports both ESP8266 & ESP32.
Usage
-----
Please see the `Usage section of the README.md file <https://github.com/espressif/esptool#usage>`_.
You can also get help information by running `esptool.py --help`.
Visit online `esptool documentation <https://docs.espressif.com/projects/esptool/>`_ or run ``esptool.py -h``.
Contributing
------------
Please see the `CONTRIBUTING.md file on github <https://github.com/espressif/esptool/blob/master/CONTRIBUTING.md>`_.
Please see the `contributions guide <https://docs.espressif.com/projects/esptool/en/latest/contributing.html>`_.
"""
# For Windows, we want to install esptool.py.exe, etc. so that normal Windows command line can run them
@@ -90,9 +75,14 @@ setup(
name='esptool',
py_modules=['esptool', 'espsecure', 'espefuse'],
version=find_version('esptool.py'),
description='A serial utility to communicate & flash code to Espressif ESP8266 & ESP32 chips.',
description='A serial utility to communicate & flash code to Espressif chips.',
long_description=long_description,
url='https://github.com/espressif/esptool',
url='https://github.com/espressif/esptool/',
project_urls={
'Documentation': 'https://docs.espressif.com/projects/esptool/',
'Source': 'https://github.com/espressif/esptool/',
'Tracker': 'https://github.com/espressif/esptool/issues/',
},
author='Fredrik Ahlberg (themadinventor) & Angus Gratton (projectgus) & Espressif Systems',
author_email='',
license='GPLv2+',
@@ -105,7 +95,7 @@ setup(
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Embedded Systems',
'Environment :: Console',
'License :: OSI Approved :: GNU General Public License v2 or later (GPL-2.0-or-later)',
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4', # Note: when dropping 3.4 support we can also remove the check in setup_requires
'Programming Language :: Python :: 3.5',