1{IDF_TARGET_SECURITY_INFO:default="32 bits ``flags``, 1 byte ``flash_crypt_cnt``, 7x1 byte ``key_purposes``, 32-bit word ``chip_id``, 32-bit word ``eco_version``", esp32s2="32 bits ``flags``, 1 byte ``flash_crypt_cnt``, 7x1 byte ``key_purposes``                                                      "}
2
3Serial Protocol
4===============
5
6This is technical documentation for the serial protocol used by the UART bootloader in the {IDF_TARGET_NAME} ROM and the esptool :ref:`stub loader <stub>` program.
7
8The UART bootloader runs on chip reset if certain strapping pins are set. See :ref:`entering-the-bootloader` for details of this process.
9
10.. only:: not esp8266
11
12    The {IDF_TARGET_NAME} ROM loader serial protocol is similar to ESP8266, although {IDF_TARGET_NAME} adds some additional commands and some slightly different behaviour.
13
14By default, esptool uploads a stub "software loader" to the IRAM of the chip. The stub 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 stub loader. See :ref:`stub` for more information.
15
16.. note::
17
18    There are differences in the serial protocol between ESP chips! To switch to documentation for a different chip, choose the desired target from the dropdown menu in the upper left corner.
19
20Packet Description
21------------------
22
23The 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.
24
25.. _low-level-protocol:
26
27Low Level Protocol
28^^^^^^^^^^^^^^^^^^
29
30The bootloader protocol uses `SLIP <https://en.wikipedia.org/wiki/Serial_Line_Internet_Protocol>`_ packet framing for data transmissions in both directions.
31
32Each 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 longer than the ``size`` field below.
33
34Command Packet
35^^^^^^^^^^^^^^
36
37Each 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.
38
39.. packetdiag:: diag/command_packet_format.diag
40    :caption: Command packet format
41    :align: center
42
43
44+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
45| Byte   | Name        | Comment                                                                                                            |
46+========+=============+====================================================================================================================+
47| 0      | Direction   | Always ``0x00`` for requests                                                                                       |
48+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
49| 1      | Command     | Command identifier (see `Commands`_).                                                                              |
50+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
51| 2-3    | Size        | Length of Data field, in bytes.                                                                                    |
52+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
53| 4-7    | Checksum    | Simple checksum of part of the data field (only used for some commands, see `Checksum`_).                          |
54+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
55| 8..n   | Data        | Variable length data payload (0-65535 bytes, as indicated by Size parameter). Usage depends on specific command.   |
56+--------+-------------+--------------------------------------------------------------------------------------------------------------------+
57
58Response Packet
59^^^^^^^^^^^^^^^
60
61Each received command will result in a response SLIP packet sent from the ESP chip to the host. Contents of the response packet is:
62
63.. packetdiag:: diag/response_packet_format.diag
64    :caption: Command packet format
65    :align: center
66
67+--------+-------------+--------------------------------------------------------------------------------------------------------------+
68| Byte   | Name        | Comment                                                                                                      |
69+========+=============+==============================================================================================================+
70| 0      | Direction   | Always ``0x01`` for responses                                                                                |
71+--------+-------------+--------------------------------------------------------------------------------------------------------------+
72| 1      | Command     | Same value as Command identifier in the request packet that triggered the response                           |
73+--------+-------------+--------------------------------------------------------------------------------------------------------------+
74| 2-3    | Size        | Size of data field. At least the length of the `Status Bytes`_ (2 or 4 bytes, see below).                    |
75+--------+-------------+--------------------------------------------------------------------------------------------------------------+
76| 4-7    | Value       | Response value used by READ_REG command (see below). Zero otherwise.                                         |
77+--------+-------------+--------------------------------------------------------------------------------------------------------------+
78| 8..n   | Data        | Variable length data payload. Length indicated by "Size" field.                                              |
79+--------+-------------+--------------------------------------------------------------------------------------------------------------+
80
81Status bytes
82""""""""""""
83
84The final bytes of the Data payload indicate command status:
85
86.. only:: esp8266
87
88    For stub loader and ESP8266 ROM loader the final two bytes indicate status (most commands return at least a two byte Data payload):
89
90.. only:: not esp8266
91
92    For stub loader the final two bytes indicate status (most commands return at least a two byte Data payload):
93
94+----------+----------+-----------------------------------------------------+
95| Byte     | Name     | Comment                                             |
96+==========+==========+=====================================================+
97| Size-2   | Status   | Status flag, success (``0``) or failure (``1``)     |
98+----------+----------+-----------------------------------------------------+
99| Size-1   | Error    | If Status is 1, this indicates the type of error.   |
100+----------+----------+-----------------------------------------------------+
101
102.. only:: not esp8266
103
104    For {IDF_TARGET_NAME} ROM (only, not the stub loader) the final four bytes are used, but only the first two bytes contain status information:
105
106    +----------+------------+---------------------------------------------------+
107    | Byte     | Name       | Comment                                           |
108    +==========+============+===================================================+
109    | Size-4   | Status     | Status flag, success (``0``) or failure (``1``)   |
110    +----------+------------+---------------------------------------------------+
111    | Size-3   | Error      | If Status 1, this indicates the type of error.    |
112    +----------+------------+---------------------------------------------------+
113    | Size-2   | Reserved   |                                                   |
114    +----------+------------+---------------------------------------------------+
115    | Size-1   | Reserved   |                                                   |
116    +----------+------------+---------------------------------------------------+
117
118ROM Loader Errors
119"""""""""""""""""
120
121The ROM loader sends the following error values
122
123+----------+---------------------------------------------------------------------------+
124| Value    | Meaning                                                                   |
125+==========+===========================================================================+
126| ``0x05`` | "Received message is invalid" (parameters or length field is invalid)     |
127+----------+---------------------------------------------------------------------------+
128| ``0x06`` | "Failed to act on received message"                                       |
129+----------+---------------------------------------------------------------------------+
130| ``0x07`` | "Invalid CRC in message"                                                  |
131+----------+---------------------------------------------------------------------------+
132| ``0x08`` | "Flash write error" - after writing a block of data to flash,             |
133|          | the ROM loader reads the value back and the 8-bit CRC is compared         |
134|          | to the data read from flash. If they don't match, this error is returned. |
135+----------+---------------------------------------------------------------------------+
136| ``0x09`` | "Flash read error" - SPI read failed                                      |
137+----------+---------------------------------------------------------------------------+
138| ``0x0a`` | "Flash read length error" - SPI read request length is too long           |
139+----------+---------------------------------------------------------------------------+
140| ``0x0b`` | "Deflate error" (compressed uploads only)                                 |
141+----------+---------------------------------------------------------------------------+
142
143Stub Loader Status & Error
144""""""""""""""""""""""""""
145
146If the stub loader is used:
147
148-  The status response is always 2 bytes regardless of chip type.
149-  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>`_).
150
151After 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.
152
153Commands
154^^^^^^^^
155
156Supported by stub loader and ROM loader
157"""""""""""""""""""""""""""""""""""""""
158
159.. only:: esp8266
160
161    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
162    | Byte       | Name           | Description                                           | Input Data                                                                                                                         | Output Data                                    |
163    +============+================+=======================================================+====================================================================================================================================+================================================+
164    | ``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.                                   |                                                |
165    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
166    | ``0x03``   | FLASH_DATA     | `Flash Download Data <#writing-data>`__               | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                          |                                                |
167    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
168    | ``0x04``   | FLASH_END      | `Finish 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     |                                                |
169    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
170    | ``0x05``   | MEM_BEGIN      | `Begin RAM Download Start <#writing-data>`__          | Total size, number of data packets, data size in one packet, memory offset                                                         |                                                |
171    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
172    | ``0x06``   | MEM_END        | `Finish RAM Download <#writing-data>`__               | Two 32-bit words: execute flag, entry point address                                                                                |                                                |
173    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
174    | ``0x07``   | MEM_DATA       | `RAM Download Data <#writing-data>`__                 | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                          |                                                |
175    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
176    | ``0x08``   | SYNC           | `Sync Frame <#initial-synchronisation>`__             | 36 bytes: ``0x07 0x07 0x12 0x20``, followed by 32 x ``0x55``                                                                       |                                                |
177    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
178    | ``0x09``   | WRITE_REG      | `Write 32-bit memory address <#32-bit-readwrite>`__   | Four 32-bit words: address, value, mask and delay (in microseconds)                                                                |                                                |
179    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
180    | ``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.   |
181    +------------+----------------+-------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------+
182
183.. only:: esp32
184
185    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
186    | Byte       | Name                 | Description                                                    | Input Data                                                                                                                                                                                                                                     | Output Data                                                                                                                       |
187    +============+======================+================================================================+================================================================================================================================================================================================================================================+===================================================================================================================================+
188    | ``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.                                                                                                                                               |                                                                                                                                   |
189    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
190    | ``0x03``   | FLASH_DATA           | `Flash Download Data <#writing-data>`__                        | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                                                                                                                                      |                                                                                                                                   |
191    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
192    | ``0x04``   | FLASH_END            | `Finish 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                                                                                                                 |                                                                                                                                   |
193    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
194    | ``0x05``   | MEM_BEGIN            | `Begin RAM Download Start <#writing-data>`__                   | Total size, number of data packets, data size in one packet, memory offset                                                                                                                                                                     |                                                                                                                                   |
195    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
196    | ``0x06``   | MEM_END              | `Finish RAM Download <#writing-data>`__                        | Two 32-bit words: execute flag, entry point address                                                                                                                                                                                            |                                                                                                                                   |
197    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
198    | ``0x07``   | MEM_DATA             | `RAM Download Data <#writing-data>`__                          | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                                                                                                                                      |                                                                                                                                   |
199    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
200    | ``0x08``   | SYNC                 | `Sync Frame <#initial-synchronisation>`__                      | 36 bytes: ``0x07 0x07 0x12 0x20``, followed by 32 x ``0x55``                                                                                                                                                                                   |                                                                                                                                   |
201    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
202    | ``0x09``   | WRITE_REG            | `Write 32-bit memory address <#32-bit-readwrite>`__            | Four 32-bit words: address, value, mask and delay (in microseconds)                                                                                                                                                                            |                                                                                                                                   |
203    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
204    | ``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.                                                                                      |
205    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
206    | ``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.                                                                                                                                                    |                                                                                                                                   |
207    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
208    | ``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 ROM loader only.                                                                                                                                   |                                                                                                                                   |
209    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
210    | ``0x0f``   | CHANGE_BAUDRATE      | `Change Baud rate <#initial-synchronisation>`__                | Two 32-bit words: new baud rate, ``0`` if we are talking to the ROM loader or the current/old baud rate if we are talking to the stub loader.                                                                                                  |                                                                                                                                   |
211    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
212    | ``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.  |                                                                                                                                   |
213    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
214    | ``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.                                                                                            |
215    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
216    | ``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.                                                                                                                |                                                                                                                                   |
217    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
218    | ``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   |
219    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
220
221.. only:: not esp8266 and not esp32
222
223    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
224    | Byte       | Name                 | Description                                                    | Input Data                                                                                                                                                                                                                                     | Output Data                                                                                                                       |
225    +============+======================+================================================================+================================================================================================================================================================================================================================================+===================================================================================================================================+
226    | ``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. A fifth 32-bit word passed to ROM loader only: ``1`` to begin encrypted flash, ``0`` to not.                                                  |                                                                                                                                   |
227    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
228    | ``0x03``   | FLASH_DATA           | `Flash Download Data <#writing-data>`__                        | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                                                                                                                                      |                                                                                                                                   |
229    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
230    | ``0x04``   | FLASH_END            | `Finish 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                                                                                                                 |                                                                                                                                   |
231    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
232    | ``0x05``   | MEM_BEGIN            | `Begin RAM Download Start <#writing-data>`__                   | Total size, number of data packets, data size in one packet, memory offset                                                                                                                                                                     |                                                                                                                                   |
233    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
234    | ``0x06``   | MEM_END              | `Finish RAM Download <#writing-data>`__                        | Two 32-bit words: execute flag, entry point address                                                                                                                                                                                            |                                                                                                                                   |
235    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
236    | ``0x07``   | MEM_DATA             | `RAM Download Data <#writing-data>`__                          | Four 32-bit words: data size, sequence number, ``0``, ``0``, then data. Uses `Checksum`_.                                                                                                                                                      |                                                                                                                                   |
237    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
238    | ``0x08``   | SYNC                 | `Sync Frame <#initial-synchronisation>`__                      | 36 bytes: ``0x07 0x07 0x12 0x20``, followed by 32 x ``0x55``                                                                                                                                                                                   |                                                                                                                                   |
239    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
240    | ``0x09``   | WRITE_REG            | `Write 32-bit memory address <#32-bit-readwrite>`__            | Four 32-bit words: address, value, mask and delay (in microseconds)                                                                                                                                                                            |                                                                                                                                   |
241    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
242    | ``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.                                                                                      |
243    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
244    | ``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.                                                                                                                                                    |                                                                                                                                   |
245    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
246    | ``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 ROM loader only.                                                                                                                                   |                                                                                                                                   |
247    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
248    | ``0x0f``   | CHANGE_BAUDRATE      | `Change Baud rate <#initial-synchronisation>`__                | Two 32-bit words: new baud rate, ``0`` if we are talking to the ROM loader or the current/old baud rate if we are talking to the stub loader.                                                                                                  |                                                                                                                                   |
249    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
250    | ``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.  |                                                                                                                                   |
251    |            |                      |                                                                | A fifth 32-bit word passed to ROM loader only: ``1`` to begin encrypted flash, ``0`` to not.                                                                                                                                                   |                                                                                                                                   |
252    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
253    | ``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.                                                                                            |
254    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
255    | ``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.                                                                                                                |                                                                                                                                   |
256    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
257    | ``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   |
258    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
259    | ``0x14``   | GET_SECURITY_INFO    | Read chip security info                                        |                                                                                                                                                                                                                                                | {IDF_TARGET_SECURITY_INFO}    |
260    +------------+----------------------+----------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------+
261
262Supported by stub loader only
263"""""""""""""""""""""""""""""
264
265ROM loaders will not recognise these commands.
266
267+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
268| Byte       | Name              | Description                       | Input                                                                                                                   | Output   |
269+============+===================+===================================+=========================================================================================================================+==========+
270| ``0xd0``   | ERASE_FLASH       | Erase entire flash chip           |                                                                                                                         |          |
271+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
272| ``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.              |          |
273+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
274| ``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   |          |
275+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
276| ``0xd3``   | RUN_USER_CODE     | Exits loader and runs user code   |                                                                                                                         |          |
277+------------+-------------------+-----------------------------------+-------------------------------------------------------------------------------------------------------------------------+----------+
278
279Checksum
280^^^^^^^^
281
282The checksum field is ignored (can be zero) for all commands except for MEM_DATA, FLASH_DATA, and FLASH_DEFL_DATA.
283
284Each of the ``_DATA`` command packets (like ``FLASH_DEFL_DATA``, ``MEM_DATA``) has the same "data payload" format:
285
286+---------+--------------------------+----------------------------------------------------------------+
287| Bytes   | Name                     | Format                                                         |
288+=========+==========================+================================================================+
289| 0-3     | "Data to write" length   | Little endian 32-bit word.                                     |
290+---------+--------------------------+----------------------------------------------------------------+
291| 4-7     | Sequence number          | Little endian 32-bit word. The sequence numbers are 0 based.   |
292+---------+--------------------------+----------------------------------------------------------------+
293| 8-15    | 0                        | Two words of all zeroes, unused.                               |
294+---------+--------------------------+----------------------------------------------------------------+
295| 16-     | "Data to write"          | Length given at beginning of payload.                          |
296+---------+--------------------------+----------------------------------------------------------------+
297
298The checksum is only applied to this final "data to write" section, not the first 16 bytes of data.
299
300To 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).
301
302.. note::
303
304    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.
305
306Functional Description
307----------------------
308
309.. blockdiag:: diag/download_procedure_chart.diag
310    :caption: Download procedure flow chart
311    :align: center
312
313
314.. note::
315    This flow chart is used to illustrate the download procedure (writing to flash), other commands have different flows.
316
317Initial Synchronisation
318^^^^^^^^^^^^^^^^^^^^^^^
319.. list::
320
321    :esp8266: *  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. However the sync packets can be sent at any baud rate, and the UART peripheral will detect this.
322    :not esp8266: *  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. {IDF_TARGET_NAME} always initialises at 115200bps. However the sync packets can be sent at any baud rate, and the UART peripheral will detect this.
323    *  The host should wait until it sees a valid response to a SYNC command, indicating the ESP chip is correctly communicating.
324    *  Esptool then (by default) uses the "RAM Download" sequence to upload :ref:`stub loader <stub>` code to IRAM of the chip. The MEM_END command contains the entry-point address to run the stub loader.
325       The stub 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.
326       If the ``--no-stub`` argument is supplied to esptool, this entire step is skipped.
327    *  esptool then uses READ_REG commands to read various addresses on the chip, to identify chip subtype, revision, etc.
328    :not esp8266: *  For commands which need to use the flash, the {IDF_TARGET_NAME} ROM an stub loader requires the SPI_ATTACH and SPI_SET_PARAMS commands. See `SPI Configuration Commands`_.
329    :esp8266: *  For stub 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.
330    :not esp8266: *  For stub loader and/or {IDF_TARGET_NAME} 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.
331
332Writing Data
333^^^^^^^^^^^^
334
335(Includes RAM Download, Flash Download, Compressed Flash Download.)
336
337.. list::
338
339    *  RAM Download (MEM_BEGIN, MEM_DATA, MEM_END) loads data into the ESP chip memory space and (optionally) executes it.
340    *  Flash Download (FLASH_BEGIN, FLASH_DATA) flashes data into the ESP SPI flash.
341    :esp8266: *  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.
342    :not esp8266: *  Compressed Flash Download is the same, only the data is compressed using the gzip Deflate algorithm to reduce serial overhead.
343
344All three of these sequences follow a similar pattern:
345
346*  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.
347*  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.
348   The last data block should be padded to the block size with 0xFF bytes.
349*  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.
350
351It'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.
352The stub loader does just-in-time erasing as it writes 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).
353
354The 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.
355
356.. only:: esp8266
357
358    Erase Size Bug
359    """"""""""""""
360
361    On ESP8266 ROM loader only (not stub 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.
362
363    This workaround is not needed if the ESP8266 is running the stub loader.
364
365Verifying Uploaded Data
366"""""""""""""""""""""""
367
368.. only:: esp8266
369
370    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.
371
372.. only:: not esp8266
373
374    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 or use another method to verify flash contents.
375
376The 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.
377
378.. only:: not esp8266
379
380    Note that the {IDF_TARGET_NAME} ROM loader returns the md5sum as 32 hex encoded ASCII bytes, whereas the stub loader returns the md5sum as 16 raw data bytes of MD5 followed by 2 status bytes.
381
382SPI Configuration Commands
383^^^^^^^^^^^^^^^^^^^^^^^^^^
384
385SPI Attach command
386""""""""""""""""""
387
388The 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.
389
390.. only:: esp8266
391
392    On the ESP8266 stub loader sending this command before interacting with SPI flash is optional. On ESP8266 ROM loader this command is not supported (SPI flash is enabled when the FLASH_BEGIN command is sent).
393
394    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
395    | Value            | Meaning                                                                                                                          |
396    +==================+==================================================================================================================================+
397    | 0                | Default SPI flash interface                                                                                                      |
398    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
399    | 1                | HSPI interface                                                                                                                   |
400    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
401
402.. only:: not esp8266
403
404    On the {IDF_TARGET_NAME} stub loader sending this command before interacting with SPI flash is optional. On {IDF_TARGET_NAME} ROM loader, it is required to send this command before interacting with SPI flash.
405
406    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
407    | Value            | Meaning                                                                                                                          |
408    +==================+==================================================================================================================================+
409    | 0                | Default SPI flash interface                                                                                                      |
410    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
411    | 1                | HSPI interface                                                                                                                   |
412    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
413    | (other values)   |  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.               |
414    +------------------+----------------------------------------------------------------------------------------------------------------------------------+
415
416    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.)
417
418    When writing the values of each pin as 6-bit numbers packed into the data word, each 6-bit value uses the following representation:
419
420    .. only:: esp32
421
422        * Pin numbers 0 through 30 are represented as themselves.
423        * Pin numbers 32 & 33 are represented as values 30 & 31.
424        * 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.
425
426    On {IDF_TARGET_NAME} ROM loader only, there is an additional 4 bytes in the data payload of this command. These bytes should all be set to zero.
427
428SPI Set Parameters
429""""""""""""""""""
430
431The SPI_SET_PARAMS command sets some parameters of the attached SPI flash chip (sizes, etc).
432
433.. only:: esp8266
434
435    This command is not supported by the ESP8266 ROM loader.
436
437All 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.
438
43932-bit Read/Write
440^^^^^^^^^^^^^^^^^
441
442The 32-bit read/write commands (READ_REG, WRITE_REG) allow word-oriented reading and writing of memory and register data.
443
444These 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.
445
446Reading Flash
447^^^^^^^^^^^^^
448
449The stub loader implements a READ_FLASH command. This command behaves differently to other commands, including the ROM loader's READ_FLASH command:
450
451*  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.
452*  The stub loader will send a standard response packet, with no additional data payload.
453*  Now the stub 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.
454*  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.
455*  The stub 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.
456*  After all data packets are acknowledged received, the stub 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.
457
458After the read flash process is complete, the stub loader goes back to normal command/response operation.
459
460The ROM loader read flash command is more normal but also much slower to read data.
461
462.. _tracing-communications:
463
464Tracing Esptool Serial Communications
465-------------------------------------
466
467esptool 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.
468
469Here is a sample extract, showing a READ_REG command and response:
470
471::
472
473    TRACE +0.000 command op=0x0a data len=4 wait_response=1 timeout=3.000 data=1400f43f
474    TRACE +0.000 Write 14 bytes: c0000a0400000000001400f43fc0
475    TRACE +0.005 Read 1 bytes: c0
476    TRACE +0.000 Read 11 bytes: 010a0200620100000000c0
477    TRACE +0.000 Received full packet: 010a0200620100000000
478
479The +X.XXX value is the time delta (in seconds) since the last trace line.
480
481Values 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:
482
483Note 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.
484Once 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.
485
486Here is a second example showing part of the initial synchronization sequence (lots of 0x55 bytes which are ``U`` in ASCII):
487
488::
489
490    TRACE +0.000 Write 46 bytes:
491        c000082400000000 0007071220555555 | ...$........ UUU
492        5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
493        5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
494    TRACE +0.011 Read 1 bytes: c0
495    TRACE +0.000 Read 63 bytes:
496        0108040007122055 00000000c0c00108 | ...... U........
497        0400071220550000 0000c0c001080400 | .... U..........
498        0712205500000000 c0c0010804000712 | .. U............
499        205500000000c0c0 01080400071220   |  U............
500    TRACE +0.000 Received full packet: 010804000712205500000000
501    TRACE +0.000 Received full packet: 010804000712205500000000
502
503.. important::
504
505    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.
506
507In addition to this trace feature, most operating systems have "system call trace" or "port trace" features which can be used to dump serial interactions.
508