[ESP32] Использование последовательного порта UART
В ESP32 есть 3 последовательных порта, по умолчанию uart0 используется в качестве вывода журнала и консоли, мы можем использовать uart1 и uart2.
Их контакты по умолчанию следующие:
UART | GPIO | UART | GPIO |
---|---|---|---|
U0_RXD | GPIO3 | U0_CTS | GPIO19 |
U0_TXD | GPIO1 | U0_RTS | GPIO22 |
U1_RXD | GPIO9 | U1_CTS | GPIO6 |
U1_TXD | GPIO10 | U1_RTS | GPIO11 |
U2_RXD | GPIO16 | U2_CTS | GPIO8 |
U2_TXD | GPIO17 | U2_RTS | GPIO7 |
Если вы используете модуль ESP32, поскольку SPI Flash подключен, GPIO6
GPIO11 будет занят, поэтому возникнут конфликты, когда uart1 использует контакты по умолчанию, нам нужно настроить контакты на другие К счастью, на GPIO вы можете управлять конфигурацией таким образом.
Использование последовательного порта esp32 можно разделить на 4 этапа:
- Установите параметры последовательного порта, включая скорость передачи данных, четность, биты данных и стоповые биты и т. Д.
- Установите контакты GPIO, используемые последовательным портом
- Установите драйвер и выделите ресурсы для uart
- Выполните последовательную связь
1 Установите параметры последовательного порта
Вызовите метод uart_param_config (), чтобы установить
2 Настройте контакты последовательного порта
Установите контакт сопоставления последовательного порта с помощью uart_set_pin (). Если вы используете значение по умолчанию, вы можете использовать UART_PIN_NO_CHANGE. Попробуйте указать один. Значение по умолчанию не кажется надежным. Параметры uart_set_pin () слева направо: TXD, RXD, RTS, CTS.
3 Установите драйвер uart
Для установки используйте функцию uart_driver_install (), прототип функции выглядит следующим образом:
esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int queue_size, QueueHandle_t *uart_queue, int intr_alloc_flags)
Очередь сообщений может иметь значение NULL, а длина — 0. Если событие прерывания не обрабатывается, последний параметр также равен 0;
Если tx_buffer_size равен 0, то есть буфер отправки отсутствует, при uart_write_bytes () он будет блокироваться и ждать, чтобы данные были отправлены перед возвратом.
rx_buffer_size не может быть пустым, предпочтительно целым числом, кратным UART_FIFO_LEN (128).
Последовательные чтение и запись данных
Отправить данные
Отправляйте данные через uart_write_bytes (). Если буфер отправки не установлен, данные будут возвращены после отправки. Если буфер отправки установлен, отправляемые данные будут скопированы в буфер, а затем возвращены. Программа обслуживания прерывания uart поместит буфер отправки в Данные перемещаются в tx FIFO, а затем отправляются.
uart_write_bytes_with_break () также является программой-отправителем, но она установит низкий уровень передачи на некоторое время после отправки данных (выполнение задачи RTOS как единое целое)
uart_tx_chars () также является программой-отправителем, но она будет напрямую записывать данные в аппаратный Tx FIFO и возвращать длину записанных данных.
uart_wait_tx_done () проверит состояние аппаратного Tx FIFO и вернется, когда он пуст или истекло время ожидания.
// Wait for packet to be sent
const int uart_num = UART_NUM_2;
ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // wait timeout is 100 RTOS ticks (TickType_t)
Получать данные
Когда последовательный порт получает данные, они будут сохранены в Rx FIFO, и мы можем прочитать их через uart_read_bytes (). Эта функция будет блокироваться и оставаться там до тех пор, пока не прочитает требуемые байты или не истечет время ожидания.
Конечно, мы также можем сначала получить длину данных в FIFO [uart_get_buffered_data_len ()], а затем прочитать соответствующее содержимое, чтобы не вызывать ненужную блокировку.
Если вам не нужно содержимое FIFO, вы можете вызвать: uart_flush ().
Используйте GPIO16 как TXD, GPIO17 как RXD, отправляйте Hello world каждые 2 секунды, закорачивайте эти два контакта, чтобы увидеть результат.
Справочный код:
Establish Serial Connection with ESP32
Establishing a serial connection with the ESP32 target device could be done using a USB-to-UART bridge.
Some development boards have the USB-to-UART bridge installed. If a board does not have a bridge then an external bridge may be used.
USB-to-UART Bridge on Development Board
For boards with an installed USB-to-UART bridge, the connection between the personal computer and the bridge is USB and between the bridge and ESP32 is UART.
Development Board with USB-to-UART Bridge
External USB-to-UART Bridge
Sometimes the USB-to-UART bridge is external. This is often used in small development boards or finished products when space and costs are crucial.
External USB-to-UART Bridge
Flash using UART
This section provides guidance on how to establish a serial connection between ESP32 and PC using USB-to-UART Bridge, either installed on the development board or external.
Connect ESP32 to PC
Connect the ESP32 board to the PC using the USB cable. If device driver does not install automatically, identify USB-to-UART bridge on your ESP32 board (or external converter dongle), search for drivers in internet and install them.
Below is the list of USB to serial converter chips installed on most of the ESP32 boards produced by Espressif together with links to the drivers:
Please check the board user guide for specific USB-to-UART bridge chip used. The drivers above are primarily for reference. Under normal circumstances, the drivers should be bundled with an operating system and automatically installed upon connecting the board to the PC.
For devices downloaded using a USB-to-UART bridge, you can run the following command including the optional argument to define the baud rate.
You can change the flasher baud rate by replacing BAUD with the baud rate you need. The default baud rate is 460800 .
If the device does not support the auto download mode, you need to get into the download mode manually. To do so, press and hold the BOOT button and then press the RESET button once. After that release the BOOT button.
Check port on Windows
Check the list of identified COM ports in the Windows Device Manager. Disconnect ESP32 and connect it back, to verify which port disappears from the list and then shows back again.
Figures below show serial port for ESP32 DevKitC and ESP32 WROVER KIT
USB to UART bridge of ESP32-DevKitC in Windows Device Manager
Two USB Serial Ports of ESP-WROVER-KIT in Windows Device Manager
Check port on Linux and macOS
To check the device name for the serial port of your ESP32 board (or external converter dongle), run this command two times, first with the board / dongle unplugged, then with plugged in. The port which appears the second time is the one you need:
macOS users: if you don’t see the serial port then check you have the USB/serial drivers installed. See Section Connect ESP32 to PC for links to drivers. For macOS High Sierra (10.13), you may also have to explicitly allow the drivers to load. Open System Preferences -> Security & Privacy -> General and check if there is a message shown here about “System Software from developer …” where the developer name is Silicon Labs or FTDI.
Adding user to dialout on Linux
The currently logged user should have read and write access the serial port over USB. On most Linux distributions, this is done by adding the user to dialout group with the following command:
on Arch Linux this is done by adding the user to uucp group with the following command:
Make sure you re-login to enable read and write permissions for the serial port.
Verify serial connection
Now verify that the serial connection is operational. You can do this using a serial terminal program by checking if you get any output on the terminal after resetting ESP32.
The default console baud rate on ESP32 is 115200.
Windows and Linux
In this example we will use PuTTY SSH Client that is available for both Windows and Linux. You can use other serial programs and set communication parameters like below.
Run terminal and set identified serial port. Baud rate = 115200 (if needed, change this to the default baud rate of the chip in use), data bits = 8, stop bits = 1, and parity = N. Below are example screenshots of setting the port and such transmission parameters (in short described as 115200-8-1-N) on Windows and Linux. Remember to select exactly the same serial port you have identified in steps above.
Setting Serial Communication in PuTTY on Windows
Setting Serial Communication in PuTTY on Linux
Then open serial port in terminal and check, if you see any log printed out by ESP32. The log contents will depend on application loaded to ESP32, see Example Output.
Close the serial terminal after verification that communication is working. If you keep the terminal session open, the serial port will be inaccessible for uploading firmware later.
macOS
To spare you the trouble of installing a serial terminal program, macOS offers the screen command.
You should see similar output:
The output will vary depending on the type and the number of boards connected to your PC. Then pick the device name of your board and run (if needed, change “115200” to the default baud rate of the chip in use):
Replace device_name with the name found running ls /dev/cu.* .
What you are looking for is some log displayed by the screen. The log contents will depend on application loaded to ESP32, see Example Output. To exit the screen session type Ctrl-A + \ .
Do not forget to exit the screen session after verifying that the communication is working. If you fail to do it and just close the terminal window, the serial port will be inaccessible for uploading firmware later.
Example Output
An example log is shown below. Reset the board if you do not see anything.
If you can see readable log output, it means serial connection is working and you are ready to proceed with installation and finally upload an application to ESP32.
For some serial port wiring configurations, the serial RTS & DTR pins need to be disabled in the terminal program before the ESP32 will boot and produce serial output. This depends on the hardware itself, most development boards (including all Espressif boards) do not have this issue. The issue is present if RTS & DTR are wired directly to the EN & GPIO0 pins. See the esptool documentation for more details.
If you got here from Step 5. First Steps on ESP-IDF when installing s/w for ESP32 development, then you can continue with Step 5. First Steps on ESP-IDF .
Проект ESP USB Bridge позволяет использовать ESP32-S2 или ESP32-S3 в микросхемах USB to UART/JTAG
ESP USB Bridge от Espressif — это проект, основанный на ESP-IDF, в котором используется USB-интерфейс ESP32-S2 или ESP32-S3 для использования платы в качестве отладочной платы USB-UART или USB-JTAG.
Он может служить заменой отладочных плат USB-TTL на базе CH340 или CP2104, например, использоваться с OpenOCD в режиме JTAG bridge, а также прошивать файл прошивки UF2 на целевую плату.
Хост-компьютер, плата ESP32-S2/S3 с прошивкой ESP USB Bridge и целевая плата с USB и/или JTAG
Как уже упоминалось, есть три основных варианта использования:
- Режим последовательного моста с терминальной программой или инструментом для прошивки, например, esptool. В этом случае он работает как обычная отладочная плата USB-TTL.
- Режим моста JTAG для отладки JTAG с помощью OpenOCD, и если целевая плата основана на ESP32, вы можете использовать проект openocd-esp32.
- Запоминающее устройство, на котором к плате может получить доступ файловый менеджер на хост-компьютере. Одним из конкретных вариантов использования в этом режиме является копирование файла прошивки UF2, который затем можно прошить на целевой микроконтроллер с помощью ESP32-S2/S3. В настоящее время ESP USB Bridge поддерживает только прошивку UF2 для микроконтроллеров Espressif.
Исходный код, выпущенный под лицензией Apache 2.0, и инструкции можно найти на Github. Вам понадобится плата ESP32-S2 или ESP32-S3, которая предоставляет контакты USB DM/DP, а также интерфейсы UART и/или JTAG. Что-то вроде Lolin S2 Mini должно выполнять работу в качестве платы USB-UART с USB и UART, доступными в разъемах, но если вам нужен JTAG, плата ESP32-S3-USB-OTG должна быть лучшим вариантом. Для сборки проекта требуется ESP-IDF 4.3 или выше.
Скачать драйвер для ESP32 (CP2102)
Убедитесь, что ваша плата имеет микросхему CP2102 (существует также драйвер для платы с микросхемой CH9102X).
CP2102 является мостом USB – UART, который позволяет ESP32 вести обмен данными с ПК через USB. Чип CP2102 обведен на рисунке красным кругом.
Установка драйвера для CP2102 в Windows
1. Подключаем ESP32 к ПК с помощью USB-кабеля.
2. Скачиваем архив с драйвером. Ниже приводятся ссылки на драйверы для ОС Windows и MacOS.
3. Распаковываем архив.
4. Запускаем файл CP210xVCPInstaller_x64.exe для 64-битной или CP210xVCPInstaller_x86.exe для 32-битной версии Windows.
Нажмимаем «Далее» в окне приветствия инсталлятора.
Соглашаемся с лицензией.
Нажимаем «Готово» в окне сообщения об успешной установке.
Установка драйвера закончена.
Проверка работы драйвера для ESP32
При правильно установленном драйвере в диспетчере устройств можно увидеть появившийся виртуальный COM-порт (при подключенном ESP32).
Запускаем диспетчер устройств (Панель управления >> Система и безопасность >> Система >> Диспетчер устройств) и проверяем наличие драйвера CP210x USB to UART в разделе «Порты COM и LPT». Номер COM-порта может отличаться от приведенного на рисунке.
USB to UART драйвер CP210x для ESP32
Скачать драйвер CP210x для Windows
Скачать драйвер CP210x для Mac OS
Драйвер для CP210x в Linux (Linux Mint, Ubuntu, Lubuntu, Kubuntu, Debian, Arch Linux, Manjaro, Fedora, MX Linux, openSUSE . ) присутствует по умолчанию и не требует установки.