Skip to content

Instantly share code, notes, and snippets.

@karlp
Created September 7, 2011 19:27
Show Gist options
  • Save karlp/1201476 to your computer and use it in GitHub Desktop.
Save karlp/1201476 to your computer and use it in GitHub Desktop.
libmodbus sample master, always gets errno == 9 for all operations after it's connected (but still works just fine)
#include <stdio.h>
#include <errno.h>
#include <modbus.h>
int main(int argc, char **argv) {
modbus_t *mb;
uint16_t tab_reg[32];
int rc;
printf("THIS IS THE MASTER!!!\n");
if (argc > 1) {
printf("Using serial port from command line: %s\n", argv[1]);
mb = modbus_new_rtu(argv[1], 115200, 'N', 8, 1);
} else {
mb = modbus_new_rtu("/dev/ttyS0", 115200, 'N', 8, 1);
}
modbus_set_debug(mb, TRUE);
modbus_rtu_set_serial_mode(mb, MODBUS_RTU_RS232);
//rc = modbus_set_slave(mb, 0x69);
rc = modbus_set_slave(mb, 1);
if (rc != 0) {
fprintf(stderr, "set slave failed: %s\n", modbus_strerror(errno));
modbus_free(mb);
return -1;
}
rc = modbus_connect(mb);
if (rc != 0) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(mb);
return -1;
}
rc = modbus_write_register(mb, 1, 250);
if (rc != 0) {
fprintf(stderr, "write failed: %d %s\n", errno, modbus_strerror(errno));
// modbus_free(mb);
// return -1;
}
rc = modbus_write_register(mb, 0, 55);
if (rc != 0) {
fprintf(stderr, "write failed: %d %s\n", errno, modbus_strerror(errno));
/*
modbus_free(mb);
return -1;
*/
}
rc = modbus_read_registers(mb, 2, 1, tab_reg);
if (rc != 0) {
fprintf(stderr, "write failed: %d %s\n", errno, modbus_strerror(errno));
/*
modbus_free(mb);
return -1;
*/
}
printf("result was :%d\n", tab_reg[0]);
/* Read 5 registers from the address 987 */
/*
rc = modbus_read_registers(mb, 987, 5, tab_reg);
if (rc != 0 ) {
fprintf(stderr, "read failed: %s\n", modbus_strerror(errno));
modbus_free(mb);
return -1;
}
int i;
for (i = 0; i < 5; i++) {
printf("Register %d is %d (%c)\n", i, tab_reg[i], tab_reg[i]);
}
*/
modbus_close(mb);
modbus_free(mb);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment