Соединяем две Piranha ESP32 по UDP и передаём массив данных
Общие сведения:
В этом проекте мы соединим две Piranha ESP32 по WiFi и будем передавать массивы данных с одной на другую при помощи протокола UDP.
UDP (англ. User Datagram Protocol) — протокол пользовательских датаграмм. UDP предоставляет ненадёжный сервис, и датаграммы могут прийти не по порядку, дублироваться или вовсе исчезнуть без следа. UDP подразумевает, что проверка ошибок и исправление либо не нужны, либо должны исполняться в приложении.
Фомат массива
При передаче и получении информации используются байты. Одним байтом возможно передать число от 0 до 255, что соответствует типу данных byte и uint8_t , а так же от -128 до 127, что соответствует типам char и int8_t . При передаче б_о_льших чисел используется трюк с преобразованием типов адресов (указателей). Например, если это массив с типом данных int (что соответствует четырём байтам для esp32), то каждый элемент массива отсылается побайтово. Таким образом число типа int i = -1 будет передано как четыре байта со значениями 0xff . Далее принимающая сторона преобразует байты обратно в int . Этот приём работает только при приёме/передаче данных представляющих непрерывные структуры в памяти, таких как массивы. Со связанными списками это приём не работает. При таком подходе очень легко выйти за границы массива, поэтому при передаче данных передаётся и их размер в байтах полученный при помощи оператора sizeof . Принимающая сторона вычисляет количество элементов приводя количество полученных байтов к размеру типа ожидаемых данных, так же при помощи оператора sizeof .
При передаче и приёме данных используйте одинаковые типы данных! В примерах используется проверка размера данных, но всё равно что-то может пойти не так. Если принимающая сторона будет ожидать int , а передающая сторона передаст char , то может произойти чтение или запись в ненадлежащую область памяти, от чего ESP32 может зависнуть, перезагружаться или работать непредсказуемо.
Видео:
Нам понадобится:
Подключение:
Скетчи проекта для прямого подключения (esp32 — esp32):
Скетч для ESP32 в качестве UDP сервера
В данном скетче отправка данных осуществляется при помощи функции printf , а получение при помощи преобразования указателей. Это сделано для демонстрации двух способов. В первом случае получатель должен парсить строку, во втором отправитель должен отсылать только байты необходимых данных.
Скетч для ESP32 в качестве UDP клиента
В скетче клиента отправка данных осуществляется побайтово, а приём при помощи парсинга строки.
Скетчи проекта для подключения через WiFi роутер (esp32 — роутер — esp32):
При таком подключении необходимо сначала загрузить скетч с сервером UDP. В последовательный порт будет выведен IP-адрес сервера, который необходимо указать в скетче клиента. Так же в обоих сетчах необходимо указать название точки доступа и пароль. Обе ESP32 должны находиться в одной сети. При таком подключении передача данных немного медленее, чем примое подключение (оверхед роутера на маршрутизацию пакетв).
Async udp arduino
Table of Contents
This AsyncUDP_Teensy41 library is a fully asynchronous UDP library, designed for a trouble-free, multi-connection network environment, for Teensy 4.1 using QNEthernet Library. The library is easy to use and includes support for Unicast, Broadcast and Multicast environments.
This library is based on, modified from:
to apply the better and faster asynchronous feature of the powerful ESPAsyncUDP Library into Teensy 4.1 using QNEthernet Library.
Why Async is better
- Using asynchronous network means that you can handle more than one connection at the same time
- You are called once the request is ready and parsed
- When you send the response, you are immediately ready to handle other connections while the server is taking care of sending the response in the background
- Speed is OMG
- After connecting to a UDP server as an Async Client, you are immediately ready to handle other connections while the Client is taking care of receiving the UDP responding packets in the background.
- You are not required to check in a tight loop() the arrival of the UDP responding packets to process them.
Currently Supported Boards
- Teensy 4.1 using QNEthernet Library
- Arduino IDE 1.8.19+ for Arduino.
- Teensy core v1.56+ for Teensy 4.1
- QNEthernet Library version v0.13.0+ for Teensy 4.1 built-in Ethernet.
The suggested way to install is to:
Use Arduino Library Manager
The best way is to use Arduino Library Manager . Search for AsyncUDP_Teensy41 , then select / install the latest version. You can also use this link for more detailed instructions.
- Navigate to AsyncUDP_Teensy41 page.
- Download the latest release AsyncUDP_Teensy41-master.zip .
- Extract the zip file to AsyncUDP_Teensy41-master directory
- Copy the whole AsyncUDP_Teensy41-master folder to Arduino libraries’ directory such as
VS Code & PlatformIO:
- Install VS Code
- Install PlatformIO
- Install AsyncUDP_Teensy41 library by using Library Manager. Search for AsyncUDP_Teensy41 in Platform.io Author’s Libraries
- Use included platformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at Project Configuration File
1. For Teensy boards
To be able to compile and run on Teensy boards, you have to copy the files in Packages_Patches for Teensy directory into Teensy hardware directory (./arduino-1.8.19/hardware/teensy/avr/boards.txt).
Supposing the Arduino version is 1.8.19. These files must be copied into the directory:
- ./arduino-1.8.19/hardware/teensy/avr/boards.txt
- ./arduino-1.8.19/hardware/teensy/avr/cores/teensy/Stream.h
- ./arduino-1.8.19/hardware/teensy/avr/cores/teensy3/Stream.h
- ./arduino-1.8.19/hardware/teensy/avr/cores/teensy4/Stream.h
Whenever a new version is installed, remember to copy this file into the new version directory. For example, new version is x.yy.zz These files must be copied into the directory:
- ./arduino-x.yy.zz/hardware/teensy/avr/boards.txt
- ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy/Stream.h
- ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy3/Stream.h
- ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy4/Stream.h
HOWTO Fix Multiple Definitions Linker Error
The current library implementation, using xyz-Impl.h instead of standard xyz.cpp , possibly creates certain Multiple Definitions Linker error in certain use cases.
You can include this .hpp file
in many files. But be sure to use the following .h file in just 1 .h , .cpp or .ino file, which must not be included in any other file, to avoid Multiple Definitions Linker Error
HOWTO Setting up the Async UDP Client
Debug Terminal Output Samples
1. AsyncUdpNTPClient on TEENSY 4.1
This is terminal debug output when running AsyncUdpNTPClient on Teensy 4.1 using built-in QNEthernet. It connects to NTP Server «0.ca.pool.ntp.org» (IPAddress(208, 81, 1, 244)) using AsyncUDP_Teensy41 library, and requests NTP time every 60s. The packet is then received and processed asynchronously to print current UTC/GMT time.
2. AsyncUDPSendReceive on TEENSY 4.1
This is terminal debug output when running AsyncUDPSendReceive on Teensy 4.1 using built-in QNEthernet. It connects to NTP Server «time.nist.gov» (IPAddress(208, 81, 1, 244)) using AsyncUDP_Teensy41 library, and requests NTP time every 60s. The packet is then received and processed asynchronously to print current UTC/GMT time.
Debug is enabled by default on Serial. To disable, use level 0
You can also change the debugging level from 0 to 4
If you get compilation errors, more often than not, you may need to install a newer version of Arduino IDE, the Arduino STM32 core or depending libraries.
Sometimes, the library will only work if you update the STM32 core to the latest version because I am always using the latest cores /libraries.
- Initial porting and coding for Teensy 4.1 using built-in QNEthernet
- Add more examples.
- Add debugging features.
Contributions and Thanks
- Based on and modified from Hristo Gochkov’s ESPAsyncUDP. Many thanks to Hristo Gochkov for good ESPAsyncUDP Library
⭐️ ⭐️ Hristo Gochkov |
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
- Copyright 2016- Hristo Gochkov
- Copyright 2022- Khoi Hoang
Footer
© 2022 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
khoih-prog/AsyncUDP_WT32_ETH01
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Table of Contents
Important Change from v2.1.0
This AsyncUDP_WT32_ETH01 library is a fully asynchronous UDP library, designed for a trouble-free, multi-connection network environment, for WT32_ETH01 (ESP32 + LAN8720 Ethernet). The library is easy to use and includes support for Unicast, Broadcast and Multicast environments.
This library is based on, modified from:
to apply the better and faster asynchronous feature of the powerful AsyncUDP into WT32_ETH01.
Why Async is better
- Using asynchronous network means that you can handle more than one connection at the same time
- You are called once the request is ready and parsed
- When you send the response, you are immediately ready to handle other connections while the server is taking care of sending the response in the background
- Speed is OMG
- After connecting to a UDP server as an Async Client, you are immediately ready to handle other connections while the Client is taking care of receiving the UDP responding packets in the background.
- You are not required to check in a tight loop() the arrival of the UDP responding packets to process them.
Currently supported Boards
- WT32_ETH01 boards using ESP32-based boards and LAN8720 Ethernet
ESP32 Core 2.0.3+ for ESP32-based boards.
WebServer_WT32_ETH01 library 1.5.0+ . To install, check .
The suggested way to install is to:
Use Arduino Library Manager
The best way is to use Arduino Library Manager . Search for AsyncUDP_WT32_ETH01 , then select / install the latest version. You can also use this link for more detailed instructions.
- Navigate to AsyncUDP_WT32_ETH01 page.
- Download the latest release AsyncUDP_WT32_ETH01-master.zip .
- Extract the zip file to AsyncUDP_WT32_ETH01-master directory
- Copy the whole AsyncUDP_WT32_ETH01-master folder to Arduino libraries’ directory such as
VS Code & PlatformIO:
- Install VS Code
- Install PlatformIO
- Install AsyncUDP_WT32_ETH01 library by using Library Manager. Search for AsyncUDP_WT32_ETH01 in Platform.io Author’s Libraries
- Use included platformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at Project Configuration File
1. For fixing ESP32 compile error
To fix ESP32 compile error , just copy the following file into the ESP32 cores/esp32 directory (e.g. ./arduino-1.8.15/hardware/espressif/cores/esp32) to overwrite the old file:
HOWTO Fix Multiple Definitions Linker Error
The current library implementation, using xyz-Impl.h instead of standard xyz.cpp , possibly creates certain Multiple Definitions Linker error in certain use cases.
You can include this .hpp file
in many files. But be sure to use the following .h file in just 1 .h , .cpp or .ino file, which must not be included in any other file, to avoid Multiple Definitions Linker Error
HOWTO Use analogRead() with ESP32 running WiFi and/or BlueTooth (BT/BLE)
1. ESP32 has 2 ADCs, named ADC1 and ADC2
2. ESP32 ADCs functions
- ADC1 controls ADC function for pins GPIO32-GPIO39
- ADC2 controls ADC function for pins GPIO0, 2, 4, 12-15, 25-27
3.. ESP32 WiFi uses ADC2 for WiFi functions
In ADC2, there’re two locks used for different cases:
lock shared with app and Wi-Fi: ESP32: When Wi-Fi using the ADC2, we assume it will never stop, so app checks the lock and returns immediately if failed. ESP32S2: The controller’s control over the ADC is determined by the arbiter. There is no need to control by lock.
lock shared between tasks: when several tasks sharing the ADC2, we want to guarantee all the requests will be handled. Since conversions are short (about 31us), app returns the lock very soon, we use a spinlock to stand there waiting to do conversions one by one.
adc2_spinlock should be acquired first, then adc2_wifi_lock or rtc_spinlock.
- In order to use ADC2 for other functions, we have to acquire complicated firmware locks and very difficult to do
- So, it’s not advisable to use ADC2 with WiFi/BlueTooth (BT/BLE).
- Use ADC1, and pins GPIO32-GPIO39
- If somehow it’s a must to use those pins serviced by ADC2 (GPIO0, 2, 4, 12, 13, 14, 15, 25, 26 and 27), use the fix mentioned at the end of ESP_WiFiManager Issue 39: Not able to read analog port when using the autoconnect example to work with ESP32 WiFi/BlueTooth (BT/BLE).
HOWTO Setting up the Async UDP Client
Lines 11 to 175 in 38f1469
# define ASYNC_UDP_WT32_ETH01_DEBUG_PORT Serial |
// Use from 0 to 4. Higher number, more debugging messages and memory usage. |
# define _ASYNC_UDP_WT32_ETH01_LOGLEVEL_ 2 |
# include AsyncUDP_WT32_ETH01.h > |
// /////////////////////////////////////////// |
// Select the IP address according to your local network |
IPAddress myIP ( 192 , 168 , 2 , 232 ); |
IPAddress myGW ( 192 , 168 , 2 , 1 ); |
IPAddress mySN ( 255 , 255 , 255 , 0 ); |
// Google DNS Server IP |
IPAddress myDNS ( 8 , 8 , 8 , 8 ); |
// /////////////////////////////////////////// |
# include time.h > |
// 0.ca.pool.ntp.org |
IPAddress timeServerIP = IPAddress( 208 , 81 , 1 , 244 ); |
// time.nist.gov |
// IPAddress timeServerIP = IPAddress(132, 163, 96, 1); |
# define NTP_REQUEST_PORT 123 |
const int NTP_PACKET_SIZE = 48 ; // NTP timestamp is in the first 48 bytes of the message |
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets |
// A UDP instance to let us send and receive packets over UDP |
AsyncUDP Udp; |
// send an NTP request to the time server at the given address |
void createNTPpacket ( void ) |
< |
Serial. println ( » ============= createNTPpacket ============= » ); |
// set all bytes in the buffer to 0 |
memset (packetBuffer, 0 , NTP_PACKET_SIZE); |
// Initialize values needed to form NTP request |
// (see URL above for details on the packets) |
packetBuffer[ 0 ] = 0b11100011 ; // LI, Version, Mode |
packetBuffer[ 1 ] = 0 ; // Stratum, or type of clock |
packetBuffer[ 2 ] = 6 ; // Polling Interval |
packetBuffer[ 3 ] = 0xEC ; // Peer Clock Precision |
// 8 bytes of zero for Root Delay & Root Dispersion |
packetBuffer[ 12 ] = 49 ; |
packetBuffer[ 13 ] = 0x4E ; |
packetBuffer[ 14 ] = 49 ; |
packetBuffer[ 15 ] = 52 ; |
> |
void parsePacket (AsyncUDPPacket packet) |
< |
struct tm ts; |
char buf[ 80 ]; |
memcpy (packetBuffer, packet. data (), sizeof (packetBuffer)); |
Serial. print ( » Received UDP Packet Type: » ); |
Serial. println (packet. isBroadcast () ? » Broadcast » : packet. isMulticast () ? » Multicast » : » Unicast » ); |
Serial. print ( » From: » ); |
Serial. print (packet. remoteIP ()); |
Serial. print ( » : » ); |
Serial. print (packet. remotePort ()); |
Serial. print ( » , To: » ); |
Serial. print (packet. localIP ()); |
Serial. print ( » : » ); |
Serial. print (packet. localPort ()); |
Serial. print ( » , Length: » ); |
Serial. print (packet. length ()); |
Serial. println (); |
unsigned long highWord = word (packetBuffer[ 40 ], packetBuffer[ 41 ]); |
unsigned long lowWord = word (packetBuffer[ 42 ], packetBuffer[ 43 ]); |
// combine the four bytes (two words) into a long integer |
// this is NTP time (seconds since Jan 1 1900): |
unsigned long secsSince1900 = highWord 16 | lowWord; |
Serial. print ( F ( » Seconds since Jan 1 1900 = » )); |
Serial. println (secsSince1900); |
// now convert NTP time into )everyday time: |
Serial. print ( F ( » Epoch/Unix time = » )); |
// Unix time starts on Jan 1 1970. In seconds, that’s 2208988800: |
const unsigned long seventyYears = 2208988800UL ; |
// subtract seventy years: |
unsigned long epoch = secsSince1900 — seventyYears; |
time_t epoch_t = epoch; // secsSince1900 — seventyYears; |
// print Unix time: |
Serial. println (epoch); |
// print the hour, minute and second: |
Serial. print ( F ( » The UTC/GMT time is » )); // UTC is the time at Greenwich Meridian (GMT) |
ts = * localtime (& epoch_t ); |
strftime (buf, sizeof (buf), » %a %Y-%m-%d %H:%M:%S %Z » , &ts); |
Serial. println (buf); |
> |
void sendNTPPacket ( void ) |
< |
createNTPpacket (); |
// Send unicast |
Udp. write (packetBuffer, sizeof (packetBuffer)); |
> |
void setup () |
< |
Serial. begin ( 115200 ); |
while (!Serial); |
Serial. print ( » \n Starting AsyncUdpNTPClient on » + String (ARDUINO_BOARD)); |
Serial. println ( » with » + String (SHIELD_TYPE)); |
Serial. println (WEBSERVER_WT32_ETH01_VERSION); |
Serial. println (ASYNC_UDP_WT32_ETH01_VERSION); |
Serial. setDebugOutput ( true ); |
// To be called before ETH.begin() |
WT32_ETH01_onEvent (); |
// bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO, |
// eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE); |
// ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE); |
ETH. begin (ETH_PHY_ADDR, ETH_PHY_POWER); |
// Static IP, leave without this line to get IP via DHCP |
// bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0); |
ETH. config (myIP, myGW, mySN, myDNS); |
WT32_ETH01_waitForConnect (); |
// Client address |
Serial. print ( » AsyncUdpNTPClient started @ IP address: » ); |
Serial. println (ETH. localIP ()); |
// NTP requests are to port NTP_REQUEST_PORT = 123 |
if (Udp. connect (timeServerIP, NTP_REQUEST_PORT)) |
< |
Serial. println ( » UDP connected » ); |
Udp. onPacket ([](AsyncUDPPacket packet) |
< |
parsePacket (packet); |
>); |
> |
> |
void loop () |
< |
sendNTPPacket (); |
// wait 60 seconds before asking for the time again |
delay ( 60000 ); |
> |
Debug Terminal Output Samples
1. AsyncUdpNTPClient on ESP32_DEV with ETH_PHY_LAN8720
This is terminal debug output when running AsyncUdpNTPClient on WT32_ETH01 (ESP32 + LAN8720). It connects to NTP Server using AsyncUDP_WT32_ETH01 library, and requests NTP time every 60s. The packet is then received and processed asynchronously to print current UTC/GMT time.
Connect to NTP server time.windows.com (IP=168.61.215.74)
Connect to NTP server time.nist.gov (IP=132.163.96.1)
2. AsyncUDPSendReceive on ESP32_DEV with ETH_PHY_LAN8720
This is terminal debug output when running AsyncUDPSendReceive on WT32_ETH01 (ESP32 + LAN8720). It connects to NTP Server time.nist.gov (IP=132.163.96.1) using AsyncUDP_WT32_ETH01 library, and requests NTP time every 60s. The packet is received and processed asynchronously to print current UTC/GMT time. The ACK packet is then sent.
Debug is enabled by default on Serial. To disable, use level 0
You can also change the debugging level from 0 to 4
If you get compilation errors, more often than not, you may need to install a newer version of Arduino IDE, the Arduino STM32 core or depending libraries.
Sometimes, the library will only work if you update the STM32 core to the latest version because I am always using the latest cores /libraries.
- Initial port to to WT32_ETH01 (ESP32 + LAN8720)
- Add more examples.
- Add debugging features.
- Auto detect ESP32 core to use for WT32_ETH01
- Fix bug in WT32_ETH01 examples to reduce connection time
- Fix multiple-definitions linker error.
- Add example multiFileProject to demo for multiple-file project
Contributions and Thanks
- Based on and modified from Hristo Gochkov’s AsyncUDP. Many thanks to Hristo Gochkov for great AsyncUDP Library
⭐️ ⭐️ Hristo Gochkov |
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
Copyright 2018- Hristo Gochkov
Copyright 2021- Khoi Hoang
About
Fully Asynchronous UDP Library for WT32_ETH01 (ESP32 + LAN8720). The library is easy to use and includes support for Unicast, Broadcast and Multicast environments.