Hey all,
I’m new to IoT and development board and I need help reading a sensor communicating in RS485 with Arduino Mega.
I have the SparkFun RS485 breakout board and connected the TX to pin 19, RX to 18, and RTS to 8.
I’m using this code:
#include <ArduinoModbus.h>
#define RTS 8
// How often (in milliseconds) the sensors will be read.
const unsigned long REPORT_INTERVAL = 1000;
void setup() {
Serial.begin(9600);
pinMode(RTS, OUTPUT);
while(!Serial);
if (!ModbusRTUClient.begin(9600)) {
Serial.println("Failed to start Modbus RTU Client!");
while (1);
}
}
// The time at which the sensors were last read.
unsigned long lastMillis = 0;
void loop() {
digitalWrite(RTS,HIGH);
// If enough time has elapsed, read again.
if (millis() - lastMillis > REPORT_INTERVAL) {
lastMillis = millis();
// The Modbus RTU temperature and humidity sensor:
// Address: 0x01
// Holding Register: 0x00
// Read Length: 2
// Temperature = result[0]
// Humidity = result[1]
if (!ModbusRTUClient.requestFrom(0x01, HOLDING_REGISTERS, 0x00, 2)) {
Serial.print("failed to read registers! ");
Serial.println(ModbusRTUClient.lastError());
}
else {
// If the request succeeds, the sensor sends the readings, that are
// stored in the holding registers. The read() method can be used to
// get the raw temperature and the humidity values.
short rawtemperature = ModbusRTUClient.read();
short rawhumidity = ModbusRTUClient.read();
// The raw values are multiplied by 10. To get the actual
// value as a float, divide it by 10.
float temperature = rawtemperature / 100.0;
float humidity = rawhumidity / 100.0;
Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("Humidity: ");
Serial.println(humidity);
}
Serial.flush();
digitalWrite(RTS,LOW);
delay(100);
}
}
But I’m getting "failed to read registers! " error and some random characters, anyone has any idea why? The TX LED on the Mega is blinking and so is the RTS LED on the breakout board… I’d highly appreciate any help.