modbus TCP 操作线圈,控制气密性测试仪
#include "modbus.h"
#include <iostream>
#pragma comment ( lib,"modbus.lib" )
using namespace std;
int main()
{
modbus_t* ctx;
const char* ipAddress = "192.168.1.2"; // Modbus TCP 从机的 IP 地址
const int port = 8000; // Modbus TCP 端口号
const int slaveId = 1; // 从机 ID
int rc;
//创建Modbus TCP上下文
ctx = modbus_new_tcp(ipAddress, port);
if (ctx == nullptr) {
std::cerr << "Failed to create Modbus context" << std::endl;
system("pause");
return -1;
}
//连接到Modbus从设备
if (modbus_connect(ctx) == -1) {
std::cerr << "Modbus connection failed: " << modbus_strerror(errno) << std::endl;
modbus_free(ctx);
system("pause");
return -1;
}
else
{
std::cout << "连接到Modbus从设备 成功" << std::endl;
}
// 读取线圈状态
const int coilAddress = 0; // 线圈地址
const int numCoils = 1; // 线圈数量
uint8_t coilStatus[numCoils];
modbus_set_slave(ctx, slaveId);
rc = modbus_read_bits(ctx, coilAddress, numCoils, coilStatus);
if (rc == -1) {
std::cerr << "Failed to read Modbus coils: " << modbus_strerror(errno) << std::endl;
system("pause");
return -1;
}
else {
std::cout << "Default coil 0 value: " << static_cast<int>(coilStatus[0]) << std::endl;
}
Sleep(1000);
// 写入线圈状态
const uint8_t writeValue = 1;
modbus_set_slave(ctx, slaveId);
rc = modbus_write_bit(ctx, coilAddress, writeValue);
if (rc == -1) {
std::cerr << "Failed to write Modbus coil: " << modbus_strerror(errno) << std::endl;
system("pause");
return -1;
}
else {
std::cout << "写入线圈成功,开始测试 " << std::endl;
}
// 关闭 Modbus 连接
//modbus_free(ctx);
Sleep(1000);
// 读取线圈状态
std::cout << "读取线圈状态" << std::endl;
modbus_set_slave(ctx, slaveId);
rc = modbus_read_bits(ctx, coilAddress, numCoils, coilStatus);
if (rc == -1) {
std::cerr << "Failed to read Modbus coils: " << modbus_strerror(errno) << std::endl;
system("pause");
return -1;
}
else {
std::cout << "Coil value: " << static_cast<int>(coilStatus[0]) << std::endl;
std::cout << "读取线圈状态 成功" << std::endl;
}
Sleep(1000);
modbus_close(ctx);
modbus_free(ctx);
system("pause");
return 0;
}