#include <stdio.h>
#include <modbus.h>
#define MB_BITRATE 9600
#define MB_DATABITS 8
#define MB_STOPBITS 1
#define MB_PARITY 'N'
#define MB_SLAVE_ADDRESS 2
#define MB_REG_BASE 0
#define MB_REG_COUNT 1
int main ()
{
modbus_t *ctx;
uint16_t tab_reg[MB_REG_BASE+MB_REG_COUNT];
int n, i;
int errno = 0;
ctx = modbus_new_rtu("/dev/ttyUSB0",
MB_BITRATE,
MB_PARITY,
MB_DATABITS,
MB_STOPBITS);
if (ctx == NULL) {
fprintf(stderr,
"Unable to create the libmodbus context on serial port %s\n",
"/dev/ttyUSB0");
return -1;
}
printf("connection created \n");
if ( modbus_set_slave(ctx, MB_SLAVE_ADDRESS) )
{
fprintf(stderr, "Failed to set modbus slave address\n");
errno = -1;
goto fail;
}
printf("slave set \n");
if ( modbus_connect(ctx))
{
fprintf(stderr,
"Unable to connect to modbus server");
errno = -1;
goto fail;
}
printf("connted to slave \n");
printf("Starting write \n");
n = modbus_write_register(ctx, 0, 255); //I suppose 2nd parameter is the memory address.
printf("Value of N is %d \n", n);
if ( n <= 0 )
{
fprintf(stderr, "Unable to read modbus registers\n");
errno = -1;
goto fail;
}
for ( i=MB_REG_BASE; i<MB_REG_BASE+n; i++ )
{
printf ( "[%d]: %d\n", i, tab_reg[i]);
}
fail:
modbus_close(ctx);
modbus_free(ctx);
return errno;
}