I am working on a project to communicate to use an arduino to act as a MODBUS master and connect to a RTU slave device utilizing RS-232. I am currently struggling to establish communication.
Hardware
Arduino MEGA
MAX3232 RS-232 to TTL Converter (purchased off Amazon)
Converter
The converter TX is connected to the Serial1 TX and and the converter RX Serial 1 RX. This looks correct to me based on checking the pin-out of the MAX3232 chip on the converter I got.
Software:
I have tried several different libraries but am currently trying to work with this one:
Modbus-Master-Slave-for-Arduino
I am slightly modified the example code as follows:
#include <ModbusRtu.h>
// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;
/**
* 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,Serial1,0); // this is master and RS-232 or USB-FTDI
/**
* This is an structe which contains a query to an slave device
*/
modbus_t telegram;
unsigned long u32wait;
void setup() {
Serial.begin( 9600 ); // baud-rate at 19200
Serial1.begin( 9600);
master.start();
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 = 0; // start address in slave
telegram.u16CoilsNo = 10; // 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.println("idle");
u8state = 0;
u32wait = millis() + 100;
}
break;
}
Serial.println(au16data[9]);
}
Right now I am just trying to get the Arduino to print holding register 9. I am just getting Zero out right now.
I am going to hook up an oscilloscope next and try to check the signals coming out of the arduino and out of the converter.
If anyone has a suggestion of a better library for a MODBUS Master RTU over RS-232, please let me know.