Skip to content

Instantly share code, notes, and snippets.

@karlp
Forked from jnareb/gist:2953631
Created June 19, 2012 12:10
Show Gist options
  • Save karlp/2953799 to your computer and use it in GitHub Desktop.
Save karlp/2953799 to your computer and use it in GitHub Desktop.
libmodbus - reading from many slave_ids via RTU
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus.h>
#define SM4_ID 3
#define P120_ID 2
int main(int argc, char *argv[])
{
modbus_t *ctx;
uint16_t buf[4];
int registers_address;
ctx = modbus_new_rtu("/dev/ttyUSB0", 9600, 'N', 8, 1);
modbus_connect(ctx);
modbus_set_slave(ctx, SM4_ID);
registers_address = 4000;
memset(buf, 0, 4*sizeof(uint16_t));
if (modbus_read_registers(ctx, registers_address, 2, buf) == -1) {
printf("Read failed: %s\n",
modbus_strerror(errno));
goto close;
}
usleep(500 * 1000);
modbus_set_slave(ctx, P120_ID);
registers_address = 7000;
memset(buf, 0, 4*sizeof(uint16_t));
if (modbus_read_registers(ctx, registers_address, 2, buf) == -1) {
printf("Read failed: %s\n",
modbus_strerror(errno));
}
close:
/* Close the connection */
modbus_close(ctx);
modbus_free(ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment