CH348结合开源ModBus协议组成串口温度采集服务器
目录
- 前言
- 开源项目libmodbus
- CH348 USB串口芯片
- 方案详情
前言
开源项目libmodbus
libmodbus作为免费的开发库,遵循标准Modbus协议的设备发送/接收数据。支持ModBus RTU、Modbus TCP。纯C代码编写,只有7个文件,体积小而稳定。
项目地址:
https://github.com/stephane/libmodbus
CH348 USB串口芯片
CH348是一款高速USB总线的转接芯片,实现USB转8个异步串口,每个串口最高波特率为6Mbps,支持CTS和RTS硬件自动流控,满足工业使用环境。
实际中可以利用USB HUB控制器芯片CH334,结合CH348,组成USB转32串口方案。
芯片详情:
CH348详情
方案详情
本次利用CH348硬件去读取八个从机的温度传感器数据,这里首要条件是保证从机与主机的串口通讯正常。这里分享下上位机的代码,介绍一下libmodbus的使用:
#include <iostream>
#include <string>
#include <vector>
#include "modbus.h"
using namespace std;
#define COMNUM 8
// 这里CH348是COM70到COM77
#define CONNUMSTART 70
int main()
{
vector<string> comname(COMNUM);
vector<modbus_t*> mbArr(COMNUM);
// 用于存储接受到的温度数据
uint16_t table[3];
// Modbus RTU初始化
for (size_t i = 0; i < COMNUM; i++) {
comname[i] = string("\\\\.\\") + string("COM") + to_string(CONNUMSTART + i);
mbArr[i] = modbus_new_rtu(comname[i].c_str(), 115200, 'N', 8, 1);
// 如需使用modbus tcp,此处应为改为类似modbus_new_tcp("slave IP ADDRESS", port_number);
if (mbArr[i] == NULL) {
modbus_free(mbArr[i]);
printf("new rtu failed: %s\n", modbus_strerror(errno));
return 0;
}
// i+1为设备地址,这里为设备1~设备8
modbus_set_slave(mbArr[i], i + 1);
if (modbus_connect(mbArr[i]) == -1) {
modbus_close(mbArr[i]);
modbus_free(mbArr[i]);
printf("connect failed: %s\n", modbus_strerror(errno));
return 0;
}
}
std::cout << "Modbus master running...\n";
int ret;
while (1) {
for (size_t i = 0; i < mbArr.size(); i++) {
// 从从机的0、1寄存器读取数据
ret = modbus_read_registers(mbArr[i], 0, 2, table);
if (ret == 2) {
cout << "receive slave No." << i + 1 << " temperature : " << table[0] + (table[1] / 10.0f) << endl;
} else {
goto EXIT;
}
Sleep(50);
}
cout << "-------------------------------------------" << endl;
// 每隔5秒轮询查询一遍温度数据
Sleep(5000);
}
EXIT:
for (auto& p : mbArr) {
modbus_close(p);
modbus_free(p);
}
}
首先运行从机,开始采集数据存储到0、1寄存器中,运行结果如下:
\Release>ModbusMaster.exe
Modbus master running!
receive slave No.1 temperature : 31.6
receive slave No.2 temperature : 30.3
receive slave No.3 temperature : 32.7
receive slave No.4 temperature : 31.7
receive slave No.5 temperature : 33.4
receive slave No.6 temperature : 30.7
receive slave No.7 temperature : 33.4
receive slave No.8 temperature : 33
-------------------------------------------
receive slave No.1 temperature : 32.9
receive slave No.2 temperature : 33.8
receive slave No.3 temperature : 32.3
receive slave No.4 temperature : 31.1
receive slave No.5 temperature : 32.7
receive slave No.6 temperature : 30.2
receive slave No.7 temperature : 30.6
receive slave No.8 temperature : 31.4
-------------------------------------------
receive slave No.1 temperature : 33.5
receive slave No.2 temperature : 33
receive slave No.3 temperature : 30
receive slave No.4 temperature : 30.9
receive slave No.5 temperature : 30
receive slave No.6 temperature : 33.2
receive slave No.7 temperature : 33.9
receive slave No.8 temperature : 32.1
-------------------------------------------