Good morning, I have an OPTA with RS485 and need to use the bus to communicate with an instrument.
The communication protocol is not Modbus. Data transmission is successful, but I am encountering issues with receiving data from the device.
Using the same commands with an Arduino Zero and a 485 converter works perfectly. What am I doing wrong?
I keep receiving "�" instead of the correct response.
#include <ArduinoRS485.h>
constexpr auto baudrate{ 9600 };
// Calculate preDelay and postDelay in microseconds for stable RS-485 transmission
constexpr auto bitduration{ 1.f / baudrate };
constexpr auto wordlen{ 9.6f }; // OR 10.0f depending on the channel configuration
constexpr auto preDelayBR{ bitduration * wordlen * 3.5f * 1e6 };
constexpr auto postDelayBR{ bitduration * wordlen * 3.5f * 1e6 };
void setup() {
Serial.begin(9600);
RS485.begin(9600);
}
void loop() {
//Scrive su 485 i dati letti dalla COM Opta
if (Serial.available() > 0) {
String datiRicevuti = Serial.readStringUntil('\r');
String datiSpediti=(datiRicevuti + '\r');
writeRS485(datiSpediti);
}
//Legge su 485 i dati letti dalla COM Slave
char* receivedData = readRS485();
if (receivedData != NULL) {
String str = String(receivedData);
Serial.println("- Receiving: "+str);
}
}
void writeRS485(String command) {
command += '\r';
RS485.noReceive();
RS485.beginTransmission();
delay(10);
Serial.println("- Sending: "+command);
RS485.print(command);
RS485.endTransmission();
}
char* readRS485() {
RS485.endTransmission();
RS485.receive();
delay(10);
static char data[100]="";
static int index = 0;
while (RS485.available() > 0) {
char received = RS485.read();
if (received == '\r') {
data[index] = '\0';
index = 0;
return data;
} else {
if (index < sizeof(data) - 1) {
data[index] = received;
index++;
}
}
}
return NULL;
RS485.noReceive();
}