赞
踩
开发环境:vs2013、qt5.8.0、Libmodbus库
开发语言:C++
项目属性内分别引入modbus.dll、modbus.h、modbus-tcp.h、modbus.lib等头文件、动态库、静态库。具体操作与引入位置参考第一篇博客。
注意64位与32位系统、debug模式与release模式下分别对应不同的引入文件。
程序中引入头文件 #include "modbus.h"
1.建立PLC连接
- void pcPLC::connect()
- {
- std::cout << "modbus init success" << std::endl;
-
- // 设置PLC的IP地址与端口,建立TCP连接
- ctx = modbus_new_tcp("192.168.1.1", 502);
- if (ctx == NULL)
- {
- std::cout << "Unable to allocate libmodbus context " << modbus_strerror(errno) << std::endl;
- }
-
- std::cout << "modbus_connect(ctx) = " << modbus_connect(ctx) << std::endl;
- if (modbus_connect(ctx) == -1)
- {
- modbus_close(ctx);
- modbus_free(ctx);
- std::cout << "PLC connect failed " << modbus_strerror(errno) << std::endl;
- }
- else
- {
- std::cout << "PLC connect success " << std::endl;
- plcFlag = 1;
- }
- }
2.读取寄存器数据
- int pcPLC::readRegister(int num)
- {
- uint16_t regs[1];
- if (plcFlag != 0)
- {
- int res = modbus_read_registers(ctx, num, 1, regs);
- if (res == -1)
- {
- std::cerr << "Failed to read registers: " << modbus_strerror(errno) << std::endl;
- // 读取失败返回值0x0000
- regs[0] = 0x0000;
- }
- else
- {
- //std::cout << "Read Register " << num << " : " << regs[0] << std::endl;
- }
- }
- // 返回读取值
- return regs[0];
- }
3.数据写入寄存器
- void pcPLC::writeRegister( int num, int value)
- {
- if (plcFlag != 0)
- {
- if (modbus_write_register(ctx, num, value) == -1)
- {
- std::cerr << "Failed to write to register: " << modbus_strerror(errno) << std::endl;
- }
- else
- {
- //std::cout << "Changed Register " << num << " to : " << value << std::endl;
- }
- }
- }
4.断开PLC连接
- void pcPLC::disconnect()
- {
- if (plcFlag != 0)
- {
- modbus_close(ctx);
- modbus_free(ctx);
- plcFlag = 0;
- std::cout << "PLC disconnect success " << std::endl;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。