#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;
//写入Modbus寄存器
int registerAddress = 90; // 寄存器地址
int numRegisters = 10; // 寄存器数量
uint16_t writeValue_register[10];
uint16_t readValue_register[10];
modbus_set_slave(ctx, slaveId);
for (int i = 0; i < numRegisters; i++) {
writeValue_register[i] = i + 1; // 填充要写入的寄存器值
}
for (int i = 0; i < numRegisters; i++) {
cout <<"writeValue : " << i << writeValue_register[i] << endl;// show 来看一下
}
for (int i = 0; i < numRegisters; i++) {
modbus_set_slave(ctx, slaveId);
rc = modbus_write_register(ctx, registerAddress, uint16_t(writeValue_register[i]));
registerAddress++;
if (rc == -1) {
cerr << "Failed to write to register: "<< i<<" "<< modbus_strerror(errno) << endl;
system("pause");
//return -1;
}
}
//读取Modbus寄存器
registerAddress = 90;
modbus_set_slave(ctx, slaveId);
rc = modbus_read_registers(ctx, registerAddress, numRegisters, readValue_register);
if (rc == -1) {
std::cerr << "Failed to read Modbus registers: " << modbus_strerror(errno) << std::endl;
system("pause");
return -1;
}
else {
//打印读取到的寄存器值
for (int i = 0; i < 10; i++)
{
//此代k码段从从设备的首个寄存器开始读取10个寄存器,并将结果打印到屏幕上。
cout << "Register " << i << ": " << readValue_register[i] << endl;
}
}
modbus_close(ctx);
modbus_free(ctx);
system("pause");
return 0;
}