【C++】Modbus通讯

MODBUS_SERVER.h

MODBUS_SERVER.cpp

MODBUS_SHARE.h

MODBUS_SHARE.cpp

PORT.h

PORT.cpp

两个VC++ Modbus通信例子源代码.rar

modbus
协议编程 C++

MODBUS_SERVER.h

//Download by http://www.NewXing.com
#if !defined(MSERVERH)
#define MSERVERH

#ifdef __cplusplus
extern "C"
{
#endif
    /*1.对单个PLC操作*/
    /*读一个或多个模拟量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
    char MODBUS_S_ReadMultiRegD(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, short int *list);
    /*读一个或多个开关量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
    char MODBUS_S_ReadMultiRegM(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, bool *list);
    /*读一个或多个开关量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
    char MODBUS_S_ReadMultiRegM_1x(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, bool *list);
    /*写一个模拟量 参数:站号,写地址, 返回数据变量指针  返回:小于零失败,大于零表示成功*/
    char MODBUS_S_WriteSingRegD(unsigned char rtu, unsigned short int RegAdd, short int var);
    /*写一个模拟量 参数:站号,写地址, 返回数据变量指针  返回:小于零失败,大于零表示成功*/
    char MODBUS_S_WriteSingRegM(unsigned char rtu, unsigned short int RegAdd, bool var);

    /*2.对全部PLC操作*/
    char MODBUS_S_A_WriteSingRegD(unsigned short int RegAdd, bool var);
    char MODBUS_S_A_WriteSingRegM(unsigned short int RegAdd, short int var);

    /*3.端口操作*/
    char MODBUS_S_Init(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
                unsigned char xParity, unsigned char xStopBit);
    char MODBUS_S_UnInit();

#ifdef __cplusplus
}
#endif

#endif

MODBUS_SERVER.cpp

#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include "MODBUS_SHARE.h"
#include "MODBUS_SERVER.h"
#include "PORT.h"
//Download by http://www.NewXing.com
unsigned char buff[256];

////////////////////////////////////////////////////////////////////////////////////////////////////
/*1.对单个PLC操作*/
/*读一个或多个模拟量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
/*40000*/
char MODBUS_S_ReadMultiRegD(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, short int *list)
{
    unsigned short int crc16;
    unsigned short int crctmp;
    short int vartmp;

    memset(buff, 0x00, 255);
    buff[0]= rtu;
    buff[1]= 0x03;
    buff[2]= (unsigned char)((RegAdd-40001) >> 8);
    buff[3]= (unsigned char)(RegAdd-40001);
    buff[4]= (unsigned char)(RegCount >> 8);
    buff[5]= (unsigned char)RegCount;
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen==8)
        {
            //读数据
            memset(buff, 0x00, 255);
            Sleep(50);
            strlen= ReadChar(255, (char *)buff, 1000);
            if(strlen==0)
            {
                //无返回
                return(-2);
            }
            else
            {
                //返回长度有效,解析接收缓冲区
                if(strlen== (3+(RegCount *2)+ 2) && buff[0]== rtu && buff[1]== 0x03)
                {
                    crc16= CalcCrcFast(buff, 3+(RegCount*2));
                    crctmp= buff[strlen-2];
                    crctmp= crctmp << 8 | buff[strlen-1];
                    if(crc16== crctmp )
                    {
                        for(int i=0; i< RegCount; i++)
                        {
                            vartmp= buff[3+(2*i)];
                            vartmp= vartmp << 8;
                            vartmp= vartmp | buff[3+((2*i)+1)];

                            list[i]= vartmp;
                        }
                    }
                    else
                    {
                        return(-1);
                    }
                }
                else
                {
                    return(-1);
                }
            }
        }
        else
        {
            return(-2);
        }
    }
    else
    {
        return(-2);
    }

    return(1);
}

/*读一个或多个开关量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
/*00000*/
char MODBUS_S_ReadMultiRegM(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, bool *list)
{
    unsigned short int crc16;
    unsigned short int crctmp;

    memset(buff, 0x00, 255);
    buff[0]= rtu;
    buff[1]= 0x01;
    buff[2]= (unsigned char)(RegAdd >> 8);
    buff[3]= (unsigned char)RegAdd;
    buff[4]= (unsigned char)(RegCount >> 8);
    buff[5]= (unsigned char)RegCount;
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen==8)
        {
            //读数据
            memset(buff, 0x00, 255);
            Sleep(50);
            strlen= ReadChar(255, (char *)buff, 1000);
            if(strlen==0)
            {
                //无返回
                return(-2);
            }
            else
            {
                //返回长度有效,解析接收缓冲区
                if(strlen== (3+((RegCount+7)/8)+ 2) && buff[0]== rtu && buff[1]== 0x01)
                {
                    crc16= CalcCrcFast(buff, 3+((RegCount +7)/8));
                    crctmp= buff[strlen-2];
                    crctmp= crctmp << 8 | buff[strlen-1];
                    if(crc16== crctmp )
                    {
                        unsigned char row=0, col=0;
                        for(int i=0; i<RegCount; i++)
                        {
                            row= i / 8;
                            col= i % 8;
                            list[i]= buff[3 + row] >> col & 0x01;
                        }
                    }
                    else
                    {
                        return(-1);
                    }
                }
                else
                {
                    return(-1);
                }
            }
        }
        else
        {
            return(-2);
        }
    }
    else
    {
        return(-2);
    }

    return(1);
}

/*读一个或多个开关量  参数:站号,开始地址, 读的数量, 返回数据变量指针  返回:-1表示CRC校验失败,-2表示无应答, 大于零表示接收数据成功*/
/*10000*/
char MODBUS_S_ReadMultiRegM_1x(unsigned char rtu, unsigned short int RegAdd, unsigned short int RegCount, bool *list)
{
    unsigned short int crc16;
    unsigned short int crctmp;

    memset(buff, 0x00, 255);
    buff[0]= rtu;
    buff[1]= 0x02;
    buff[2]= (unsigned char)((RegAdd-10001)>> 8);
    buff[3]= (unsigned char)(RegAdd-10001);
    buff[4]= (unsigned char)(RegCount >> 8);
    buff[5]= (unsigned char)RegCount;
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen==8)
        {
            //读数据
            memset(buff, 0x00, 255);
            Sleep(50);
            strlen= ReadChar(255, (char *)buff, 1000);
            if(strlen==0)
            {
                //无返回
                return(-2);
            }
            else
            {
                //返回长度有效,解析接收缓冲区
                if(strlen== (3+((RegCount+7)/8)+ 2) && buff[0]== rtu && buff[1]== 0x02)
                {
                    crc16= CalcCrcFast(buff, 3+((RegCount +7)/8));
                    crctmp= buff[strlen-2];
                    crctmp= crctmp << 8 | buff[strlen-1];
                    if(crc16== crctmp )
                    {
                        unsigned char row=0, col=0;
                        for(int i=0; i<RegCount; i++)
                        {
                            row= i / 8;
                            col= i % 8;
                            list[i]= buff[3 + row] >> col & 0x01;
                        }
                    }
                    else
                    {
                        return(-1);
                    }
                }
                else
                {
                    return(-1);
                }
            }
        }
        else
        {
            return(-2);
        }
    }
    else
    {
        return(-2);
    }

    return(1);
}

/*写一个模拟量 参数:站号,写地址, 返回数据变量指针  返回:小于零失败,大于零表示成功*/
/*40000*/
char MODBUS_S_WriteSingRegD(unsigned char rtu, unsigned short int RegAdd, short int var)
{
    unsigned short int crc16;

    memset(buff, 0x00, 255);
    buff[0]= rtu;
    buff[1]= 0x06;
    buff[2]= (unsigned char)((RegAdd-40001) >> 8);
    buff[3]= (unsigned char)(RegAdd-40001);
    buff[4]= (unsigned char)(var >> 8);
    buff[5]= (unsigned char)var;
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen==8)
        {
            Sleep(50);
            strlen= ReadChar(255, (char *)buff, 1000);
            //返回长度有效,解析接收缓冲区
            if(!(strlen== 8 && buff[0]== rtu && buff[1]== 0x06))
            {
                return(-1);
            }
        }
        else
        {
            return(-1);
        }
    }
    else
    {
        return(-1);
    }

    return(1);
}

/*写一个模拟量 参数:站号,写地址, 返回数据变量指针  返回:小于零失败,大于零表示成功*/
char MODBUS_S_WriteSingRegM(unsigned char rtu, unsigned short int RegAdd, bool var)
{
    unsigned short int crc16;

    memset(buff, 0x00, 255);
    buff[0]= rtu;
    buff[1]= 0x05;
    buff[2]= (unsigned char)(RegAdd >> 8);
    buff[3]= (unsigned char)RegAdd;
    if(var)
    {
        buff[4]= 0xff;
        buff[5]= 0x00;
    }
    else
    {
        buff[4]= 0x00;
        buff[5]= 0x00;
    }
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        Sleep(50);
        strlen= WriteChar(8, (char *)buff);
        if(strlen==8)
        {
            Sleep(50);
            strlen= ReadChar(255, (char *)buff, 1000);
            //返回长度有效,解析接收缓冲区
            if(!(strlen== 8 && buff[0]== rtu && buff[1]== 0x05))
            {
                return(-1);
            }
        }
        else
        {
            return(-1);
        }
    }
    else
    {
        return(-1);
    }

    return(1);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*2.对全部PLC操作*/
char MODBUS_S_A_WriteSingRegD(unsigned short int RegAdd, short int var)
{
    unsigned short int crc16;

    memset(buff, 0x00, 255);
    buff[0]= 0xff;
    buff[1]= 0x06;
    buff[2]= (unsigned char)((RegAdd -40001) >> 8);
    buff[3]= (unsigned char)(RegAdd -40001);
    buff[4]= (unsigned char)(var >> 8);
    buff[5]= (unsigned char)var;
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen!=8)
        {
            return(-1);
        }
    }
    else
    {
        return(-1);
    }

    return(1);
}

