Page 1 of 1

Can i connect three ESP32 through serial communication?

Posted: Tue Jun 06, 2023 6:31 pm
by jaugual
I want to establish serial communication between three ESP32 devices. One ESP32 will act as the receiver, while the other two ESP32 devices will act as senders. The senders will transmit data using their respective Tx pins (4 and 17), which will be connected to the receiver's Rx pins (16 and 1). I have provided the code below, which uses the HardwareSerial.h library. Could you please review the code and let me know if it will work?

  1.  
  2.  
  3. //------------------------------------------ sender 1 ---------------------
  4.  
  5. #include Arduino.h
  6. #include <HardwareSerial.h>
  7.  
  8. HardwareSerial sender1Serial(2);
  9. #define SENDER1_TX_PIN 17
  10. #define SENDER1_RX_PIN 16
  11.  
  12. void setup() {
  13.     Serial.begin(115200);
  14.  
  15.      sender1Serial.begin(9600, SERIAL_8N1, SENDER1_RX_PIN, SENDER1_TX_PIN);
  16.  
  17. }
  18.    
  19. void loop() {
  20.     sender1Serial.print("Sender 1");
  21. }
  1. //------------------------------------------ sender 2 ---------------------
  2.  
  3. // Sender 2
  4. HardwareSerial sender2Serial(1); // UART1
  5. #define SENDER2_TX_PIN 4
  6. #define SENDER2_RX_PIN 5
  7. #include Arduino.h
  8. #include <HardwareSerial.h>
  9.  
  10.  
  11. void setup() {
  12.     Serial.begin(115200);
  13.  
  14.      sender2Serial.begin(9600, SERIAL_8N1, SENDER2_RX_PIN, SENDER2_TX_PIN);
  15.  
  16. }
  17.  
  18. void loop() {
  19.     sender2Serial.print("Sender 2");
  20. }
  1. //------------------------------------------ receiver ---------------------
  2.  
  3. #include <Arduino.h>
  4. #include <HardwareSerial.h>
  5.  
  6. HardwareSerial receiverSerial1(1); // UART1
  7. HardwareSerial receiverSerial2(2); // UART2
  8. #define RECEIVER_TX1_PIN 1
  9. #define RECEIVER_RX1_PIN 3
  10.  
  11. #define RECEIVER_TX2_PIN 17
  12. #define RECEIVER_RX2_PIN 16
  13.  
  14. void setup() {
  15.     Serial.begin(115200);
  16.  
  17.     receiverSerial1.begin(9600, SERIAL_8N1, RECEIVER_RX1_PIN, RECEIVER_TX1_PIN);
  18.     receiverSerial2.begin(9600, SERIAL_8N1, RECEIVER_RX2_PIN, RECEIVER_TX2_PIN);
  19. }
  20.  
  21. void loop() {
  22.     if (receiverSerial1.available()) {
  23.         String receivedData1 = receiverSerial1.readString();
  24.         Serial.println(receivedData1);
  25.     }
  26.  
  27.     if (receiverSerial2.available()) {
  28.         String receivedData2 = receiverSerial2.readString();
  29.         Serial.println(receivedData2);
  30.     }
  31. }