%ignore_pre_1%
上述示例代码使用了modbus协议中的读保持寄存器功能,通过TCP连接发送请求,接收响应并解析响应,最后关闭TCP连接。您可以根据实际情况修改代码中的SERVER_IP和DEVICE_ID等参数,以及读取的保持寄存器地址和数量。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 502
#define SERVER_IP "192.168.0.100"
#define DEVICE_ID 1
#define BUFFER_SIZE 1024
int main() {
// 创建TCP连接
int sockfd;
struct sockaddr_in server_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("Failed to create socket: %s\n", strerror(errno));
return 1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
printf("Failed to connect to server: %s\n", strerror(errno));
close(sockfd);
return 1;
}
printf("Connected to server successfully.\n");
// 准备modbus请求
unsigned char request[BUFFER_SIZE];
unsigned char response[BUFFER_SIZE];
int request_length, response_length;
// 读保持寄存器
int register_address = 0;
int register_count = 4;
request_length = modbus_build_request(request, DEVICE_ID, MODBUS_FC_READ_HOLDING_REGISTERS, register_address, register_count);
// 发送modbus请求
if (send(sockfd, request, request_length, 0) == -1) {
printf("Failed to send request: %s\n", strerror(errno));
close(sockfd);
return 1;
}
printf("Sent request successfully.\n");
// 接收modbus响应
response_length = recv(sockfd, response, BUFFER_SIZE, 0);
if (response_length == -1) {
printf("Failed to receive response: %s\n", strerror(errno));
close(sockfd);
return 1;
}
printf("Received response successfully.\n");
// 解析modbus响应
int register_value = modbus_get_response_value(response, response_length);
printf("Register value: %d\n", register_value);
// 关闭TCP连接
close(sockfd);
return 0;
}