前言
本文章講解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
是在mysy使用linux環境編譯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