Connect nodemcu esp32 to multiple esp32 via RS485 modules

hello all.

i am trying to connect 2 nodemcu esp32 via rs485 modules but its not working. the esp32 and modules are connected in the following diagram:

the code used is the following:

#include <Arduino.h>
#define RXD2 16
#define TXD2 17
#define CTD2 22
void setup()
{
  // put your setup code here, to run once:
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.begin(115200);
  Serial.println("Begin Software...");
  Serial.println("Serial Txd is on pin: " + String(TX));
  Serial.println("Serial Rxd is on pin: " + String(RX));
  Serial.flush();
  pinMode(CTD2, OUTPUT);
  digitalWrite(CTD2, LOW);
}

void loop()
{
  while (Serial2.available())
  {
    int size = Serial2.available();
    String data = Serial2.readStringUntil('\n');
    Serial.println("RECEIVED: ");
    Serial.println(data);
  }
  if (Serial.available())
  {
    String data = Serial.readString();
    Serial.print("Sending: ");
    Serial.println(data);
    digitalWrite(CTD2, HIGH);
    Serial2.println(data);
    digitalWrite(CTD2, LOW);
  }
}

N.B first i tested this code (without the transmission pin "22") on a normal uart communication without rs485 and it was working fine. what can be the problem?
thanks in advance

try using Serial2.flush() to empty the transmit buffer before switching CTD2

  if (Serial.available())
  {
    String data = Serial.readString();
    Serial.print("Sending: ");
    Serial.println(data);
    digitalWrite(CTD2, HIGH);
    Serial2.println(data);
    Serial2.flush();             // <<<<< try
    digitalWrite(CTD2, LOW);
  }
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.