modbus是一个比较简单的协议,在工业领域和嵌入式设备上使用非常多,得益于其协议的简单,得到了广泛的应用。
虽然此协议存在一些不足之处,比如一次传输的数据量有限,以偏移量定义变量,需要对应的点表才能解析等等,但不影响其使用的广泛。
各类Modbus协议的代码多如牛毛。在此推荐一个不错的Modbus c++代码,项目比较完整,跨平台支持比较好,既可以在Linux下编译,也可以在windows下运行。
代码地址:https://github.com/lyqdy/ymodbus
下载后在tests目录下有.sln,需要使用vs2015打开,用到一些c++11的特性。vs2013以后的估计都可以。
1. 直接编译会报一些头文件找不到,需要将 ../ , ../include 加入到头文件目录
2. 我用vs2019编译报不识别 std::placeholders, 在报错的文件test_***.cpp 里面添加 #include <functional>
3. 删除解决方案里的 linuxserlistener.cpp, 工程中用不到linux下面的文件
4. 报main函数重复,删除一个test_开头的文件 test_ymaster.cpp 或 test_yslave.cpp 。
5.ymblog.h 里面 #ifndef WIN32 改成 #ifndef _WIN32
基本上就可以编译成功了。
不想动手的可以到ymodbus在windows下的修改版,能够被vs2019编译通过。-交通文档类资源-CSDN下载
下载,我用的vs2019,不知vs2015能否打开。生成的时候选择生成 x86平台的。
test中相当于将项目的使用已经说的比较清楚了。还是比较简单的。
class Player : public IPlayer
在Player类中写入相应的逻辑即可实现modbus功能,可以说对于我们的modbus是非常方便的了。