In a few weeks I will receive a sensor with a modbus interface (RS485) for my work. Unfortunately I have no experience in modbus programming. I tried to document myself and I wrote this program. My arduino is used as master and the sensor as slave. I want to read at address 0x0001 the value of the water flow. In the datasheet it says: "Read out corresponding registers with function code 4 (0x04) (Read Input Registers)".
Am I on the right way or are there improvements to be made until I get the sensor back?
//#include <ArduinoRS485.h>
//#include <ArduinoModbus.h>
#include <ModbusMaster.h>
#define MAX485_DE 3 // Pin names that are connected between the MAX485 TTL to RS-485 converter module and Arduino UNO.
#define MAX485_RE_NEG 2
ModbusMaster node; //object node for class ModbusMaster
// preTrasnmission() and postTrasmission() for making the Pins RE and DE of Max485 TTL to RS-485 convertor module high or low to Transmit or Receive data
void preTransmission()
{
digitalWrite(MAX485_RE_NEG, 1);
digitalWrite(MAX485_DE, 1);
}
void postTransmission()
{
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
}
void setup() {
// put your setup code here, to run once:
pinMode(MAX485_RE_NEG, OUTPUT);
pinMode(MAX485_DE, OUTPUT);
// intit receive mode
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
Serial.begin(9600);
node.begin(1, Serial);
node.preTransmission(preTransmission);
node.postTransmission(postTransmission);
}
void loop() {
// put your main code here, to run repeatedly:
float valueSensor;
valueSensor = node.readInputRegisters(0x0001, 1);
delay(1000);
}