以下是一个使用 libmodbus 库创建简单的MODBUS TCP服务器的C语言示例代码,该服务器可以处理读取保持寄存器(功能码0x03)的请求:
#include <stdio.h>
#include <stdlib.h>
#include <modbus.h>
#define SERVER_PORT 502
#define REGISTER_COUNT 10
int main() {
modbus_t *ctx;
int rc;
uint16_t registers[REGISTER_COUNT] = {0};
// 初始化MODBUS上下文,创建TCP服务器
ctx = modbus_new_tcp(\”0.0.0.0\”, SERVER_PORT);
if (ctx == NULL) {
fprintf(stderr, \”Unable to allocate libmodbus context\\n\”);
return -1;
}
// 设置服务器监听队列的最大长度
modbus_set_backlog(ctx, 5);
// 绑定并监听端口
if (modbus_tcp_listen(ctx, 1) == -1) {
fprintf(stderr, \”Unable to listen on port %d\\n\”, SERVER_PORT);
评论前必须登录!
注册