Hi, I'm a beginner in Arduino and the like. I'm trying to connect an Arduino Uno (Slave) which has a SW420 sensor to an Arduino Mega (Master) which has a 16x2 I2C LCD and uses RS485 module as a communication protocol. When trying to run the program, the "GET" command from the master is successfully received by the slave and the slave has successfully sent sensor data. But, on the master, the value received from the slave is always 0 as shown in the screenshot of my serial monitor. Is there someone who can help me solve this problem?
Yes, the sensor can work well, in the picture above the sensor value is successfully received by the slave node. But when sending to master, the value sent becomes 0;
first of all if you have 4 hardware UART's available you should not use swSerial really, but this is not your issue.
mySerial.print("GET%");
digitalWrite(enTxPin, LOW); // change pin to RX
swSerial is non-blocking' and if you are using RS485 bi-directional, you should make sure that the sending of the message has completed before you disable TX on the RS485
mySerial.print("GET%");
mySerial.flush();
delay(10); // wait another whole byte to be sure
digitalWrite(enTxPin, LOW); // change pin to RX
on the slave end.
if (mySerial.available()) {
String dataIN = "";
like this you maky not be reading the whole message to begin with. At 9600bps, a byte takes about 1 ms to transmit, but this is a different matter. The Serial reception method does not look very reliable to me, but that doesn't mean you may not be able to get it working at all. Still adding a small delay here as well will improve things.
if (mySerial.available()) {
delay(100); // you will wait for 3000ms for a response so we have some time to fill the buffer.
String dataIN = "";
Main thing to make sure is that the transmission of any data is complete before you switch the RS485 unit to RX and that you don't start responding until the reception of any dat has been completed. You don't want both units in TX mode at the same time, they may (and will) break.
so
if (dataIN.substring(0,3) == "GET"){
while (mySerial.available()) {
char c = mySerial.read();
delay(10);
}
digitalWrite(enTxPin, HIGH); // change pin to HIGH for TX
And rather than having the master defaulting as TX. Keep it in RX mode until you decide to transmit a request.