Skip to content

Instantly share code, notes, and snippets.

@LosantGists
Created February 27, 2020 21:37
Show Gist options
  • Save LosantGists/1e12abc82df404e18a08e247caabff61 to your computer and use it in GitHub Desktop.
Save LosantGists/1e12abc82df404e18a08e247caabff61 to your computer and use it in GitHub Desktop.
Example sketch that reads Modbus RTU data with an Arduino
#include <ArduinoModbus.h>
// How often (in milliseconds) the sensors will be read.
const unsigned long REPORT_INTERVAL = 1000;
void setup() {
Serial.begin(9600);
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() {
// 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 / 10.0;
float humidity = rawhumidity / 10.0;
Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("Humidity: ");
Serial.println(humidity);
}
delay(100);
}
}
@aaaniol
Copy link

aaaniol commented Jul 8, 2022

You don't know how much you saved my life hahaha, thx!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment