Esp8266 выдает ошибку

ESP8266 is a low-cost Wi-Fi chip that supports full TCP/IP stack. Till date, numerous types of boards are developed using ESP8266. The developers implement various programming languages to program this chip. You can use very basic level AT commands, low-level C/C++ language, or high-level and users friendly languages like Arduino, Micropython, and NodeMCU. The possibilities are virtually endless. But, ESP8266 sometime shows errors while connected to the serial monitor.

Understanding The Error Messages

The error messages are displayed in predefined codes. Unless you know the code, you can never understand what it says. ESP8266 error messages can be categorized into 3 types – 1) Reset causes, 2) Boot modes, and 3) Fatal Exceptions. Though some can argue that boot mode is not exactly an “error message”, but sometimes it really helps to diagnose a runtime error. Explanation of all the three error messages are below:

1. Reset Causes

Each time ESP8266 reboots, the ROM code will print out a number corresponding to the reset cause. You can verify the cause of the reset based on the number. Use this as a debugging method when you cannot start the user program and need to analyze the cause of the reset. The chart is given below,

Reset Cause No. Description
0 Unidentified
1 Power reboot or normal boot
2 External reset using reset pin or wake up from deep sleep
3 Software reset
4 Hardware watchdog (WDT) reset

Examples:

rst cause: 2   ->  Normal reset using reset peen or woke up from a deep-sleep.
rst cause: 4   ->  Device encountered a hardware WDT reset.

2. Boot Modes

On reboot, ESP8266 prints the boot mode too. The boot mode message helps to find out two important information: pin mode of three GPIO pins and the location of the boot file used. A boot mode message looks like below,

boot mode :  (5,6)

So, the pattern is – boot mode :  (m,n), where represents the state of three GPIO pins – 15, 0, and 2, and represents the location of the boot file used.

The following table shows the GPIO states as per the value of m,

0 -> ( logic LOW) = 0 Volt            1 -> (Logic HIGH) = 3.3 volt
Value of “m” GPIO15 GPIO0 GPIO2 Mode
0 0 0 0 Invalid
1 0 0 1 UART
2 0 1 0 Invalid
3 0 1 1 Flash
4 1 0 0 SDIO
5 1 0 1 SDIO
6 1 1 0 SDIO
7 1 1 1 SDIO

The table below shows different boot modes for different states of the GPIOs.

untitled

FlashMode and BootMode ESP12E

The following table shows the boot modes as per the value of n,

Value of “n” SD_sel != 3 SD_sel == 3
0 Remapping _
1 UART boot _
2 Jump boot _
3 Flash boot _
4 SDIO LowSpeed V2 IO UART1 booting
5 SDIO HighSpeed V1 IO UART1 booting
6 SDIO LowSpeed V1 IO UART1 booting
7 SDIO HighSpeed V2 IO UART1 booting

Example:

boot mode :  (3,6)  ->  GPIO 15 is low, GPIO 0 is high, GPIO 2 high, esp8266 booted from flash memory. SDIO LowSpeed v1 IO, UART1 booting.

3. Fatal Exceptions

When a program crashes, it prints out an error message containing a fatal exception number. You can debug the crash based on the Fatal exception number.

The following table shows common Fatal exceptions and their possible causes.

Fatal Exception No. Details Possible Causes
0 Command is invalid 1. Damaged .BIN binaries
2. Wild pointers
6 Division by zero Division by zero
9 unaligned read/write operation addresses 1. Unaligned read/write cache addresses
2. Wild pointers
28/29 Access to invalid addresses 1. Access to cache after it’s turned off
2. Wild pointers

Example: (As per the documentation of espressif.com. The explanation seemed a bit unclear there)

Fatal exception (28): 
epc1=0x4025bfa6, epc2=0x00000000, epc3=0x00000000, excvaddr=0x0000000f, depc=0x00000000

If user1.1024.new.2.bin is used, verify that the exception address is “0x4025bfa6” in the user1.1024.new.2.S file. If eagle.irom0text.bin is used, verify the cause of the fatal exception in the eagle.S file. If the address of exception cannot be found, it means that the crash occurs during an interrupt, or that there is a code problem in ROM, such as: –

  • 4000e190
  • 4000df48
  • 4000dea8
  • 4000de84
  • 4000e1e0

Conclusion

The above tables and explanations will help you to debug your codes from the error messages. But, there are a few tricks that can be followed to avoid such problems. Making proper wirings is one of them. Even a slightly loose connection can yield tons of errors and is enough to become your nightmare. Even if you are super sure that connections are pretty okay, still check it again. Disconnect all existing wirings and connect them again.

Try to avoid using any breadboard. It seems strange, but there’s a reason. You cannot be sure about the internal connections of the breadboard. Always try to solder wires and external components directly with ESP8266 breakout boards for an error-free result. This simple trick solved many of my problems dramatically.

Another important and clever trick is using a pull-up or a pull-down resistor instead of directly connecting boot selector GPIOs to Vcc or ground. Also, don’t forget to connect a pull-up resistor between reset pin and Vcc. A 10K ohm resistor will work just fine as a pull-up/down resistor.

  • #1

Добрый день, уважаемые форумчане!
Сделал отладочную плату для ESP-01 по следующей схеме
схема.jpg
Выдает вместо отладочной информации такую лабуду
2020-10-26_120608.jpg
При этом через адаптер https://ae01.alicdn.com/kf/H4a2e18d…odule-3-3V-5V-Compatible-Serial-Board-For.jpg все работает.
Есть сомнения в номиналах элементов обвязки. Сравниваю сопротивления между контактами на своей плате и на плате переходника. Отличаются. Не подскажите, что сделано неправильно, и в какую сторону копать. Схему переходника не могу найти, чтобы сделать аналогично.

  • #2

