自行封装在用的Modbus通迅库,集成了com,tcp,udp, 做个笔记吧, 以下头文件,
#pragma once
#include
#include
#include
#include
#ifdef LIBMODBUS_EXPORTS
#define LIBMODBUS_EXPORT_API __declspec(dllexport)
#else
#define LIBMODBUS_EXPORT_API __declspec(dllimport)
#endif
class LIBMODBUS_EXPORT_API RTUModbus {
public:
//devflag is 1 as default value
RTUModbus();
~RTUModbus();
public:
std::string getAddrPLC();
uint16_t getDevflag();
int getPort();
void sendBit(uint16_t addrstart, bool mvalue);
bool readBit(uint16_t addrstart, uint8_t* destBit);
void sendDataRegister(uint16_t addrstart, uint16_t mvalue);
void sendDataRegisters(uint16_t addrstart, uint16_t* mvalue);
void sendDataRegisters(uint16_t addrstart,const int len, uint16_t* mvalue);
bool readDataRegisters(uint16_t addrstart, uint16_t* destBit);
bool readDataRegisters(uint16_t addrstart,const int len, uint16_t* destBit);
bool isConnected();
void setPLCParam(const int mport, std::string ipra);
void disconnect();
bool connectPLCbyNet(const int port, const int devflag, std::string addr);
bool connectPLC(const int devflag);
//mport :com1 ,flag:0 Rs232,1:RS485
bool connectPLCbySerial(const char * mport, const int flag, const int baud = 115200,
char parity = 'N', const int data_bit = 8, const int stopbit = 1);
bool connectTo_UDP(std::string strIP, const int mport);
private:
std::shared_ptr
};
应用标例:
RTUModbus* mBus=new RTUModbus();
网口连接:
//tcp:
bool res=mBus->connectPLCbyNet(9000,1,"192.168.3.58");
//udp
bool res=connectTo_UDP("192.168.3.58",9000);
串口:
bool res=connectPLCbySerial("com1",1,115200);
读写方式,三者(串口、网口tcp,udp)都是共用的
下载地址:
LibModbus库(udp,tcp.com)一应俱全
https://download.csdn.net/download/sukeman/88504938
平台;VC++2015 ++