Created
December 30, 2020 07:56
-
-
Save KunYi/f7fd517c4783fb4ea7026436ef4dc6ec to your computer and use it in GitHub Desktop.
create a test program with libmodbus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*--------------------------------------- | |
* | |
* modbus-rtu-master.c | |
* | |
*--------------------------------------- | |
*/ | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <modbus/modbus.h> | |
#define PORT_MODBUS ("/dev/ttyUSB0") | |
#define PORT_BAUDRATE (9600) | |
#define PORT_PARITY ('N') | |
#define PORT_DATABIT (8) | |
#define PORT_STOPBIT (1) | |
#define SLAVE_ID (16) | |
int main(int argc, char *argv[]) | |
{ | |
uint16_t tab_reg[64] = {0}; | |
modbus_t *ctx = NULL; | |
int rc; | |
int i; | |
ctx = modbus_new_rtu(PORT_MODBUS, | |
PORT_BAUDRATE, PORT_PARITY, PORT_DATABIT, PORT_STOPBIT); | |
if (ctx == NULL) | |
{ | |
fprintf(stderr, "Unable to allocate libmodbus contex\n"); | |
return -1; | |
} | |
modbus_set_debug(ctx, 1); // setting for debug message | |
modbus_set_slave(ctx, SLAVE_ID); | |
if (modbus_connect(ctx) == -1) | |
{ | |
fprintf(stderr, "Connection failed:%s\n", modbus_strerror(errno)); | |
return -1; | |
} | |
while (1) | |
{ | |
printf("\n----------------\n"); | |
#if 1 | |
// function 03 | |
rc = modbus_read_registers(ctx, 5, 7, tab_reg); | |
if (rc == -1) | |
{ | |
fprintf(stderr,"%s\n", modbus_strerror(errno)); | |
return -1; | |
} | |
else { | |
for (i=0; i < rc; i++) | |
{ | |
printf("reg[%d] = %d(0x%x)\n", i, tab_reg[i], tab_reg[i]); | |
} | |
} | |
#endif | |
#if 0 | |
// function 04 | |
rc = modbus_read_input_registers(ctx, 0, 3, tab_reg); | |
if (rc == -1) | |
{ | |
fprintf(stderr,"%s\n", modbus_strerror(errno)); | |
return -1; | |
} | |
else { | |
for (i=0; i < rc; i++) | |
{ | |
printf("reg[%d] = %d(0x%x)\n", i, tab_reg[i], tab_reg[i]); | |
} | |
} | |
#endif | |
sleep(1); | |
} | |
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