Первая проблема решена. Теперь ESP-01 работает от 5в внешних. Проблема была в неправильном номинале резистора R12, подтягивающего вывод GPIO2 к VCC. Номинал был уменьшен до 1к, и ESP стартует. Но теперь возникла другая проблема. При использовании блока питания 220В/12В, установленного на плате, микросхема опять не стартует. Может кто подскажет, в какую теперь сторону копать? Или стоит номиналы всех подтягивающих резисторов уменьшить?
Во вложении вид печатной платы.
плата.png

  • #3

По совету из поста https://esp8266.ru/forum/threads/esp-01-lovit-pomexu-a-sonoff-net.3440/post-52063 поставил после 1117 электролит 2200 мкФх10В. Но не помогло. Также заметил, что при питании от USB синий светодиод мигает 2 раза, а при питании от сети 220 В — происходит только одно мигание. Сейчас попробую еще керамику припаять прямо на ножки ESP, может поможет. Хотя есть подозрение, что может помеха идет не по питанию, а по другим выводам.

  • #4

ЗЫ: припаивание керамики прямо на выводы питания ESP не помогло.

  • #5

заменил подтягивающие резисторы на 1к. И припаял 10 нФ на пины RST — GND. Старт модуля стал лучше, но все равно после снятия питания модуль не всегда нормально стартует. Не подскажете, что еще можно проверить. Пины RX-TX выведены на гребенку и к ним ничего не подключено, влияет ли это на старт?

  • #6

Отключите triak , zero и проверьте как будет стартовать.

  • #7

У вас схема сделана неправильно.
Нельзя до запуска ESP что то вешать на пины GPIO0 GPIO2 и GPIO15.
Вернее можно, но осторожно.
У вас все что там висит надо отрубить и все будет нормально работать
потом разбирайтесь с тем что нагородили на эти пины.

  • #8

Доброй ночи!
Схему частично позаимствовал из этого источника

www.instructables.com

Light Switch + Fan Dimmer in One Board With ESP8266

Light Switch + Fan Dimmer in One Board With ESP8266: In this tutorial you are going to learn how to build your own light switch and fan dimmer in just one board with the microcontroller and WiFi module ESP8266. This is a great project for IoT. Cautions: This circuit handles AC main voltages, so…

www.instructables.com


www.instructables.com

Попробую сегодня вечером убрать на GPIO0 и GPIO2 все лишнее. GPIO15 не выведен на ESP-01.

  • #9

Убрал пока резистор R11, который подключен к GPIO2. Из 10 переталкиваний питания ESP нормально стартанула 3 раза.
Потом убрал оптопару 4N35, подключенную к выводу GPIO0 и ESP из 10 раз стартанула вроде бы правильно все 10. Как бы теперь правильно прилепить оптопару обратно? Спасибо всем за содействие.

  • #10

Как бы теперь правильно прилепить оптопару обратно?

На выводах GPIO0 и GPIO2, при старте, должен быть высокий уровень, ваша схема этого не обеспечивает.
Диод Оптопары можно попробовать включить в плюсовую цепь, через резистор, но надо пробовать будет ли нормально запускаться.
Или подключитесь к Rx Tx или возьмите esp12F.

  • #11

Как я выше написал, проблема скорее всего была в пине GPIO0, к которому был подключен детектор перехода через ноль сети питания. И на этот пин подключен транзистор оптопары, который закрывается в момент перехода сетевого напряжения через «0» и и вывод подтягивается к +3 В. В остальное время пин будет притянут к «GND». Но у товарища, по ссылке выше, все это как-то работает.
схема.jpg
я указал на схеме выше. Имеет ли значение, что в исходной схеме используется другая оптопара? Подтяжка к 3,3В также организована 1к резистором.

Это понятно, хотелось организовать это на валяющихся без дела ESP-01.

  • #12

ЗЫ: и у него на видео все работает. Чудес же не бывает. Схемотехника сделана также как и у него.

  • #13

ЗЫ1: Во непруха, прочитал у него на канале Youtube вопрос
«Я хотел бы сделать этот проект, но вместо того, чтобы управлять двигателем вентилятора, я хотел бы контролировать интенсивность света. Можно ли это сделать так же, как и систему для вентилятора? И обязательно ли раскрашивать кнопку сброса во всех проектах такого типа? «
И ответ этого товарища
«Кнопка сброса необходима в этом типе проекта, где используются все контакты esp8266, потому что у него есть определенные уловки, и иногда вам нужно сбрасывать его несколько раз подряд, чтобы он загружался в правильной конфигурации. Вы можете использовать точно такую же схему и код, и вы можете контролировать интенсивность. «
поможет ли керамический конденсатор 100 нФ между GND и GPIO0, для задержки на время включения ESP?

  • #14

поможет ли керамический конденсатор 100 нФ между GND и GPIO0, для задержки на время включения ESP?

Поможет, будет гарантированно не включаться.

  • #15

:) буду думать, как перевести на свободный пин TXD, а GPIO0 останется чисто под выбор способа загрузки. Получается, что выводы GPIO0 и GPIO2 нельзя использовать под ввод, так как нельзя обеспечить гарантированный высокий уровень при включении. Их можно использовать только как вывод, с организацией высокого уровня при старте

  • #16

Получается, что выводы GPIO0 и GPIO2 нельзя использовать под ввод, так как нельзя обеспечить гарантированный высокий уровень при включении.

Наоборот, можно использовать под ввод и вывод, если обеспечить гарантированный высокий уровень при включении.

Если не лень, в вашей схеме можно добавить микросхему, которая будет подключать выводы GPIO0 и GPIO2 к схеме с задержкой после подачи питания. Но проще

подключитесь к Rx Tx или возьмите esp12F.

, но учтите, что после включения, на ноге Tx будет пачка импульсов.

Последнее редактирование:

  • #17

А насколько это критично, что будет выводиться отладочная информация на TXD при старте. Я же могу после задержки включать чтение на этом выводе? TXD лучше притянуть к 3,3В резистором 1к?

  • #18

Я же могу после задержки включать чтение на этом выводе?

Что будет, если схема подаст на вывод есп лог. ноль, а есп в это время на эту ногу подаст лог. единицу?
Безопасней вывод Tx использовать на вывод, ну при включении морганет лампочка.

  • #19

будет к.з. Может тогда стоит добавить последовательный резистор, если не изменяет память считали 560 Ом, для ограничения тока.

  • #20

Может тогда стоит добавить последовательный резистор, если не изменяет память считали 560 Ом, для ограничения тока.

Может и будет работать, только нужно будет поставить резистор от плюс 3.3 в на оптотранзистор.
Поставьте номиналом 10ком, если будут помехи, можно уменьшить до 1ком.

  • Introduction

  • Initial Checks

  • Advanced Checks

  • Reset Methods

  • Ck

  • Nodemcu

  • I’m Stuck

  • Conclusion

Introduction¶

This message indicates issue with uploading ESP module over a serial
connection. There are couple of possible causes, that depend on the type
of module, if you use separate USB to serial converter, what parameters
are selected for upload, etc. As result there is no single answer on the
root cause. To find it out you may need to complete couple of
troubleshooting steps.

Note: If you are just starting with ESP, to reduce potential issues
with uploading, select ESP board with integrated USB to serial
converter. This will considerably reduce number of user depended
factors or configuration settings that influence upload process.

Example boards with USB to serial converter build in, that will make
your initial project development easier, are shown below.

Example boards with integrated USB to serial converter

Example boards with integrated USB to serial converter

If you are using a Generic ESP8266 module, separate USB to serial
converter and connect them by yourself, please make sure you have the
following three things right: 1. Module is provided with enough power,
2. GPIO0, GPIO15 and CH_PD are connected using pull up / pull down
resistors, 3. Module is put into boot loader mode.

For specific details please refer to section on Generic ESP8266 module.
Example modules without USB to serial converter on board are shown below.

Example ESP8266 modules without USB to serial converter

Example ESP8266 modules without USB to serial converter

Initial Checks¶

In order to troubleshoot “espcomm_sync failed” error, please proceed
step by step through the checklist below. This list is organized
starting with most common and simple to more complex issues.

  1. Start with reading exact message displayed in debug window of Arduino
    IDE. In many cases it provides direct information where the issue is.

"espcomm\_open failed" error

“espcomm_open failed” error

For instance message above suggests that Arduino IDE is unable to open a
serial port COM3. Check if you have selected port where your module is
connected to.

Serial port selection

Serial port selection

  1. If a module is connected to the serial port but not responding as a
    valid ESP8266 device, the message will read slightly different (see
    below). If you have other modules connected to your PC, make sure
    that you are uploading code to ESP8266 and not to e.g. Arduino UNO.

Serial port selection

Serial port selection

  1. To have your PC talking to ESP, select exact ESP type in upload menu.
    If selection is incorrect then the upload may fail.

Board selection

Board selection

Basing on selected board type, Arduino IDE will apply specific “reset
method” to enter the board into boot loading mode. Reset methods are
board specific. Some boards do not have the h/w in place to support
reset by Arduino IDE. If this is the case, you need to enter such board
into boot loading mode manually.

  1. Upload may be also failing due to too high speed. If you have long or
    poor quality USB cable, try reducing selection under Upload Speed.

Serial speed selection

Serial speed selection

Advanced Checks¶

  1. If you are still facing issues, test if module is indeed entering the
    boot loading mode. You can do it by connecting secondary USB to
    serial converter and checking the message displayed. Attach RX and
    GND pins of converter to TX and GND pin of ESP as shown on example
    below (get fzz
    source).

Secondary USB to serial converter hookup

Secondary USB to serial converter hookup

Then open a terminal at 74880 baud, and look what message is reported
when ESP is being reset for programming. Correct message looks as
follows:

ets Jan  8 2013,rst cause:2, boot mode:(1,7)

If you see similar message but different values then decode them using
Boot Messages and Modes. The
key information is contained in first digit / three right-most bits of
the boot mode message as shown below.

Decoding of boot mode

Decoding of boot mode

For instance message boot mode (3,3) indicates that pins GPIO2 and
GPIO0 are set HIGH and GPIO15 is set LOW. This is configuration for
normal
operation
of
module (to execute application from flash), not for boot
loading

(flash programming).

Note: Without having this step right you will not be able to upload
your module over a serial port.

  1. You have confirmed that module is in boot loading mode but upload
    still fails. If you are using external USB to serial converter, then
    check if it operates correctly by looping it back. This is quite
    simple check. Just connect TX and RX of your converter together like
    on picture below. Then open Serial Monitor and type some characters.
    If everything is fine, then you should see what you type immediately
    printed back on the monitor. For an ESP with USB to serial converter
    on board, this check may involve breaking some PCB traces. I would
    not do it unless being desperate. Instead try steps below.

USB to serial converter loop back

USB to serial converter loop back

  1. Next step to try, if not done already, is checking detailed debug
    messages. Go to File > Preferences, enable Show verbose output
    during: upload
    and try uploading again. For successful upload this
    log should look similar to example shown below:

C:\Users\Krzysztof\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.8/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\KRZYSZ~1\AppData\Local\Temp\build7e44b372385012e74d64fb272d24b802.tmp/Blink.ino.bin    esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>       setting board to ck       setting baudrate from 115200 to 115200       setting port from COM1 to COM3       setting address from 0x00000000 to 0x00000000       espcomm_upload_file       espcomm_upload_mem       setting serial port timeouts to 1000 ms   opening bootloader   resetting board   trying to connect       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       read 0, requested 1   trying to connect       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data   Uploading 226368 bytes from to flash at 0x00000000       erasing flash       size: 037440 address: 000000       first_sector_index: 0       total_sector_count: 56       head_sector_count: 16       adjusted_sector_count: 40       erase_size: 028000       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       setting serial port timeouts to 15000 ms       setting serial port timeouts to 1000 ms       espcomm_send_command: receiving 2 bytes of data       writing flash   ..............................................................................................................................................................................................................................   starting app without reboot       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       espcomm_send_command: receiving 2 bytes of data   closing bootloader       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete

Upload log may be longer depending on number of connection attempts made
by esptool. Analyze it for any anomalies to configuration you have
selected in Arduino IDE, like different serial port, reset method, baud
rate, etc. Resolve all noted differences.

Reset Methods¶

If you got to this point and still see espcomm_sync failed, then now
you need to bring in the heavy guns.

Connect scope or logic analyzer to GPIO0, RST and RXD pins of the ESP to
check what’s happening.

Then compare your measurements with wave-forms collected for circuits
below. They document two standard methods of resetting ESP8266 for
upload, that you can select in Arduino IDE — ck and
nodemcu.

Ck¶

Circuit below has been prepared to collect wave-forms for ck reset
method (get fzz source). It is
simpler than for nodemcu reset and therefore often used
to wire up generic ESP modules on a breadboard. Check it against your
wiring when comparing your measurements against wave-forms below.

Sample circuit to check ck method

Sample circuit to check ck method

The following wave-forms below show voltage signals on GPIO0 and RST
pins of the ESP board when uploading the firmware.

Close up of ck reset method signal sequence at the beginning of upload
is shown below.

Reset Method: ck, close up at the beginning of upload

Reset Method: ck, close up at the beginning of upload

Next picture shows complete upload of
Blink.ino
example at 921600 baud. This is quite high speed, so the upload takes
only about 8s.

Reset Method: ck, complete upload

Reset Method: ck, complete upload

Please note that when esptool is not able to initialize upload at the
first time, then it retries reset procedure. Case of one such retry is
shown on wave-form below.

Reset Method: ck, complete upload

Reset Method: ck, complete upload

Each retry is reported in upload log as follows:

resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1

Presented circuit has one important limitation when it comes to work
with Arduino IDE. After opening Serial Monitor (Ctrl-Shift-M), both RTS
and DTR lines are permanently pulled down. As RTS line is connected to
REST input of ESP, the module is hold in reset state / not able to run.
Therefore after uploading module, you need to disconnect both lines or
use different serial terminal program that is not pulling down RTS and
DTR lines. Otherwise the module will get stuck waiting for releasing the
REST signal and you will see nothing on the Serial Monitor.

As for different serial terminal program you can check Arduino IDE
add-on Serial Monitor for
ESP8266 developed
by user [@mytrain](https://github.com/mytrain) and discussed in
#1360.

If you prefer external terminal program, then for Windows users we can
recommend free and handy
Termite.

Nodemcu¶

Nodemcu reset method is named after
NodeMCU board where it
has been introduced for the first time. It overcomes limitations with
handling of RTS and DTR lines discussed for ck reset method
above.

Sample circuit to measure wave-form is shown below (get fzz
source).

Sample circuit to check nodemcu reset method

Sample circuit to check nodemcu reset method

Close up of voltage signals on GPIO0 and RST pins at the beginning of
firmware upload is shown below.

Reset Method: nodemcu, close up at the beginning of upload

Reset Method: nodemcu, close up at the beginning of upload

Please note that the reset sequence is about 10x shorter comparing to
ck reset (about 25ms vs. 250ms).

Next picture covers complete upload of
Blink.ino
example at 921600 baud. Except for difference of the reset signal
sequence, the complete upload looks similar to that of ck.

Reset Method: nodemcu, complete upload

Reset Method: nodemcu, complete upload

A sample wave-form below shows another upload of
Blink.ino
example at 921600 baud, but with two reset retries.

Reset Method: nodemcu, reset retries

Reset Method: nodemcu, reset retries

If you are interested how nodemcu reset method is implemented, then
check circuit below. As indicated it does not pull to ground RTS and DTR
lines once you open Serial Monitor in Arduino IDE.

Implementation of nodemcu reset

Implementation of nodemcu reset

It consists of two transistors and resistors that you can locate on
NodeMCU board on right. On left you can see complete circuit and the
truth table how RTS and DTR signals of the serial interface are
translated to RST and GPIO0 on the ESP. For more details please refer to
nodemcu repository on
GitHub.

I’m Stuck¶

Hopefully at this point you were able to resolve espcomm_sync failed issue and now enjoy quick and reliable uploads of your ESP modules.

If this is still not the case, then review once more all discussed steps in the checklist below.

Initial Checks

  • [ ] Is your module connected to serial port and visible in IDE?

  • [ ] Is connected device responding to IDE? What is exact message in debug window?

  • [ ] Have you selected correct ESP module type in Board menu? What is the selection?

  • [ ] Have you tried to reduce upload speed? What speeds have you tried?

Advanced Checks

  • [ ] What message is reported by ESP at 74880 baud when entering boot loading mode?

  • [ ] Have you checked your USB to serial converter by looping it back? What is the result?

  • [ ] Is your detailed upload log consistent with settings in IDE? What is the log?

Reset Method

  • [ ] What reset method do you use?

  • [ ] What is your connection diagram? Does it match diagram in this FAQ?

  • [ ] What is your wave-form of board reset? Does it match wave-form in this FAQ?

  • [ ] What is your wave-form of complete upload? Does it match wave-form in this FAQ?

Software

  • [ ] Do you use the latest stable version of esp8266 / Arduino? What is it?

  • [ ] What is the name and version of your IDE and O/S?

If you are stuck at certain step, then post this list on ESP8266 Community Forum asking for support.

Conclusion¶

With variety of available ESP8266 modules and boards, as well as
possible connection methods, troubleshooting of upload issues may take
several steps.

If you are a beginner, then use boards with integrated power supply and
USB to serial converter. Check carefully message in debug window and act
accordingly. Select your exact module type in IDE and try to adjust
upload speed. Check if board is indeed entering boot loading mode. Check
operation of your USB to serial converter with loop back. Analyze
detailed upload log for inconsistencies with IDE settings.

Verify your connection diagram and wave-form for consistency with
selected reset method.

If you get stuck, then ask community for
support providing summary of all completed checks.

Test stand used during checking of ck reset method

Test stand used during checking of ck reset method

Test stand used for checking of ck reset method is shown above.

No any ESP module has been harmed during preparation of this FAQ item.

FAQ list :back:

Проверка/Оформление/Редактирование: Мякишев Е.А.

При попытке загрузить ESP8266 получаю ошибку «espcomm_sync failed». Как решить эту проблему?[1]

Это сообщение информирует о проблеме с загрузкой прошивки на ESP8266 через последовательное соединение. Причина может варьироваться в зависимости от типа модуля, от параметров, выбранных при загрузке, от того, используете ли вы отдельный USB-Serial конвертер, и т.д. То есть одного простого ответа на то, что является основной причиной проблемы, нет. Чтобы найти ее, придется выполнить диагностику.

Примечание: Если вы новичок в теме ESP8266 и хотели бы избежать потенциальных проблем с загрузкой прошивки, купите модуль ESP8266 со встроенным конвертером USB-Serial. Это существенно сократит количество факторов (в частности, уменьшит возню с настройками), из-за которых вы можете случайно помешать процессу загрузки.

На картинке ниже показаны платы со встроенным конвертером USB-Serial. Их использование, повторюсь, значительно упростит разработку ваших первых проектов на ESP8266.

Если вы используете «голый» (стандартный) модуль ESP8266 (например, ESP-01 или ESP-12), самостоятельно подключенный к отдельному USB-Serial конвертеру, обязательно проделайте следующее:

  1. Обеспечьте модуль достаточным питанием
  2. Подключите контакты GPIO0, GPIO15 и CH_PD при помощи подтягивающих/стягивающих резисторов
  3. Переведите модуль в режим загрузчика

Более подробно читайте в разделе «Стандартные модули ESP8266» статьи «Платы для аддона ESP8266 для IDE Arduino». На картинке ниже показаны платы без встроенного конвертера USB-Serial:

Платы ESP8266 без встроенного конвертера USB-Serial

Предварительные проверки

Чтобы исправить ошибку «espcomm_sync failed», пройдите шаг за шагом инструкцию ниже. Это список решений, ранжированных от самого простого до самого сложного.

1. Прочтите сообщение, показанное в отладочном окне IDE Arduino. Во многих случаях оно предоставляет точную информацию о том, где именно возникла проблема.

Ошибка «Failed to open COM3»

К примеру, сообщение на картинке выше, говорит, что IDE Arduino не может открыть последовательный порт COM3. Следовательно, нужно проверить, выбран ли в IDE Arduino порт, к которому подключен ваш модуль.

Выбор последовательного порта

2. Если модуль подключен к последовательному порту, но не отвечает как модуль ESP8266, сообщение в отладочном окне будет слегка другим (см. ниже). Если к вашему ПК подключены другие модули, проверьте, что загрузили код на ESP8266, а не на, к примеру, Arduino UNO.

Ошибка «espcomm_sync failed»

3. Чтобы ваш ПК мог общаться с ESP8266, выберите в IDE Arduino правильный модуль ESP8266. Если выбрать неправильный модуль, загрузка прошивки может завершиться неудачей.

Выбор платы

Выбрать правильную плату нужно для того, чтобы IDE Arduino мог применить правильный «метод сброса» при переключении платы в режим загрузчика. Разные платы используют разные методы сброса. У некоторых плат нет аппаратных компонентов, чтобы выполнить сброс через IDE Arduino. В таком случае плату нужно перевести в режим загрузчика вручную.

4. Кроме того, загрузка прошивки может не удаться из-за слишком высокой скорости передачи данных. Если у вас длинный или некачественный USB-кабель, попробуйте снизить скорость загрузки в меню «Upload Speed».

Выбор скорости для передачи данных через последовательное соединение

Дополнительные проверки

1. Если проблема не исчезла, проверьте, точно ли модуль вошел в режим загрузчика. Для этого нужно подключить к ESP8266 добавочный конвертер USB-Serial, а затем посмотреть на показываемые сообщения.

Итак, для начала подключите контакты RX и GND конвертера к контактам TX и GND на ESP8266, как показано ниже:

Подключение добавочного USB-Serial конвертера

Затем откройте терминал на скорости 74880 бод и посмотрите, какие сообщения присылает ESP8266 при сбросе, выполняемом для загрузки прошивки. Правильное сообщение должно выглядеть примерно так:

ets Jan  8 2013,rst cause:2, boot mode:(1,7)

Если у вас появилось такое же сообщение, но с другими значениями, то расшифровать его можно при помощи таблицы из этой статьи (см. третью таблицу в разделе «Сообщения о режимах запуска и причине сброса/перезагрузки»). Ключевая информация содержится в первой цифре, находящейся в скобочках рядом с надписью «boot mode», как показано на картинке ниже:

Расшифровка сообщения о режиме запуска

К примеру, сообщение «boot mode (3, 3)» информирует, что контакты GPIO2 и GPIO0 выставлены на HIGH, а GPIO15 – на LOW. Это настройка для нормальной работы модуля (т.е. выполнения программы, записанной на flash-память), но не для режима загрузчика (т.е. программирования flash-памяти).

Примечание: Если выполнить этот шаг неправильно, вы не сможете загрузить прошивку на модуль через последовательный порт.

2. Вы убедились, что модуль находится в режиме загрузчика, но загрузить прошивку по-прежнему не удается. Если вы используете внешний конвертер USB-Serial, проверьте, правильно ли он работает, закольцевав выход на вход. Этой очень простая проверка. Просто подключите друг к другу контакты RX и TX на конвертере как показано на картинке ниже. Затем откройте монитор порта и впишите там несколько символов. Если все в порядке, то все написанные вами символы должны сразу же появится в мониторе порта. Чтобы выполнить такую проверку на модуле со встроенным USB-Serial конвертером, может понадобиться разрушить некоторые дорожки на печатной плате. Я бы сделал это лишь в полном отчаянии. Лучше попробуйте способы, описываемые еще ниже.

3. Еще один способ – это просмотр более детальных отладочных сообщений. Кликните в IDE Arduino на Файл > Настройки (File > Preferences) и поставьте галочку рядом с пунктом «Показать подробный вывод: Загрузка» («Show verbose output during: upload»). Чтобы загрузка прошивки была успешной, эти логи должны выглядеть примерно так:

C:\Users\Krzysztof\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.8/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\KRZYSZ~1\AppData\Local\Temp\build7e44b372385012e74d64fb272d24b802.tmp/Blink.ino.bin    esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>       setting board to ck       setting baudrate from 115200 to 115200       setting port from COM1 to COM3       setting address from 0x00000000 to 0x00000000       espcomm_upload_file       espcomm_upload_mem       setting serial port timeouts to 1000 ms   opening bootloader   resetting board   trying to connect       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       read 0, requested 1   trying to connect       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data       espcomm_send_command: receiving 2 bytes of data   Uploading 226368 bytes from to flash at 0x00000000       erasing flash       size: 037440 address: 000000       first_sector_index: 0       total_sector_count: 56       head_sector_count: 16       adjusted_sector_count: 40       erase_size: 028000       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       setting serial port timeouts to 15000 ms       setting serial port timeouts to 1000 ms       espcomm_send_command: receiving 2 bytes of data       writing flash   ..............................................................................................................................................................................................................................   starting app without reboot       espcomm_send_command: sending command header       espcomm_send_command: sending command payload       espcomm_send_command: receiving 2 bytes of data   closing bootloader       flush start       setting serial port timeouts to 1 ms       setting serial port timeouts to 1000 ms       flush complete

Логов может быть больше, и это зависит от количества попыток подключения, выполненных «esptool». Проанализируйте эти логи на предмет аномалий в настройках, выбранных в IDE Arduino – вроде другого последовательного порта, метода сброса, скорости передачи данных и т.д. Исправьте найденные ошибки.

Методы сброса

Если вы дошли досюда, а ошибка «espcomm_sync failed» никуда не делась, значит, пришло время расчехлить пушки покрупнее.

Чтобы понять, что происходит, подключите к контактам GPIO0, RST и RXD на ESP8266 осциллограф или логический анализатор. Затем сравните свои измерения с формой сигнала на графиках ниже. В них задокументированы два стандартных метода сброса ESP8266 для загрузки кода, которые можно выбрать в IDE Arduino – «ck» и «nodemcu».

Ck

На картинке ниже изображена цепь, специально подготовленная для определения формы сигнала при использовании метода «ck». Он проще сброса методом «nodemcu» и поэтому часто используется для подключения стандартных модулей ESP к макетной плате. Сверьте это подключение со своим.

Простая цепь для проверки метода «ck»

Графики ниже показывают сигналы напряжения на контактах GPIO0 и RST при загрузке прошивки.

Первый график показывает форму сигнала в начале загрузки кода.

Метод сброса «ck», начало загрузки кода

Второй график показывает полную загрузку скетча «Blink.io» на скорости 921600 бод. Это довольно высокая скорость, поэтому на загрузку уходит всего 8 секунд.

Метод сброса «ck», загрузка скетча «Blink.io»

Когда у «esptool» не получается выполнить загрузку, он инициализирует сброс. Подобная ситуация показана, к примеру, на графике ниже.

Метод сброса «ck», конец загрузки

Каждая новая попытка отображается в логах загрузки:

resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1

Цепь, показанная выше, имеет одно важное ограничение при работе с IDE Arduino. После открытия монитора порта ( Ctrl + ⇧ Shift + M ) линии RTS и DTR переключаются в состояние LOW. Поскольку линия RTS подключена к входной линии REST на ESP8266, то ESP8266 просто зависнет в состоянии сброса и запустить его будет нельзя. Следовательно, после загрузки прошивки вам нужно отключить обе линии или воспользоваться другой консолью (не монитором порта IDE Arduino), которая не переключает RTS и DTR в состояние LOW. В противном случае модуль зависнет в ожидании переключения REST в состояние HIGH и в мониторе порта ничего показывать не будет.

Что касается другой консоли, можно воспользоваться монитором порта IDE Arduino для ESP8266, разработанной пользователем mytrain и обсуждаемой в отчете 1360.

Если предпочитаете программы, то для Windows я бы порекомендовал бесплатную и удобную Termite.

Nodemcu

Метод сброса «nodemcu» получил название от платы NodeMCU, где он был реализован в самый первый раз. Этот метод позволяет обойти ограничения с управлением линиями RTS и DTR, о которых говорилось в главе о методе «ck».

Ниже показана простая цепь для измерения формы сигнала при помощи метода «nodemcu»:

Простая цепь для проверки метода «nodemcu»

Первый график показывает напряжение на контактах GPIO0 и RST в начале загрузки прошивки:

Метод сброса: «nodemcu», начало загрузки

Обратите внимание, что последовательность сигналов длится в 10 раз короче, чем при использовании метода «ck» – примерно 25 мс против 250 мс.

Второй график показывает загрузку скетча «Blink.ino» на скорости 921600 бод. Не считая разницы в длине последовательности сигналов, он выглядит как аналогичный график для метода «ck».

Метод сброса: «nodemcu», загрузка полностью

Третий график тоже демонстрирует загрузку скетча «Blink.ino» на скорости 921600 бод, но с двумя попытками сброса.

Метод сброса: «nodemcu», с двумя новыми попытками сброса

Если вам интересно, как реализуется этот метод сброса, обратите внимание на схемы ниже. Он не притягивает линии RTS и DTR к «земле», когда вы открываете в IDE Arduino монитор порта.

Реализация сброса методом «nodemcu»

Такая цепь состоит из двух транзисторов и резисторов, расположенных на плате NodeMCU. Слева изображены полная схема и таблица истинности – она показывает, как сигналы RTS и DTR на последовательном порту преобразуются в контакты RST и GPIO0 на ESP8266. Более подробно смотрите в репозитории NodeMCU на GitHub.

Эм… похоже, я застрял

Надеемся, советы выше помогли вам справиться с ошибкой «espcomm_sync failed», а загрузка прошивки на ESP8266 стала быстрой и беспроблемной.

Если опять нет, пробегитесь по вопросам ниже (они представляют короткую версию того, о чем писалось в главах выше):

Предварительные проверки

  • Подключен ли ваш модуль к последовательному порту? Видит ли его IDE Arduino?
  • Отвечает ли подключенный девайс на IDE Arduino? Какое именно сообщение появляется в отладочном окне?
  • Правильный ли модуль ESP8266 выбран в меню «Плата»? Что именно у вас выбрано?
  • Пробовали ли вы снизить скорость загрузки? Какую скорость вы уже попробовали?

Дополнительные проверки

  • Какое сообщение присылает ESP8266 на скорости 74880 бод, когда вы входите в режим загрузчика?
  • Проверяли ли вы конвертер USB-Serial, зациклив его? Каков был результат?
  • Соответствует ли информация, показанная в логах, настройкам IDE Arduino? Если да, что в них?

Метод сброса

  • Какой метод сброса вы используете?
  • Какая у вас схема подключения? Она соответствует той, что показана в FAQ?
  • Какую форму имеет сигнал во время сброса? Она соответствует форме сигнала в FAQ?
  • Какую форму имеет сигнал при полной загрузке скетча? Она соответствует форме сигнала в FAQ?

ПО

  • Вы используете стабильную версию аддона ESP8266 для IDE Arduino? Что это за версия?
  • Как называется и какая версия у ваших IDE и ОС?

Если застопорились на каком-то шаге, опишите его как можно подробней и обратитесь за помощью на форум сообщества ESP8266.

Итого

С таким разнообразием модулей и плат на базе ESP8266, а также возможных методов сброса, решение проблем с загрузкой может потребовать очень много проб и попыток.
Если вы новичок, лучше использовать платы со встроенными USB-Serial конвертером и цепью для питания. Осторожно проверяйте сообщения в отладочном окне, а затем действуйте согласно этим сообщениям. Выберите правильный тип модуля в IDE Arduino и правильно настройте скорость загрузки прошивки. Проверьте, действительно ли плата переключена в режим загрузчика. Проверьте работоспособность USB-Serial конвертера, зациклив его. Проанализируйте детальные логи на предмет несоответствий с настройками IDE Arduino.

Проверьте схему подключения и форму сигнала на соответствие используемому методу сброса.

Если застряли, спросите совета у сообщества, предоставив данные обо всех выполненных вами шагах.

Тестовая площадка, которой я пользовался для проверки метода «ck»

На картинке выше показана тестовая площадка для метода «ck».

Во время подготовки этой статьи не пострадало ни одного ESP8266.

См.также

Внешние ссылки

  1. arduino-esp8266.readthedocs.io — I am getting “espcomm_sync failed” error when trying to upload my ESP. How to resolve this issue?

The ESP8266 has a few common issues, specially when you are trying to flash a new firmware or uploading scripts.

This is a companion guide to the Home Automation using ESP8266 and Password Protected Web Server eBooks.

Here’s a compilation with some of the most common problems with the ESP8266 and how to fix them.

ESP8266 Troubleshooting – NodeMCU Flasher

Where do I download the NodeMCU flasher?

Go to the NodeMCU flasher GitHub repository and download the flasher for your Windows PC bit version by clicking the button that says “Raw”:

  • NodeMCU flasher Windows 64 bits
  • NodeMCU flasher Windows 32 bits

Which settings should I use with the NodeMCU flasher?

The NodeMCU flasher already comes with the right settings by default.

If you have changed some of the settings, I highly recommend that you re-download the NodeMCU flasher.

Here’s my current settings:

nodemcu flasher

After I press the “Flash” button nothing happens, the NodeMCU flasher doesn’t start the flashing process 

If you pressed the “Flash” button and nothing happens… It means one of these two things:

  • Problem 1 – Your ESP isn’t in flash mode (double-check if GPIO 0 is connected to GND on power up)
  • Problem 2 – Your FTDI Programmer can’t supply enough current to your ESP

nothing happens

Problem 1 – How to make your ESP go into flash mode:

  1. Close the NodeMCU flasher window
  2. Remove power from your ESP8266
  3. Having your ESP connected like this (double check that GPIO 0 is connected to GND)
  4. Apply power to your ESP8266 and open the NodeMCU flasher
  5. Press the “Flash” button

If it’s still saying “Waiting MAC”, then try the following:

  1. Having the NodeMCU flasher still open
  2. Connect a wire from your ESP8266 reset pin to GND
  3. Remove that wire from GND and connect to VCC

Repeat steps 2 and 3 a few times until your ESP reboots and hopefully the NodeMCU flasher can detect your ESP and start the flashing process.

Problem 2 – If your FTDI can’t supply enough current, you might need to buy a new FTDI programmer or power your ESP8266 with an external power supply.

NodeMCU flasher gets stuck at a certain percentage

nodemcu stuck

  1. Remove power from your ESP+FTDI:
  2. Close the NodeMCU flasher window
  3. Plug your ESP+FTDI to your computer again
  4. Open NodeMCU flasher and try the 19200 baud rate

If this process fails, please repeat the same procedure for the next baud rates (38400, 57600, 74880 and 115200).

I don’t know why, but at least 5 people faced the same problem and this trick solved it. So at a baud rate of 57600 or 115200 I think it will flash 100%. I don’t have any logical explanation, since this is not very common.

How does the NodeMCU flasher should look after a successful flash?

It should have a green arrow in the bottom left.

nodemcu flasher flashed

Unbricking the FTDI Programmer on Windows PC

If you have a brand new FTDI Programmer and you need to install your FTDI drivers on Windows, visit this website for the official drivers: http://www.ftdichip.com/Drivers/VCP.htm.

In alternative, you can contact the seller that sold you the FTDI Programmer.

If you’re having trouble installing the FTDI drivers on Windows 7/8/8.1/10 it’s very likely that FTDI is bricked.

Follow this tutorial to fix that: http://youtu.be/SPdSKT6KdF8.

In the video I mentioned earlier, the guy tells you to download the drivers from the FTDI website, read carefully the YouTube description of his video to find all the links. Here’s the drivers you need: http://www.ftdichip.com/Drivers/CDM/CDM%20v2.12.00%20WHQL%20Certified.zip

ESP8266 Troubleshooting – ESPlorer IDE

ESPlorer IDE Error: only one tcp server allowed

This means that you tried to upload multiple scripts and you ESP is still running the old script with a web server. To fix it, you simply need to send these commands to delete all the files and restart your ESP:

  1. file.format()
  2. node.restart()

Upload the script again and name it ‘init.lua’ and you shouldn’t see that error again.

ESPlorer IDE Error: can’t autodetect firmware

and

ESPlorer IDE Error: Waiting answer from ESP – Timeout reached. Command aborted.Waiting answer from ESP – Timeout reached. Command aborted.

can't autodetect firmware

This sounds like your ESP it’s still in flash mode. How to make your ESP go into user mode:

  1. Close the ESPlorer IDE connection
  2. Remove power from your ESP8266
  3. Having your ESP with GPIO 0 connected to VCC
  4. Apply power to your ESP8266 and re-establish the connection with ESPlorer IDE

If it’s still saying “can’t autodetect firmware”, then try the following:

  1. Having the ESPlorer IDE connection still printing “…..”
  2. Connect a wire from your ESP8266 reset pin to GND
  3. Remove that wire from GND and connect to VCC

Repeat steps 2 and 3 a few times until your ESP reboots and hopefully the ESPlorer IDE can detect your ESP.

My code disappears when I restart the ESP8266

If you upload a script to your ESP and when you restart it your ESP doesn’t do anything. It means that your ESP couldn’t find the script or it occurred a memory issue.

This can be solved like this:

  1. You didn’t save your script with this exact name ‘init.lua’. Re-uploading the same script, but with the ‘init.lua’ name should solve your problem
  2. It can be a memory issue. Re-flashing the ESP with NodeMCU flasher usually solves that problem

Finding the ESP8266 IP Address

Before you start make sure you check these two items:

  1. Verify that the script uploaded to your ESP has the right network credentials
  2. Make sure your ESP is near your router

Here’s what you can do to find the IP address:

Solution 1 – Sending a command with the ESPlorer IDE

  1. Send the command “print(wifi.sta.getip())” with the ESPlorer IDE and it should print your IP Address

ESP IP Address

Solution 2 – Install an IP Scanner Software

  1. An IP Scanner software searches for all the devices in your network
  2. Download this free software:
    1. Windows PC: www.advanced-ip-scanner.com
    2. MAC OS X, Windows or Linux: http://angryip.org
  3. Install one of these softwares (while having your ESP running with that web server script)
  4. Open the IP Scanner software and click “Scan”
  5. Let that process finish (it can take a couple of minutes)

In my case, it found my ESP. Now if I type 192.168.1.95 in my browser I can see the ESP web server.

advanced ip scanner

ESP8266 Troubleshooting – Arduino IDE

I can’t upload scripts to my ESP8266 using the Arduino IDE

How to make your ESP go into upload mode when using the Arduino IDE:

  1. Remove power from your ESP8266
  2. Having your ESP connected like this (double check that GPIO 0 is connected to GND)
  3. Apply power to your ESP8266 and open the Arduino IDE
  4. Press the “Upload” button

Did you experience other problems?

Please leave a comment below, so I can update the troubleshooting guide with more problems and solutions.

Thanks for reading,

-Rui Santos

Понравилась статья? Поделить с друзьями:
  • Esp ошибка сузуки сх4
  • Esp ошибка фольксваген кадди
  • Esp ошибка фольксваген джетта
  • Esp ошибка рено флюенс
  • Esp ошибка опель мерива