char MODBUS_S_A_WriteSingRegM(unsigned short int RegAdd, bool var)
{
    unsigned short int crc16;

    memset(buff, 0x00, 255);
    buff[0]= 0xff;
    buff[1]= 0x05;
    buff[2]= (unsigned char)(RegAdd >> 8);
    buff[3]= (unsigned char)RegAdd;
    if(var)
    {
        buff[4]= 0xff;
        buff[5]= 0x00;
    }
    else
    {
        buff[4]= 0x00;
        buff[5]= 0x00;
    }
    crc16= CalcCrcFast(buff, 6);
    buff[6]= (unsigned char)(crc16 >> 8);
    buff[7]= (unsigned char)crc16;

    //发送数据
    unsigned long strlen;
    if(IsOpen())
    {
        //发送数据
        strlen= WriteChar(8, (char *)buff);
        if(strlen!=8)
        {
            return(-1);
        }
    }
    else
    {
        return(-1);
    }

    return(1);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
char MODBUS_S_Init(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
                unsigned char xParity, unsigned char xStopBit)
{
    /*
    Parity :
    EVENPARITY Even
    MARKPARITY Mark
    NOPARITY No parity
    ODDPARITY Odd
    SPACEPARITY Space
    */
    /*BaudRate:
    CBR_110
    CBR_19200
    CBR_300
    CBR_38400
    CBR_600
    CBR_56000
    CBR_1200
    CBR_57600
    CBR_2400
    CBR_115200
    CBR_4800
    CBR_128000
    CBR_9600
    CBR_256000
    CBR_14400
    */
    /*
    ONESTOPBIT 1 stop bit
    ONE5STOPBITS 1.5 stop bits
    TWOSTOPBITS
    */

    if(OpenPort(xPort,xBabd,xDataSize,xParity, xStopBit,4096,4096,1000))
    {
        return(1);
    }
    else
    {
        return(0);
    }
}

char MODBUS_S_UnInit()
{
    ClosePort();
    return(1);
}

MODBUS_SHARE.h

//Download by http://www.NewXing.com
#if !defined(MSHAREH)
#define MSHAREH

#ifdef __cplusplus
extern "C"
{
    #endif

    unsigned short CalcCrcFast(unsigned char*puchMsg,unsigned short usDataLen);

    #ifdef __cplusplus
}
#endif

#endif

MODBUS_SHARE.cpp

#include "stdafx.h"
#include "MODBUS_SHARE.h"
//Download by http://www.NewXing.com
const unsigned char m_auchCRCHi[]=
{
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40
}
;

const unsigned char m_auchCRCLo[]=
{
    0x00,0xC0,0xC1,0x01,0xC3,0x03,0x02,0xC2,0xC6,0x06,
    0x07,0xC7,0x05,0xC5,0xC4,0x04,0xCC,0x0C,0x0D,0xCD,
    0x0F,0xCF,0xCE,0x0E,0x0A,0xCA,0xCB,0x0B,0xC9,0x09,
    0x08,0xC8,0xD8,0x18,0x19,0xD9,0x1B,0xDB,0xDA,0x1A,
    0x1E,0xDE,0xDF,0x1F,0xDD,0x1D,0x1C,0xDC,0x14,0xD4,
    0xD5,0x15,0xD7,0x17,0x16,0xD6,0xD2,0x12,0x13,0xD3,
    0x11,0xD1,0xD0,0x10,0xF0,0x30,0x31,0xF1,0x33,0xF3,
    0xF2,0x32,0x36,0xF6,0xF7,0x37,0xF5,0x35,0x34,0xF4,
    0x3C,0xFC,0xFD,0x3D,0xFF,0x3F,0x3E,0xFE,0xFA,0x3A,
    0x3B,0xFB,0x39,0xF9,0xF8,0x38,0x28,0xE8,0xE9,0x29,
    0xEB,0x2B,0x2A,0xEA,0xEE,0x2E,0x2F,0xEF,0x2D,0xED,
    0xEC,0x2C,0xE4,0x24,0x25,0xE5,0x27,0xE7,0xE6,0x26,
    0x22,0xE2,0xE3,0x23,0xE1,0x21,0x20,0xE0,0xA0,0x60,
    0x61,0xA1,0x63,0xA3,0xA2,0x62,0x66,0xA6,0xA7,0x67,
    0xA5,0x65,0x64,0xA4,0x6C,0xAC,0xAD,0x6D,0xAF,0x6F,
    0x6E,0xAE,0xAA,0x6A,0x6B,0xAB,0x69,0xA9,0xA8,0x68,
    0x78,0xB8,0xB9,0x79,0xBB,0x7B,0x7A,0xBA,0xBE,0x7E,
    0x7F,0xBF,0x7D,0xBD,0xBC,0x7C,0xB4,0x74,0x75,0xB5,
    0x77,0xB7,0xB6,0x76,0x72,0xB2,0xB3,0x73,0xB1,0x71,
    0x70,0xB0,0x50,0x90,0x91,0x51,0x93,0x53,0x52,0x92,
    0x96,0x56,0x57,0x97,0x55,0x95,0x94,0x54,0x9C,0x5C,
    0x5D,0x9D,0x5F,0x9F,0x9E,0x5E,0x5A,0x9A,0x9B,0x5B,
    0x99,0x59,0x58,0x98,0x88,0x48,0x49,0x89,0x4B,0x8B,
    0x8A,0x4A,0x4E,0x8E,0x8F,0x4F,0x8D,0x4D,0x4C,0x8C,
    0x44,0x84,0x85,0x45,0x87,0x47,0x46,0x86,0x82,0x42,
    0x43,0x83,0x41,0x81,0x80,0x40
}
;

unsigned short CalcCrcFast(unsigned char*puchMsg,unsigned short usDataLen)
{
    unsigned char uchCRCHi=0xFF ;
    unsigned char uchCRCLo=0xFF ;
    unsigned short uIndex ;

    while(usDataLen--)
    {
        uIndex=uchCRCHi^*puchMsg++;
        uchCRCHi=uchCRCLo^m_auchCRCHi[uIndex];
        uchCRCLo=m_auchCRCLo[uIndex];
    }
    return(uchCRCHi<<8|uchCRCLo);
}

PORT.h

//Download by http://www.NewXing.com
#if !defined(MPORT)
#define MPORT

#ifdef __cplusplus
extern "C"
{
#endif

    inline bool IsOpen();
    bool OpenPort(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
                unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
                unsigned long OutputBuffSize, unsigned long dwTimerOut);
    void ClosePort();
    void ClearBuffer();
    unsigned long ReadChar(unsigned long dwBufferLength, char *buff, unsigned long dwWaitTime);
    unsigned long WriteChar(unsigned long dwBufferLength, char *buff);

#ifdef __cplusplus
}
#endif

#endif

PORT.cpp

//Download by http://www.NewXing.com
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "PORT.h"

//////////////////////////////////////////////////////////////////////////////////////////////////////////
DCB dcb;
COMMTIMEOUTS CommTimerOuts;
HANDLE hCom= INVALID_HANDLE_VALUE;

OVERLAPPED m_overlappedRead;
OVERLAPPED m_overlappedWrite;

//////////////////////////////////////////////////////////////////////////////////////////////////////////
//通讯端口是否打开
inline bool IsOpen()
{
    return hCom != INVALID_HANDLE_VALUE;
} 

//设置超时
void SetTimerOut(unsigned long dwTimerOut= 5000)
{
    if(!IsOpen())
    {
        return;
    }

    CommTimerOuts.ReadIntervalTimeout= MAXDWORD;
    CommTimerOuts.ReadTotalTimeoutConstant= 0;
    CommTimerOuts.ReadTotalTimeoutMultiplier= 0;
    CommTimerOuts.WriteTotalTimeoutConstant= dwTimerOut;
    CommTimerOuts.WriteTotalTimeoutMultiplier= 0;

    SetCommTimeouts(hCom, &CommTimerOuts);
}

//设置DCB参数
bool SetDCBParm(unsigned long xBabd, unsigned char xDataSize,
                unsigned char xParity, unsigned char xStopBit)
{
    if(!IsOpen())
    {
        return false;
    }

    if (!GetCommState(hCom, &dcb))
    {
        #ifdef _DEBUG
            printf ("错误: %d << 等到通讯口参数失败.\n", GetLastError());
        #endif

        ClosePort();
        return (false);
    }
    //设置通讯参数
    dcb.DCBlength= sizeof(DCB);
    dcb.BaudRate = xBabd;     // set the baud rate
    dcb.ByteSize = xDataSize; // data size, xmit, and rcv
    dcb.Parity =   xParity;   // no parity bit
    dcb.StopBits = xStopBit;  // one stop bit
    if (!SetCommState(hCom, &dcb))
    {
        #ifdef _DEBUG
            printf ("错误: %d << 设置通讯端口参数失败.\n", GetLastError());
        #endif
        ClosePort();
        return (false);
    }   

    return true;
}

//设置端口缓冲区大小
bool SetPortBuffSize(unsigned long InputBuffSize, unsigned long OutputBuffSize)
{
    if(!IsOpen())
    {
        return false;
    } 

    if(!SetupComm(hCom, InputBuffSize, OutputBuffSize))
    {
        #ifdef _DEBUG
            printf ("错误: %d << 设置通讯端口缓冲失败.\n", GetLastError());
        #endif
        ClosePort();
        return (false);
    }   

    return true;
}

//清理所有缓冲区
void ClearBuffer()
{
    if(!IsOpen())
    {
        return;
    }

    PurgeComm(hCom, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
}

//当前接收缓冲区字节数目;
unsigned long GetInBuffCount()
{
    if(!IsOpen())
    {
    return(0);
    }

    DWORD     dwErrorFalgs;
    COMSTAT   Comstat;

    ClearCommError(hCom, &dwErrorFalgs, &Comstat);
    return Comstat.cbInQue;
}

//当前发送缓冲区字节数目;
unsigned long GetOutBuffCount()
{
    if(!IsOpen())
    {
        return false;
    }

    DWORD     dwErrorFalgs;
    COMSTAT   Comstat;

    ClearCommError(hCom, &dwErrorFalgs, &Comstat);
    return Comstat.cbOutQue;
}

///打开串口////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool OpenPort(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
                unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
                unsigned long OutputBuffSize, unsigned long dwTimerOut)
{
    if(IsOpen())
    {
        ClosePort();
    }
    //设置事件
    memset(&m_overlappedRead,0,sizeof(OVERLAPPED));
    m_overlappedRead.hEvent= CreateEvent(NULL,FALSE,TRUE,"portread");
    ASSERT(m_overlappedRead.hEvent != INVALID_HANDLE_VALUE);

    memset(&m_overlappedWrite,0,sizeof(OVERLAPPED));
    m_overlappedWrite.hEvent= CreateEvent(NULL,FALSE,TRUE,"portwrite");
    ASSERT(m_overlappedWrite.hEvent != INVALID_HANDLE_VALUE);
    //取得串口字符
    char com_str[255];
    strcpy(com_str, "COM");
    ltoa(xPort, com_str + 3, 10);
    //打开通讯端口
    hCom = CreateFile(com_str,
                    GENERIC_READ | GENERIC_WRITE,
                    0,
                    NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                    NULL
                    );
    if (hCom == INVALID_HANDLE_VALUE)
    {
        #ifdef _DEBUG
            printf ("错误: %d << 打开通讯口失败,请检查是否已经安装串口设备.\n", GetLastError());
        #endif
        return (false);
    }
    SetPortBuffSize(InputBuffSize,OutputBuffSize);
    SetDCBParm(xBabd,xDataSize,xParity,xStopBit);
    SetTimerOut(dwTimerOut);
    //清理缓冲器
    PurgeComm(hCom, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
    //启动成功
    #ifdef _DEBUG
        printf ("成功开启端口 %d.\n", com_str);
    #endif
    return(true);
}

//关闭串口;
void ClosePort()
{
    if(IsOpen())
    {
        CloseHandle(hCom);
        hCom= INVALID_HANDLE_VALUE;
    }    

    //ResetEvent(m_overlappedRead.hEvent);
    //ResetEvent(m_overlappedWrite.hEvent); 

    if(m_overlappedRead.hEvent!=NULL)
    {
        CloseHandle(m_overlappedRead.hEvent);
    }
    if(m_overlappedWrite.hEvent!=NULL)
    {
        CloseHandle(m_overlappedWrite.hEvent);
    }
}

//异步读数据
unsigned long ReadChar(unsigned long dwBufferLength, char *buff, unsigned long dwWaitTime=20)
{
    if(!IsOpen())
    {
        return(0);
    }

    DWORD       dwError;
    COMSTAT     Stat;
    if(::ClearCommError(hCom, &dwError, &Stat) && dwError > 0)   //清除错误
    {
        ::PurgeComm(hCom, PURGE_RXABORT | PURGE_RXCLEAR); /*清除输入缓冲区*/
        return 0;
    }
    if(!Stat.cbInQue)// 缓冲区无数据
    {
        return 0;
    }

    unsigned long uReadLength = 0;
    dwBufferLength = dwBufferLength - 1 > Stat.cbInQue ? Stat.cbInQue : dwBufferLength - 1;
    if(!::ReadFile(hCom, buff, dwBufferLength, &uReadLength, &m_overlappedRead)) //2000 下 ReadFile 始终返回 True
    {
        if(::GetLastError() == ERROR_IO_PENDING) // 结束异步I/O
        {
            WaitForSingleObject(m_overlappedRead.hEvent, dwWaitTime);   //等待20ms
            if(!::GetOverlappedResult(hCom, &m_overlappedRead, &uReadLength, false))
            {
                if(::GetLastError() != ERROR_IO_INCOMPLETE)//其他错误
                {
                    uReadLength = 0;
                }
            }
        }
        else
        {
            uReadLength = 0;
        }
    }

    return uReadLength;
}

//异步写数据
unsigned long WriteChar(unsigned long dwBufferLength, char *buff)
{
    if(!IsOpen())
    {
        return 0;
    }

    DWORD dwError;
    if(ClearCommError(hCom, &dwError, NULL) && dwError > 0)  //清除错误
    {
        PurgeComm(hCom, PURGE_TXABORT | PURGE_TXCLEAR);
    }

    unsigned long uWriteLength = 0;
    if(!WriteFile(hCom, buff, dwBufferLength, &uWriteLength, &m_overlappedWrite))
    {
        if(GetLastError() == ERROR_IO_PENDING)
        {
            DWORD m_tmp=0;
            m_tmp= WaitForSingleObject(m_overlappedWrite.hEvent, 1000);
            if(m_tmp== WAIT_TIMEOUT || m_tmp== WAIT_ABANDONED)
            {
                return(0);
            }
            else if(m_tmp== WAIT_OBJECT_0)
            {
                if(!GetOverlappedResult(hCom,&m_overlappedWrite,&uWriteLength,false))
                {
                    return(0);
                }
                else
                {
                    return uWriteLength;
                }
            }

            uWriteLength = 0;
        }
    }

    return uWriteLength;
}
时间: 2024-10-13 22:10:18

【C++】Modbus通讯的相关文章

ModBus通讯注意事项

很多同学在做Modbus通讯时,需要连续读取多个现场设备的数据,虽然也编写了Modbus轮询的程序,但是有时还是无法正常通讯.有时虽然能够保证通讯,但是所有现场设备的轮询周期很长.本文将从MBUS_CTRL的超时时间参数设置来说明超时时间设置的重要性.答:Modbus通讯协议是单主多从的通讯协议,如果需要读取多个现场Modbus从站设备的数据时,很多PLC不支持对Modbus通讯功能块的自动排序,需要自己编写Modbus轮询程序来实现,轮询时每次只能激活一个Modbus的读写功能块.以常见的主站

modbus协议显示屏|modbus通讯显示屏|modbus显示电子屏功能码实现代码分享

modbus协议显示屏|modbus通讯显示屏|modbus显示电子屏功能码实现代码分享,主要用来实现"预置多个寄存器功能码". MODBUS-RTU协议的"0X1F"功能码实物效果图拍摄如下: MODBUS-RTU协议的"0X1F"功能码示例如下: 例:请求在从机MODBUS显示屏设备17 中的2 个寄存器中放入预置值,起始寄存器为40002 ,预置值为00 0AH 和01 02H.QUERYField NameSlave AddressFun

MODBUS通讯协议及编程

MODBUS通讯协议及编程 单片机的modbus RTU的详细解释

【案例分析】西门子S7-200与变频器之间无线MODBUS通讯实例

在工业现场由PLC远程控制变频器的应用非常常见,如果挖沟布线不便或者变频器在移动设备上,那么采用无线通讯就是最佳方案. 本方案的好处是:没有运行费用,不用插卡,自主组网:距离远,可以穿过障碍,绕过阻挡物,无线传输距离达到3公里以上. 这里我们选用西门子PLC和台达的变频器为例,并结合西安达泰的DTD433M无线数据终端来说明PLC与变频器之间的无线通讯过程. 其他变频器和S7-200的无线MODBUS通讯都是一样的,最大的区别就是通讯代码是各厂家自行定义的,查说明书就行. 我们的硬件测试环境如下

Modbus通讯协议

<ignore_js_op> O1CN01P1wxTI1dCdw5nAeMO_!!85243700.jpg (287.43 KB, 下载次数: 0) 下载附件  保存到相册 2019-6-19 11:24 上传 Modbus通讯协议Modbus概述 Modbus是由Modicon公司(现为施耐德电气的一个品牌)在1978年发明的,这是一个跨时代.里程碑式的网络协议,因为工业网络从此拉开了序幕.    Modbus是全球第一个真正用于工业现场的总线协议,据不完全统计:截至到2004中,Modbu

modbus通讯协议详解

一.Modbus 协议简介  Modbus协议是一种已广泛应用于当今工业控制领域的通用通讯协议.通过此协议,控制器相互之间.或控制器经由网络(如以太网)可以和其它设备之间进行通信.Modbus协议使用的是主从通讯技术,即由主设备主动查询和操作从设备.一般将主控设备方所使用的协议称为Modbus Master,从设备方使用的协议称为Modbus Slave.典型的主设备包括工控机和工业控制器等:典型的从设备如PLC可编程控制器等.Modbus通讯物理接口可以选用串口(包括RS232和RS485),

PC高级语言与施耐德、罗克韦尔、台达等PLC的Modbus通讯源代码(ModbusTCP.DLL/ModbusRTU.DLL)

1.0  通讯组件概述 该类通讯组件适用于基于PC高级语言的工业自动化控制系统,用于PC与可编程控制器(PLC).智能仪表等进行数据通讯.组件采用动态链接库文件(*.DLL)的形式,在PC系统的项目工程里引用该组件,调用相应的属性与方法函数,即可快速实现PC与PLC的数据高效交换. DLL通讯组件无须安装,直接复制到工程文件目录,方便打包安装部署:无须任何配置,直接调用函数,与应用开发无缝衔接:多年工程经验的软件团队开发测试,经过本公司及客户的海量实际应用检验,稳定可靠:采用稳定高效的内部协议,

Modbus通讯协议简介

Modbus协议简介 Modbus协议是应用于电子控制器上的一种通用语言.通过此协议,控制器相互之间.控制器经由网络(例如以太网)和其他设备之间可以通信.它已成为一种通用的工业标准,有了它,不同厂商生产的控制设备可以练成工业网络,进行集中监控. 此协议定义了一个控制器能认识使用的消息结构,而不管它们是经过何种网络进行通信的.它描述了一种控制器请求访问其他设备的过程,如果回应来自其他设备的请求,以及怎样侦测错误并记录.它制定了消息域格局和内容的公共格式. 当在以Modbus网络上通信时,此协议决定

维控PLC与电流变送器modbus通讯获取电流变送器数据

2018-09-2319:28:01 今天本来要用单片机来做这个项目的,但是失败了.... 所以我又拿出了PLC来搞,也是相当之复杂,查了很多资料终于做出而来了. 今天还有事,赶紧临时备份总结一波 原文地址:https://www.cnblogs.com/pengwenzheng/p/9693563.html