I'm trying to use the ModbusRTU.h library with SoftSerial.h using this example
I'm working with a 32-Input Modbus module, simply trying to poll the inputs to read On states (0=off, 1=on) of a holding register in this example. I have tested this module with other example (function 03) reads found in the manufacturer's instructions using Arduino Nano with MAX485 module, and Modbus Poll, a Modbus Master app for slave testing -- all works perfect.
My code:
#include <ModbusRtu.h>
#include <SoftwareSerial.h>
// data array for modbus network sharing
uint16_t au16data[32];
uint8_t u8state;
SoftwareSerial mySerial(2, 3);//Create a SoftwareSerial object so that we can use software serial. Search "software serial" on Arduino.cc to find out more details.
/**
* Modbus object declaration
* u8id : node id = 0 for master, = 1..247 for slave
* port : serial port
* u8txenpin : 0 for RS-232 and USB-FTDI
* or any pin number > 1 for RS-485
*/
Modbus master(0, mySerial); // this is master and RS-232 or USB-FTDI via software serial
/**
* This is an structe which contains a query to an slave device
*/
modbus_t telegram;
unsigned long u32wait;
void setup() {
Serial.begin(9600);
mySerial.begin(9600);//use the hardware serial if you want to connect to your computer via usb cable, etc.
master.start(); // start the ModBus object.
master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
u32wait = millis() + 1000;
u8state = 0;
}
void loop() {
switch( u8state ) {
case 0:
if (millis() > u32wait) u8state++; // wait state
break;
case 1:
telegram.u8id = 1; // slave address
telegram.u8fct = 3; // function code (this one is registers read)
telegram.u16RegAdd = 128; // start address in slave
telegram.u16CoilsNo = 32; // number of elements (coils or registers) to read
telegram.au16reg = au16data; // pointer to a memory array in the Arduino
master.query( telegram ); // send query (only once)
u8state++;
break;
case 2:
master.poll(); // check incoming messages
if (master.getState() == COM_IDLE)
{
Serial.print("STATE:");
Serial.println(master.getState()); // 0
Serial.print("ERROR:");
Serial.println(master.getLastError()); // 0 Errors
Serial.print("READ DATA:");
Serial.println(au16data[0]); // 0, never a 1 with input
u32wait = millis() + 1000;
u8state = 0;
}
break;
}
}
Is this more of the same problems from smarmengol?
I have the below array value properly selected to print I believe.
Serial.println(au16data[0]);//Register 1 value
I suppose there is no way to see/read the query hex frame being sent to the I/O module without a serial analyzer app, when using a library.