若该文为原创文章,转载请注明原文出处
本文章博客地址:https://blog.csdn.net/qq21497936/article/details/116196923
长期持续带来更多项目与技术分享,咨询请加QQ:21497936、微信:yangsir198808
红胖子(红模仿)的博文大全:开发技术集合(包含Qt实用技术、树莓派、三维、OpenCV、OpenGL、ffmpeg、OSG、单片机、软硬结合等等)持续更新中…(点击传送门)
本文章讲解libmodbus。
libmodbus是一个免费软件库,可根据Modbus协议发送/接收数据。该库用C编写,并支持RTU(串行)和TCP(以太网)通信。
https://github.com/stephane/libmodbus
QQ群下载地址:1047134658(点击“文件”搜索“modbus”,群内与博文同步更新)
export PATH=$PATH:/mingw530_32/bin
cd /home/21497/compile/modbus
tar xvf libmodbus-3.1.6.tar.gz
cd libmodbus-3.1.6
./configure --prefix=/home/21497/compile/modbus/libmodbus-3.1.6/install
./configure --prefix=/home/21497/compile/modbus/libmodbus-3.1.6/install -build=x86
make -j16
make install
bool ModbusManager::testEnvAndRtu()
{
LOG << LIBMODBUS_VERSION_STRING;
// 步骤一:创建modbus RTU
modbus_t *pModbus = 0;
pModbus = modbus_new_rtu("com5",
115200,
'E',
8,
1);
if(!pModbus)
{
LOG << "Failed to modbus_new_rtu";
return false;
}
LOG << "Succeed to modbus_new_rtu";
// 步骤二: 485 RTU 模式
modbus_rtu_set_serial_mode(pModbus, MODBUS_RTU_RS485);
// 步骤三: 设置从机站号 1
modbus_set_slave(pModbus, 1);
// 步骤四:设置超时时间 100 ms
modbus_set_response_timeout(pModbus, 0, 100 * 1000);
// 步骤五: 连接 (注意:经过测试,只是485和232只是打开串口,并未交互)
int ret = modbus_connect(pModbus);
if(ret)
{
LOG << "Failed to modbus_connect, ret =" << ret;
return false;
}
LOG << "Succeed to modbus_connect, ret =" << ret;
// 步骤六:读取线圈
uint8_t buffer8t[10] = {0x00};
ret = modbus_read_bits(pModbus, 25, 10, buffer8t);
if(ret <= 0)
{
LOG << "Failed to modbus_read_registers, ret =" << ret;
return false;
}
LOG << "Succeed to modbus_read_registers, ret =" << ret;
// 步骤七:打印返回
for(int index = 0; index < 10; index++)
{
LOG << QString("%1").arg(buffer8t[index]);
}
// 步骤八:读取寄存器
uint16_t buffer16t[10] = {0x00};
ret = modbus_read_registers(pModbus, 95, 10, buffer16t);
if(ret <= 0)
{
LOG << "Failed to modbus_read_registers, ret =" << ret;
return false;
}
LOG << "Succeed to modbus_read_registers, ret =" << ret;
// 步骤九:打印返回
for(int index = 0; index < 10; index++)
{
LOG << QString("%1").arg(buffer16t[index]);
}
// 步骤十:读取寄存器
memset(buffer16t, 0, 10);
ret = modbus_read_input_registers(pModbus, 100, 1, buffer16t);
if(ret <= 0)
{
LOG << "Failed to modbus_read_registers, ret =" << ret;
return false;
}
LOG << "Succeed to modbus_read_input_registers, ret =" << ret;
// 步骤十一:打印返回
for(int index = 0; index < 10; index++)
{
LOG << QString("%1").arg(buffer16t[index]);
}
return true;
}
modbusDemo_v1.0.0_基础模板_读取线圈_读取寄存器简单测试.rar
若该文为原创文章,转载请注明原文出处
本文章博客地址:https://blog.csdn.net/qq21497936/article/details/116196923