【实用】libmodbus周期性读写线圈Coils实例
安装libmodbus
Ubuntu20.04
apt install libmodbus-dev libmodbus5
源码
#include <stdio.h>
#include <modbus.h>
#include <unistd.h> // 用于 sleep 函数
#include <errno.h>
#define IO_MAX_PER_SLAVE (16)
int main() {
modbus_t *ctx;
uint8_t tab_reg[IO_MAX_PER_SLAVE]; // 用于存储读取的寄存器
// 创建 Modbus TCP 上下文
//ctx = modbus_new_tcp("192.168.1.12", 502); // 替换为你的从站 IP 地址和端口
ctx = modbus_new_tcp("192.168.3.239", 502);
if (ctx == NULL) {
fprintf(stderr, "Unable to create the libmodbus context\n");
return -1;
}
modbus_set_debug(ctx,0);
// 启用 TCP Keepalive
//modbus_set_tcp_keepalive(ctx, 1); // 1 表示启用,0 表示禁用
// 设置从站 ID
modbus_set_slave(ctx, 1); // 替换为你的从站 ID
// 连接到从站
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
// 主循环:定期发送请求
uint8_t loop = 0;
while (1) {
printf("Write Coils value: ");
for(int i=0;i<IO_MAX_PER_SLAVE;i++) {
tab_reg[i] = 0;
if(i<=loop)
tab_reg[i] = 1;
printf(" %02X ", tab_reg[i]);
}
printf("\n");
int rc1 = modbus_write_bits(ctx, 0, IO_MAX_PER_SLAVE, tab_reg);
if (rc1 == -1) {
fprintf(stderr, "Failed to write coils: %s\n", modbus_strerror(errno));
// 尝试重新连接
modbus_close(ctx);
//ctx = modbus_new_tcp("192.168.1.12", 502);
ctx = modbus_new_tcp("192.168.1.13", 502);
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Reconnection failed: %s\n", modbus_strerror(errno));
break;
}
} else {
printf("Write Coils value: OK! \n");
}
// 读取一个寄存器
int rc = modbus_read_bits(ctx, 0, IO_MAX_PER_SLAVE, tab_reg); // 从地址 0 开始读取 16 个coils
if (rc == -1) {
fprintf(stderr, "Failed to read coils: %s\n", modbus_strerror(errno));
// 尝试重新连接
modbus_close(ctx);
//ctx = modbus_new_tcp("192.168.1.12", 502);
ctx = modbus_new_tcp("192.168.3.239", 502);
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Reconnection failed: %s\n", modbus_strerror(errno));
break;
}
} else {
printf("Read Coils value: ");
for(int i=0;i<IO_MAX_PER_SLAVE;i++)
printf(" %02X ", tab_reg[i]);
printf("\n");
}
// 每隔 2 秒发送一次请求
loop++;
loop = loop%16;
sleep(2);
}
// 关闭连接并释放资源
modbus_close(ctx);
modbus_free(ctx);
return 0;
}
makefile
#CROSS_COMPILE := aarch64-linux-gnu-
CC := $(CROSS_COMPILE)gcc
PROG := modbus
SRC := $(PROG).c
all:
$(CC) $(SRC) -I/usr/include/modbus -lmodbus -o $(PROG)
clean:
rm -fr *.o modbus
1905

被折叠的 条评论
为什么被折叠?



