Serial send/receive issues - timing? coding?

Hello,

The following is just a simplified test I’m running. I’ve got 2 Arduinos communicating via hardware serial, and sharing pretty much the same code (see below). In principle the master sends 111 then waits for a response (112 from slave). Yet even though the enable pins (I’m using RS485) are set low on the slave, no value seems to be getting through.

I’ve tested the Arduinos with other sketches designed to just send a byte array from master to slave, and that works (the slave prints a confirmation response). It works when I reverse the roles too. But in this case the slave isn’t even getting a response, so I’m guessing this has to do either with the high/low timing on the enable pins, or with the code.

Any help would be vastly appreciated, I’m trying to complete an art installation by the end of August. Thank you so much!

MASTER

const int pinEnable = 2;
byte hello = 111;
byte inRead = 0;
boolean received = true;

void setup ()
{
  pinMode(pinEnable,OUTPUT);
   Serial.begin(57600);
}

void check () {
  digitalWrite(pinEnable, LOW);
  inRead = Serial.read();
  if (inRead == 112) {
    received = true;
  }  
}
  
void loop() {
  check();
  if (received == true) {
    Serial.write(inRead);
    digitalWrite(pinEnable, HIGH);
    Serial.write(hello);
    digitalWrite(pinEnable, LOW);
    received = false;
  }
}

SLAVE

const int pinEnable = 2;
byte helloBack = 112;
byte inRead = 0;
boolean received = true;

void setup ()
{
  pinMode(pinEnable,OUTPUT);
   Serial.begin(57600);
}

void check () {
  digitalWrite(pinEnable, LOW);
  inRead = Serial.read();
  if (inRead == 111) {
    received = true;
  }  
}
  
void loop() {
  check();
  if (received == true) {
    delay(300);
    Serial.write(inRead);
    digitalWrite(pinEnable, HIGH);
    Serial.write(helloBack);
    digitalWrite(pinEnable, LOW);
    received = false;
  }
}

How are you implementing RS-485? Are you using your own transceivers or some ready made parts?

Can we assume that pin 2 is connected to the RS-485 TX/RX pin and that you believe a low signal puts the transceiver into receive?

In the Master code, are you aware that the Serial.write(inRead) in the loop will not transmit data since the TX enable pin is not high? Might be best to wrap your serial.write and reads into an RS485Read and write routine that sets the pin properly. That you you will not get a mismatch. Something like:

RS485_write(byte num) {
    digitalWrite(pinEnable, HIGH);
    inRead = Serial.write(num);
}

int RS485_read(byte num) {
    digitalWrite(pinEnable, LOW);
    return(Serial.read());
}

I thought one of the changes is that serial is now asynchronous. So you can not tell when the Serial write occurs, the pins could be up or done. Personally, I think there needs to be a sync mode as well.