Це відео не доступне.
Перепрошуємо.
Tech Note 137 - ESP32 a further insight into using the serial ports
Вставка
- Опубліковано 15 сер 2024
- The ESP32 has 3 serial ports, two of which are available for use on most development boards, here's an insight into how to use them, including a novel example of sending and receiving data to the same ESP32 !
Code examples: github.com/G6E...
Super useful! I hope they add even more hardware serial channels in future revisions. On the board I'm using, (1) is an e-paper screen and (2) is an SD card reader.
thank you so much. this is such an useful video. before i didn't know ESP32 has three (3) UART ports. now i know. thanks man!
I've literally been looking for this video for months and finally got it.. Thank you soo much for your hard work!
Thanks Dave, hope you are doing well. Everybody take care!
Thank you! I love the internet because of channels like this
Thanks Dave! Great videos on ESP32 serial communications! But just for the record '
' is a newline; '
' is a carriage return. Picking nits, I know!
Thanks David, you did a great job. Very well explained.
Whats the difference between Serial2.begin(9600, 8N1, 16, 17) and HardwareSerial Ser(2); Ser.begin(9600, 8N1, 16, 17);? I am using the first one without using HardwareSerial library and it works but am i not using hardware serial? or its the same thing
The same thing
Thanks David, this helped me to understand why I had some connection trouble when using wireless microcode installation process from ESPHOME , I used TX0 and RX0 :-)
Thank you very much for the excellent explanation.! very easy to understand.
Thanks for this. I commented yesterday on one of your vids then removed the comment when I'd figured out some useful code. This shows me a good insight. :)
Onboard Drones, hope this helps you.
It has, thanks. :) I had been searching for about a week on this, all other vids show how to connect different sensors but no direct explanation like this. Thanks again.
Ottimo video di grande aiuto. Grazie !
Great video, thanks a lot. I managed to use UART2 with an ESP32 board for an own project. However, I prefer to use my ESP Pico discovery board (from Erik Bartmann), using theESP32 PICO D4. The PICO seems not to accept the usage of the UART2, it doesn't run with the code. On the ESP32 DoIt DevKit V1 board code runs fine.
Is my assumption correct that the PICO doesn't support UART2 usage by code? Why is it so?
I think you stated it in one of your videos but I just don't remember where you said it.
The PICO only has two UART’s; it’s a cut down version, the other is used for flash memory access
спасибо) and separately thank you for the examples👍
Very helpful indeed. Thank you so much.
What to do if it receives sent values, but in addition some noise of random values from 0 to 255?
You shouldn’t get random values unless there is electrical noise on the connection between devices, you can try turning on parity by changing the format that will remove false data packets if the protuberance check fails. It does sound like you have a noisy electrical environment though. Make sure the earth at both ends is the same meaning connected together.
Excellent explanation. Thanks!
We can Conect them together over 100m twisted cable?
-
How we can make random connection over 4 pairs
-
I need to make two way talk over utp network cable
-
This feature needed when we have faults in termination pairs
-
As you see we have 8 pins but
may be all of them was reversed
-
Can you help me ❤
You can use twisted pair like CAT5 or 6 or 7 or better, as that will eliminate common mode noise, but really that’s not the way to do it, you’d need to use RS485 transceivers at each end often called MODBUS that is designed for high speed serial, but don’t expect Ethernet speeds. You’d need to use a minimum of two twisted pairs out of a CAT cable. You can’t use UTP as you can’t gain access to the lower part of the TCP/IP stack to extract the protocol and thereby send over serial lines, well not easily. I think using MODBUS transceivers is your answer, very low cost and reliable.
Thanks, very useful information.
Thanks Dave, very useful.
amazing video!! thank you so much!!!
Very good, congratulations
Thanks David. We could build a hardware key logger to capture a USB keyboard?
Can the esp32 serial port be used to upload sketches to an arduino wirelessly ? I have a mega2560(ch340) pro micro running my project and I would like to be able to update the sketch without having to plug in the usb cable.
Well it could but to initiate an upload to the Mega you’d need to setup a serial point to which a microUSB cable is attached and plugged into the Mega, then on the ESP initiate the programming sequence by pulling a GPIO pin low and connected to the cables DTR line then send the configuration data to the Mega and then the program, definitely possible but very complex to achieve
Hello Sir, I love your channel.
One question, can the hardware serial be used at the same time as the usb serial in order not to disconnect serial monitor everytime a new version of the program is flashed on the chip. I am in the process of designing a complex program and I reflash constantly. Most often than not, I forget to disconnect the serial monitor.
Stephen Remillard, in the video I mention not to use Serial port 0 as this is almost always reserved for device programming and for the Serial Monitor, so in answer to your question yes you can easily do what you need. If you notice in my code examples I initialise all 3 serial ports ready for use. Once operational the programming serial port can be disconnected leaving the other two to carry on sending and receiving data.
How would you receive mixed data like "char and integer" in one string
The data sent is all binary (0-255) so you’d need to interpret the received data according to its type, or format the data before sending in a struct framework with fields of different types then send the data (as binary) then use the same struct framework at the receiver and it will read and format the data into the correct types. It’s definitely possible to do.
Thank you for pointing me in the right direction. wasn't quit sure on how do do it. struck makes sense.
Monsieur David j'ai un problème au niveau de la programmation de la carte esp est ce que vous pouvez m'aider s'il vous plait ?
quel genre de problème, des messages d'erreur?
@@G6EJD non,je veux programmer la carte de tel sorte quand j'envoie 0 à la pompe commandé ,cette dérnière doit s'arreter ,j'ai essayée pas mal de fois et je sais pas où est le problème ,j'espère bien que vous pouvez m'aider
why is my esp32 only recieve negative value?
It depends on the data type and how you are interpreting the data. If your using a signed integer and the value received has the most significant bit set then it is interpreted as a negative. Eg a byte can hold a value between 0-255, but a signed integer using a byte interprets the values as 127 to -128, so what are you doing?
Thanks Dave, noob question, how do you add/include the HardwareSerial library in your Arduino IDE?
It’s now in-built if you have the latest version
Hello, thank you for interesting video. I tried this codes and working good, but i removed delay and codes doesn’t work anymore. What could be the reason? Thank you in advance.
You have to allow time for the UART to send the data which will depend on the baud rate so at 9600baud each character will take 1mS so there has to be at least that much delay before the next character is sent. The UART has a single character buffer to enable the character to be read whilst one is being received. Nothing is perfect. This is all normal behaviour.
@@G6EJD Thank you
Thanks for the video David, is it possible to change the GPIO for the default UART0 if I wanted to locate this on a different GPIO?
Yes you can, but when it comes to reprogramming you may find it a bit tricky to get attention to initiate the reprogramming, but solved by pressing reset just before programming starts, you may need to do this a few times and timing can be crucial, what happens is the programming port is in use by the sketch do the boot loader may not detect a request to begin an upload.
Hello, excellent video.
How can I do to send data from different sensors and receive them separately? For example:
Sensor 1 = 14.5
Sensor 2 = 45.3
You need to develop/use a protocol of some type, for example send 0x01 as a signal that data follows in the next byte(s), then the device address say 0x01 then the reading, so protocol is
0x01: start sequence
0xnn: Device address
0xrr: Device reading
0x01,0x02,0x23 would be sending a reading for device 2 with a reading of 23 then for the other device
0x01,0x01,0x44 and so on.
At the receiver end look for 0x01, if received expect the next byte to be the device address, then after that the reading.
Hello Sir. I have a question. I am having trouble because, if I just send "int" with value 0 continously, from time to time it will read a random number like an 8 or 40. Is the sender board sending data faster than the the receiving board can process it?
It could be, but more likely electrical noise
BTW 8 and 40 are both likely to be bit errors or noise
My idea is to read the wifi information that is in the serial.print and upload a network with them, would you have any tips?
It’s relatively easy to do, but depends a lot on which network you want to upload to, local, remote, non-ssl or ssl and so on.
I would like to connect several serial devices to several pins on the ESP32 using the same UART. Can I initialize the serial port and pin assignments within the main loop or function and change the pin assignments throughout the loop to read these multiple devices and process the data? Can I use one common TX pin and only change the RX pin assignment to save pins? Thanks,
You can use a common TX connected to all the remote RX pins, but you can’t connect remote TX pins to a single RX pin without some isolation because you’d effectively be connecting (remotely) TX pins together ie an output to and output, but that is easily solved by wiring a diode in series with each remote TX pin. You can also reconfigure the UART to separate pins or change the RX pin, but you can’t easily get data that is in the remote UART buffers so you’d need to establish a connection UART main to remote UART-1 complete the communications then move to remote UART-2 and so on, data management will be essential to keep the data aligned to the correct device.
@@G6EJD Wow, very quick response and very helpful as well as your video. To follow up your comments - my intended sensors are for voltage and current so I will likely read each sensor multiple times and average them before moving to the next sensor so I'm assuming that anything remaining in the serial device buffer should not be problematic?? Or to clarify if I do need to move between UARTS can I simply toggle back and forth between UART-1 and UART-2 to read data from a new sensor and that will close or purge any data remaining in the buffer? Thanks,
@@tomfalls1006 you can toggle between sensors but ideally you’ll need a regime where the sending device denotes the end of the data with a known termination character but the problem can be differentiating between data and end-of-data, there is an ASCII ETX byte you can use, I recommend you devise a transmission protocol to follow so you can be sure the data is complete, and you need to decide whether to send text or binary data for the readings eg 23.4 or 0x02,0x03,0x4 with an inferred decimal place or send a 4-byte flooring point, so something like bytes [deviceID][reading byte-1][reading byte-2][reading byte-3][reading byte-4][ETX] or more simply [deviceID][“23.4”][ETX] then when you receive ETX you know the end of transmission has occurred and can move on
Hi, thanks for your tutorial.
I used two ESP32OLED tests. One of them is the sender. every 3 seconds it reads an empty analog pin, displays the value on the screen and sends it via serial. The second (receiver) receives the value and immediately displays it on the screen. The pause after the display is 10ms. I noticed that the time between displaying on the transmitter and displaying it on the receiver takes about 1 second.
It's quite a long time. Does the serial broadcast require this time? Is it possible to change something to get the display without delay? Can you tell me how to do it?
Without seeing your code I don' know what's happening, but it's almost certainly to do with your OLED display refresh timing, have you checked the serial port to see when the data arrives? Most OLED's refresh quite quickly, so it will be a programme logic error or the driver is slow...
@@G6EJD This is probably not a problem with OLED refresh. Below is the transmitter and receiver LOOP section
SENDER LOOP
void loop() {
display.clear();
sensor_temperature = analogRead(15);
display.drawString(0, 0, "SENDER");
display.display();
display.drawString(50, 40, String(sensor_temperature));
display.display();
Sender.print(sensor_temperature);
delay(3000);
}
RECEIVER LOOP
void loop() {
while (Receiver.available()) {
int received_temperature = Receiver.parseFloat();
display.clear();
display.drawString(50, 40, String(received_temperature));
display.display();
display.drawString(0, 0, "RECEIVER");
display.display();
delay(10);
};
}
@@worldexplorerPL what is the baud rate your using? Also could the serial read function waiting for cr/lf and if not received it times out, turn on the timer function on the serial monitor port tick in bottom left and see where time delay is occurring or out diagnostic timer prints in the code.
@@worldexplorerPL Receiver.parseFloat() may need to be changed for speed purposes
@@G6EJD unfortunately I do not know how this function works and what it can possibly be replaced with
This video and the example codes helped me a lot. BUT: at 2:00, you have reversed the Rx and Tx designations in the command! It took me hours to figure this out (duh, should have been minutes), but please check this out. Again, this video has been very helpful for me, thanks! I'm surprised I even found a mistake!
I did that to illustrate that the definitions can be reversed as long as the PIN numbers are too, maybe that wasn’t as clear as it could have been. Most Chinese suppliers do not understand this subject and often rename pins to make it so Tx connects to Tx and not Tx to Rx which then makes taking a board at random extremely difficult because in actuality Tx has been renamed as Rx when it’s not!
@@G6EJD Look at your example:
"Sender.begin(115200, SERIAL_8N1, Sender_Txd_pin, Sender_Rxd_pin); // Define and start Sender serial port
It is just wrong, because Rx is before Tx in this command or constructor. You can't just arbitrarily change it. Try it!
Of course you can change them, your not understanding the principles. Are you Russian?
@@G6EJD I'm English, an engineer with decades of experience with UARTs, looking for a quick start on how they are implemented in ESP32.
I agree with yuchoy1 that you've make it very confusing. Your code does not match the constructor. I'm using V2 of the IDE, and its autocomplete feature immediately showed me that the constructor is the opposite way round to your comments. I trusted the tools instead of your comments, and it worked first time. I'm connecting to a USB-UART adapter, not another ESP32 that's been programmed with the same mistake.
I was illustrating that by far the majority of breakout boards with a serial port have had the designations of RX and Tx reversed so that they can be wired RX-RX and TX-TX now whilst convenient it is for learning purposes very confusing to those trying to understand. For example if someone picks up an external board they’d think TX is TX when in fact it’s RX! Using the Constructor in reverse is irrelevant as long as you know which element is which and I did cover that first. I’m trying to give confidence that they can be reversed when met with situations where the terminals are reversed by suppliers.
Hey this is very nice but for what i'm tryna do I want to send Serial data from an Esp32 to an Arduino Uno. But I can only find information on doing it the other way around. Do you know anywhere I could find out how to do this or could you make a video on the topic please? It would help out tremendously, thanks
There is no difference to which hardware platform you use the principles are the same, there is an example serial port in the Arduino Examples just use that for the UNO but remover to swap over the Tx and RX lines so that Tx-RX and Rx-Tx or do that in software by the pins definition.
Doh, done the mistake lots do... had some PCBs designed, good quality... yet messed up on hardware serial2. Cant seem to remap rx to tx respectively. On a d1 mini pro 32 kit. Do I need to reorder boards or is there something I can do?
The ESP32 allies all functions such as serial to be remapped to any input/output GPIO pins. How are you defining the serial2 pins? Are you trying to remap their programming port(1) rather than the second serial UART?
@@G6EJD just trying to change rx to 17 and tx to 16. Just for serial output to be read by a teensy board.
In which case you would just reverse the values eg Rx=16 Tx=17 becomes Rx=17 Tx=16 it vice versa or use any other pins as required. Don’t use built in values of RX or TX as the compiler will use those not your required pins, maybe use the pins numbers explicitly eg ,16,17); or ,17,16);
Thank you so much
Thanks Dave, health still ok ? Stay out of the corona I hope.
Yes I’m good, in total isolation u TIL hopefully all this covid-19 passes over
3:33 why not? Unit1.print("hello world");
Nice, thx
Can we do the same for esp8266, esp8266 to esp8266 serial communication?
Yes, but you have to use the library software serial and the ESP8266 has 2 UART's: Serial0 uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.
Serial1 uses UART1, TX pin is GPIO2. UART1 can not be used to receive data because normally it's RX pin is occupied for flash chip connection. To use Serial1, call Serial1.begin(baudrate).
Thank you
Can i made swap afer i set up my uart 0 to pin Gpio 15, 13 just to debug the code?
Yes that will work
@@G6EJD i try this code for resive data via serialString resive ;
String commant = " ";
void setup() {
Serial.begin(115200);
pinMode(15, OUTPUT);
pinMode(13, INPUT);
}
void loop() {
Serial.flush();
Serial.swap();
resive = Serial.readString( );//by swap uart from mesh gateway
Serial.swap();//normal uart
Serial.print("
from ----> ");
Serial.print(resive);
}
And this one for sender
String commant = " ";
int count ;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(15, OUTPUT);
Serial.swap() ;
}
void loop() {
// while(Serial.available()){
Serial.write("
234f
");
// }
}
It Work for some loops but it resive the sending massage like That. ؟
So what is the wrong with this codes?
@@hero-gl4zy you can’t use swap because UART1 is used to receive data as normally its RX pin is occupied for flash chip connection. You have to select the two unused UARTs and select unused pins. Change the uarts over by not using swap.
@@G6EJD in the prevouse code i used uart0 not 1
@@hero-gl4zy swap() uses UART0 and 1 just use two other UART’s and don’t use swap(); do what you might call manually not using a single function that is not doing what you need.
Hi, great video, thanks. I have a ESP32 project where I used up most of the available pins but still need to take a picture. How can I use this technic to connect to an ESP32-CAM to have it taking the picture and send to the main ESP32? Thanks
One of the problems with video is large amount of data to be moved around, I don’t know if you want to send static images or are trying to move live video frames around, but say an image of 640x480 pixels, this requires 640x3x480 bytes = 926100 bytes per frame, so at the maximum baud rate of 926100 bits/sec would take 10-secs to move an single frame of 640x480 24-bit colour. You can multiplex nearly every function eg serial or spi or I2c to any pin on the ESP32 so you could once programmed also use your TX and RX pins as additional GPIO pins but interacting with the ESP32 becomes quite difficult/ tedious, but possible nonetheless.
@@G6EJD Hi, thanks for taking the time to respond to my question. All I need is a single picture, say, ever 10 minutes or so and it will run unattended. I have code to take the picture into a variable and save it to a SD card. What would I do to transfer the contents of this variable to the main ESP32? Thanks again.
SmartIOT, open the file, then while not eof, read a byte, serial.write(byte), done
So about 5-lines, there are examples around of reading a file, you just need to setup the serial port then send data to it. Your receiving system would need to be permanently listen though unless synchronised or some start signal
If an array then for next then serial.write(array[i])
The code I have that captures the image is:
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
fb must be some sort of frame buffer, this variable is not initialized by me. I have code to save it to SD but in fact I would like not to use an SD card and transfer the image straight to the main ESP32 that will then transfer it to an FTP server. I already have the code for the ESP32-CAM to transfer the image to an FTP server. I don't know what fb is, may be it is char array. The code I have transfers whatever is in the fb to the FTP server so the ideal would have the same sort of variable been created at the main ESP32 side so I could apply the code I already have. What do you recommend on for this scenario? Thanks
Hello thank you very much for the video, i tried it with your github code when there is no other operation only sending the float temperature value it works fine but when there is other operation such as sensor reading then sending the value from the sensor it doesnt work for me could you please help me
What sort of problems do you have?
@@G6EJD I didnt receive any message fro the sender in the receiver
@@NickyAndre that’s be used the data format is wrong, what type of sensor reading are you sending
@@G6EJD Thank you very much you stick to me david i am pretty sure that my data format is correct i am reading Voutput of phototransistor which is in float data type then in the receiver also parseFloat i believe this correct right? Is there any impact of the processing time of both ESP32 it should be the same? because one is in fast processing time and one in low processing time.
Timing could be your problem, but only at the receiver end but the UART has a buffer so the data sent should be in the buffer until read. What distance is involved and is there good earthing between the devices as the transfer via serial is a very basic function that is reliable and should work without any issues.
No library?
Install it from the IDE Sketch Manage, easily found
if you've having trouble, don't waste your time. the UARTs on most esp32s are garbage, code that works on many systems even the crappy ones like electric imp have great difficulty working on esp32 for some reason. It's like the manufactures didn't think much about the UART anyway and you'll have a hard time getting it to work consistently
Have you ever looked at heltec esp32 lora boards? I been trying to figure out how to do this i need serial connection to a rockblock
Zachary Neuhaus, yes I have extensive experience of using the Heltec boards, but and both the Wireless stick and Wireless stick lite are power hungry, that aside they work very well. What are you trying to do, by the way a typical Lora transfer can take a few seconds to send.
@@G6EJD Hi David, So I have a Heltec esp32 Lora version 2 board. I have a rock block 9603. I want to wire the to block to the heltec but i can't establish a serial connection.