串口通信(同步,异步)VC++

同步:

SerialComm.h文件

#pragma once

//数据缓冲区长度
#define MAX_BUF_LEN		10240

//校验类型枚举
typedef enum CheckType
{
        ctNoSet = 0,
        ctNoCheck,
        ctCRC
};

//生成CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要生成校验的数据指针
//  int dwLen:输入参数,需要生成校验的数据长度
//  返回值:WORD,生成的十六位CRC校验
//
WORD CRC(BYTE* pBuf,int dwLen);

//校验CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要校验的数据指针
//  int dwLen:输入参数,需要校验的数据长度
//  返回值:BOOL,校验正确为TRUE,否则为FALSE
//
BOOL CRCCheck(BYTE* pBuf,int dwLen);


//CSerialComm 串行通讯处理
class CSerialComm : public CObject
{
        friend class CSimulationManage;
public:
        //标准构造函数
        CSerialComm();
        //构造函数
        CSerialComm(int Port,CheckType Check = ctNoSet,int BaudRate = 0,int ByteSize = 0,int Parity = -1, int StopBit = -1);
        //析构函数
        ~CSerialComm();
        //串口初始化
        BOOL Open();
        //串口初始化
        BOOL Open(int Port,CheckType Check = ctNoSet,int BaudRate = 0,int ByteSize = 0,int Parity = -1, int StopBit = -1);
        //读数据
        BOOL Read(BYTE* pBuf,int BufLen,int& nRead);
        //读机车数据
        BOOL ReadLocDat(BYTE* pBuf,int BufLen,int& nRead);
        //写数据
        BOOL Write(BYTE* pBuf,int BufLen);
        //关闭
        BOOL Close();
        //检测串口是否打开
        BOOL IsOpen();
private:
        //串口句柄
        HANDLE m_hCom;
        //端口号
        int m_Port;
        //速率
        int m_BaudRate;
        //发送的字节位数
        int m_ByteSize;
        //停止位数
        int m_StopBit;
        //校验
        int m_Parity;
        //校验类型
        CheckType m_Check;
        //缓冲区长度
        int m_RecvBufLen;
        //接收缓冲区长度
        BYTE m_RecvBuf[MAX_BUF_LEN];
        ///写端口,参数依次为句柄,缓冲区指针,要写字节数,写入字节数
        BOOL WriteComm(void* lpBuffer,DWORD nToWrite,DWORD* nWritten);
public:
        ///读端口,参数依次为句柄,缓冲区指针,要读字节数,读入字节数
        BOOL ReadComm(void* lpBuffer,DWORD nToRead,DWORD* nRead);
};


.cpp文件

// SerialComm.cpp : 实现文件
//

#include "stdafx.h"
#include "SerialComm.h"

//CRC查表算法
WORD ccitt_16[ 256 ] =
{
    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
    0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
    0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
    0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
    0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
    0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
    0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
    0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
    0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
    0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
    0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
    0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
    0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
    0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
    0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
    0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
    0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
    0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
    0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
    0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
    0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
    0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
    0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
    0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
    0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
    0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
    0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
    0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
    0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
    0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
    0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
    0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};


//生成CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要生成校验的数据指针
//  int dwLen:输入参数,需要生成校验的数据长度
//  返回值:WORD,生成的十六位CRC校验
//

WORD CRC(BYTE* pBuf,int dwLen)
{
        BYTE *p = pBuf;
        WORD crc = 0;

        while ( dwLen-- != 0 )
        {
                crc = ( crc << 8 ) ^ ccitt_16[ ( crc >> 8 ) ^ *p++];
        }

        return crc;
}

//校验CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要校验的数据指针
//  int dwLen:输入参数,需要校验的数据长度
//  返回值:BOOL,校验正确为TRUE,否则为FALSE
//

BOOL CRCCheck(BYTE* pBuf,int dwLen)
{
    WORD crc = CRC(pBuf,dwLen);
    return (BOOL)(crc==0);
}

//标准构造函数
//缺省绑定串口2,但不打开串口。
//
CSerialComm::CSerialComm()
{
        m_hCom = NULL;
        m_Port = 2;
        m_Check = ctCRC;
        m_BaudRate = 9600;
        m_ByteSize = 8;
        m_Parity = 0;
        m_StopBit = 0;
        m_RecvBufLen = 0;
}

//构造函数
//参数说明:
//  int Port:指定的串口号
//  CheckType Check:校验类型,缺省为未设置,此时使用以前的校验方式
//  int BaudRate:速率,通讯速率,可省略,此时使用以前的速率
//  int ByteSize:每字节的位数,可省略,此时使用以前的设置
//  int Parity:校验,可省略,此时使用以前的设置
//  int StopBit:停止位,可省略,此时使用以前的设置
//
CSerialComm::CSerialComm(int Port,CheckType Check,int BaudRate,int ByteSize,int Parity,int StopBit)
{
        m_hCom = NULL;
        m_RecvBufLen = 0;
        Open(Port,Check,BaudRate,ByteSize,Parity,StopBit);
}

//析构函数
CSerialComm::~CSerialComm()
{
        Close();
}

// CSerialComm 成员函数
//串口初始化
//参数说明:
//  无输入参数
//  返回BOOL值,打开串口为TRUE,否则为FALSE
//
BOOL CSerialComm::Open()
{
        return Open(m_Port);
}

//串口初始化
//参数说明:
//  int Port:指定的串口号
//  CheckType Check:校验类型,缺省为未设置,此时使用以前的校验方式
//  int BaudRate:速率,通讯速率,可省略,此时使用以前的速率
//  int ByteSize:每字节的位数,可省略,此时使用以前的设置
//  int Parity:校验,可省略,此时使用以前的设置
//  int StopBit:停止位,可省略,此时使用以前的设置
//  返回BOOL值,打开串口为TRUE,否则为FALSE
//
BOOL CSerialComm::Open(int Port,CheckType Check,int BaudRate,int ByteSize,int Parity, int StopBit)
{
        BOOL bRet = TRUE;

        Close();

        if(Port!=0) m_Port = Port;
        if(Check!=ctNoSet) m_Check = Check;
        if(BaudRate!=0) m_BaudRate = BaudRate;
        if(ByteSize>0) m_ByteSize = ByteSize;
        if(Parity>=0) m_Parity = Parity;
        if(StopBit>=0) m_StopBit = StopBit;

    char ComStr[80];
        DCB  dcb;
        COMMTIMEOUTS TimeOut;

        sprintf(ComStr,"Com%d",m_Port);

        //当串口打开或初始化失败时,可得到返回值
        //函数结束时可根据返回值对串口句柄进行处理
        while(1)
        {
                //创建串口设备
                m_hCom=CreateFile(ComStr,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
                if (m_hCom==INVALID_HANDLE_VALUE)
                {
                        bRet = FALSE;
                        break;
                }

                //获取并设置串口属性
                memset(&dcb,0,sizeof(dcb));
                dcb.DCBlength = sizeof(DCB) ;
                if(!GetCommState(m_hCom,&dcb))
                {
                        bRet = FALSE;
                        break;
                }

                dcb.fBinary = 1;
                dcb.BaudRate=m_BaudRate;
                dcb.ByteSize=m_ByteSize;
                dcb.Parity=m_Parity;
                dcb.StopBits=m_StopBit;
                dcb.fParity=0;
                dcb.fDtrControl=1;
                dcb.fOutxCtsFlow=0;
                dcb.fOutxDsrFlow=0;
                dcb.fRtsControl=1;
                dcb.fAbortOnError=1;
                dcb.fTXContinueOnXoff=1;
                dcb.fOutX=0;
                dcb.fInX=0;
                if(!SetCommState(m_hCom,&dcb))
                {
                        bRet = FALSE;
                        break;
                }

                //设置串口读写时间属性
                TimeOut.ReadIntervalTimeout=MAXDWORD;
                TimeOut.ReadTotalTimeoutMultiplier=0;
                TimeOut.ReadTotalTimeoutConstant=0;
                TimeOut.WriteTotalTimeoutMultiplier=1;
                TimeOut.WriteTotalTimeoutConstant=1;
                if(!SetCommTimeouts(m_hCom,&TimeOut))
                {
                        bRet = FALSE;
                        break;
                }

                //清空串口
                PurgeComm(m_hCom,PURGE_TXCLEAR|PURGE_RXCLEAR);
                break;
        }

        //如果初始化失败则对句柄进行处理
        if(!bRet)
        {
                if((m_hCom!=NULL)&&(m_hCom!=INVALID_HANDLE_VALUE)) CloseHandle(m_hCom);
                m_hCom = NULL;
        }
    return bRet;
}

//读数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据缓冲区指针
//  int BufLen:输入参数,数据缓冲区长度
//  int& nRead:输出参数,读到的数据长度
//  返回值:读到有效数据为TRUE,否则为FALSE
//
BOOL CSerialComm::Read(BYTE* pBuf,int BufLen,int& nRead)
{
        int BgnPos = -1,EndPos = -1,i;
        DWORD nReadCount = 0;

        if(m_RecvBufLen>(MAX_BUF_LEN/2)) m_RecvBufLen = 0;
        ReadComm(&m_RecvBuf[m_RecvBufLen],100,&nReadCount);
        m_RecvBufLen += nReadCount;

        if(nReadCount>0)
        {
                nReadCount = nReadCount;
        }

        nRead = 0;
        if(m_RecvBufLen<=0) return FALSE;

        //查找帧头
        for(i=0;i0)
        {
                BOOL bDelete = FALSE;
                nRead = 0;
                for(i=BgnPos+2;i=BufLen) break;
                }

                BOOL bRet = FALSE;

                switch(m_Check)
                {
                case ctCRC:
                        if(CRCCheck(pBuf,nRead))
                        {
                                bRet = TRUE;
                                nRead -= 2;
                        }
                        else
                        {
                                nRead = 0;
                        }
                        break;
                default:
                        bRet = TRUE;
                        break;
                }

                if(EndPos+20)
                {
                        memmove(&m_RecvBuf[0],&m_RecvBuf[BgnPos],m_RecvBufLen-BgnPos);
                        m_RecvBufLen -= BgnPos;
                }

                return FALSE;
        }
}

/************************************************************************/
//读数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据缓冲区指针
//  int BufLen:输入参数,数据缓冲区长度
//  int& nRead:输出参数,读到的数据长度
//  返回值:读到有效数据为TRUE,否则为FALSE
//
BOOL CSerialComm::ReadLocDat(BYTE* pBuf,int BufLen,int& nRead)
{
        int BgnPos = -1,EndPos = -1,i;
        DWORD nReadCount = 0;

        if(m_RecvBufLen>(MAX_BUF_LEN/2))
                m_RecvBufLen = 0;
        ReadComm(&m_RecvBuf[m_RecvBufLen],/*100*/BufLen,&nReadCount);
        m_RecvBufLen += nReadCount;

        if(nReadCount>0)
        {
                nReadCount = nReadCount;
        }

        nRead = 0;
        if(m_RecvBufLen<=0) return FALSE;

        //查找帧头
        for(i=0;i0)
                        {
                                if(m_RecvBuf[i-1]!=0x80 && m_RecvBuf[i+1] == 0x01 && m_RecvBuf[i+2] == 0x01)
                                {
                                        BgnPos = i;
                                        break;
                                }
                        }
                        else
                        {
                                if (m_RecvBuf[i+1] == 0x01 && m_RecvBuf[i+2] == 0x01)
                                {
                                        BgnPos = i;
                                        break;
                                }
                        }
                        //BgnPos = i;
                        //break;
                }
        }

        //如果没有找到帧头则作相应处理
        if(BgnPos<0)
        {
                /*if(m_RecvBuf[m_RecvBufLen-1]==0x10)
                {
                        m_RecvBuf[0] = 0x10;
                        m_RecvBufLen = 1;
                }
                else*/
                        m_RecvBufLen = 0;

                return FALSE;
        }

        //查找帧尾
        for(i=BgnPos+3;i0)
        {
                //BOOL bDelete = FALSE;
                nRead = 0;
                for(i=BgnPos+1;i=BufLen) break;
                }

                BOOL bRet = FALSE;

                switch(m_Check)
                {
                case ctCRC:
                        if(CRCCheck(pBuf,nRead))
                        {
                                bRet = TRUE;
                                nRead -= 2;
                        }
                        else
                        {
                                nRead = 0;
                        }
                        break;
                default:
                        bRet = TRUE;
                        break;
                }

                if(EndPos+10)
                {
                        memmove(&m_RecvBuf[0],&m_RecvBuf[BgnPos],m_RecvBufLen-BgnPos);
                        m_RecvBufLen -= BgnPos;
                }

                return FALSE;
        }
}
/************************************************************************/
//写数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据指针
//  int BufLen:输入参数,需要发送的数据长度
//  返回值:BOOL,正确发送为TRUE,否则为FALSE
//
BOOL CSerialComm::Write(BYTE* pBuf,int BufLen)
{
        WORD C = 0;
        int Len = 0;
        DWORD nWritten = 0;
        BYTE Buf[MAX_BUF_LEN];

        if((NULL==pBuf)||(BufLen<=0)) return FALSE;

        if(m_Check==ctCRC)
        {
                //生成校验
                C = CRC(pBuf,BufLen);
        }

        Buf[Len++] = 0x10;
        Buf[Len++] = 0x02;
        for(int i=0;i

 

异步实现(仅供参考)

SerialCommAsyn.h文件

#pragma once

//数据缓冲区长度
#define MAX_BUF_LEN		1024

//校验类型枚举
typedef enum CheckType
{
	ctNoSet = 0,
	ctNoCheck,
	ctCRC
};

//NO USE 生成CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要生成校验的数据指针
//  int dwLen:输入参数,需要生成校验的数据长度
//  返回值:WORD,生成的十六位CRC校验
//
WORD CRC(BYTE* pBuf,int dwLen);

//校验CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要校验的数据指针
//  int dwLen:输入参数,需要校验的数据长度
//  返回值:BOOL,校验正确为TRUE,否则为FALSE
//
BOOL CRCCheck(BYTE* pBuf,int dwLen);


//CSerialComm 串行通讯处理
class CSerialComm : public CObject
{
public:
	//标准构造函数
	CSerialComm();
	//构造函数
	CSerialComm(int Port,CheckType Check = ctNoSet,int BaudRate = 0,int ByteSize = 0,int Parity = -1, int StopBit = -1);
	//析构函数
	~CSerialComm();
	//串口初始化
	BOOL Open();
	//串口初始化
	BOOL Open(int Port,CheckType Check = ctNoSet,int BaudRate = 0,int ByteSize = 0,int Parity = -1, int StopBit = -1);
	//读数据
	BOOL Read(BYTE* pBuf,int BufLen,int& nRead);
	//读电量数据
	BOOL ReadBtyDat(BYTE* pBuf,int BufLen,int& nRead);
	//NO USE 写数据
	BOOL Write(BYTE* pBuf,int BufLen);
	//关闭
	BOOL Close();
	//检测串口是否打开
	BOOL IsOpen();
	//private:
public:
	//串口句柄
	HANDLE m_hCom;
	//端口号
	int m_Port;
	//速率
	int m_BaudRate;
	//发送的字节位数
	int m_ByteSize;
	//停止位数
	int m_StopBit;
	//校验
	int m_Parity;
	//校验类型
	CheckType m_Check;
	//异步读入信号
	OVERLAPPED m_osRead;
	//异步写入信号
	OVERLAPPED m_osWrite;
	//异步等待信号
	OVERLAPPED m_osWait;
	//缓冲区长度
	int m_RecvBufLen;
	//接收缓冲区长度
	BYTE m_RecvBuf[MAX_BUF_LEN];
	///NO USE 写端口,参数依次为句柄,缓冲区指针,要写字节数,写入字节数
	BOOL WriteComm(void* lpBuffer,DWORD nToWrite,DWORD* nWritten);
public:
	///读端口,参数依次为句柄,缓冲区指针,要读字节数,读入字节数
	BOOL ReadComm(void* lpBuffer,DWORD nToRead,DWORD* nRead);
};


,cpp文件

// SerialComm_Battery.cpp : 实现文件
//

#include "stdafx.h"

#include "SerialComm.h"
//CRC查表算法
WORD ccitt_16[ 256 ] =
{
    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
    0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
    0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
    0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
    0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
    0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
    0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
    0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
    0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
    0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
    0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
    0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
    0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
    0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
    0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
    0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
    0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
    0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
    0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
    0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
    0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
    0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
    0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
    0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
    0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
    0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
    0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
    0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
    0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
    0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
    0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
    0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};


//生成CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要生成校验的数据指针
//  int dwLen:输入参数,需要生成校验的数据长度
//  返回值:WORD,生成的十六位CRC校验
//

WORD CRC(BYTE* pBuf,int dwLen)
{
	BYTE *p = pBuf;
	WORD crc = 0;

	while ( dwLen-- != 0 )
	{
		crc = ( crc << 8 ) ^ ccitt_16[ ( crc >> 8 ) ^ *p++];
	}

	return crc;
}

//校验CRC
//参数说明:
//  BYTE* pBuf:输入参数,需要校验的数据指针
//  int dwLen:输入参数,需要校验的数据长度
//  返回值:BOOL,校验正确为TRUE,否则为FALSE
//

BOOL CRCCheck(BYTE* pBuf,int dwLen)
{
    //WORD crc = CRC(pBuf,dwLen);
    //return (BOOL)(crc==0);
	if(((pBuf[0]+pBuf[1]+pBuf[2])&0xFF) == pBuf[3])
	{	
		return true;
	}
	else return false;
}

//标准构造函数
//缺省绑定串口2,但不打开串口。
//
CSerialComm::CSerialComm()
{
	m_hCom = NULL;
	m_Port = 4;
	m_Check = ctCRC;
	m_BaudRate = 9600;
	m_ByteSize = 8;
	m_Parity = 0;
	m_StopBit = 0;
	m_RecvBufLen = 0;
}

//构造函数
//参数说明:
//  int Port:指定的串口号
//  CheckType Check:校验类型,缺省为未设置,此时使用以前的校验方式
//  int BaudRate:速率,通讯速率,可省略,此时使用以前的速率
//  int ByteSize:每字节的位数,可省略,此时使用以前的设置
//  int Parity:校验,可省略,此时使用以前的设置
//  int StopBit:停止位,可省略,此时使用以前的设置
//
CSerialComm::CSerialComm(int Port,CheckType Check,int BaudRate,int ByteSize,int Parity,int StopBit)
{
	m_hCom = NULL;
	m_RecvBufLen = 0;
	Open(Port,Check,BaudRate,ByteSize,Parity,StopBit);
}

//析构函数
CSerialComm::~CSerialComm()
{
	Close();
}

// CSerialComm 成员函数
//串口初始化
//参数说明:
//  无输入参数
//  返回BOOL值,打开串口为TRUE,否则为FALSE
//
BOOL CSerialComm::Open()
{
	return Open(m_Port);
}

//串口初始化
//参数说明:
//  int Port:指定的串口号
//  CheckType Check:校验类型,缺省为未设置,此时使用以前的校验方式
//  int BaudRate:速率,通讯速率,可省略,此时使用以前的速率
//  int ByteSize:每字节的位数,可省略,此时使用以前的设置
//  int Parity:校验,可省略,此时使用以前的设置
//  int StopBit:停止位,可省略,此时使用以前的设置
//  返回BOOL值,打开串口为TRUE,否则为FALSE
//
BOOL CSerialComm::Open(int Port,CheckType Check,int BaudRate,int ByteSize,int Parity, int StopBit)
{
	BOOL bRet = TRUE;

	Close();

	if(Port!=0) m_Port = Port;
	if(Check!=ctNoSet) m_Check = Check;
	if(BaudRate!=0) m_BaudRate = BaudRate;
	if(ByteSize>0) m_ByteSize = ByteSize;
	if(Parity>=0) m_Parity = Parity;
	if(StopBit>=0) m_StopBit = StopBit;

    char ComStr[80];
	DCB  dcb;
	COMMTIMEOUTS TimeOut;

	sprintf(ComStr,"Com%d",m_Port);

	//当串口打开或初始化失败时,可得到返回值
	//函数结束时可根据返回值对串口句柄进行处理
	while(1)
	{
		//创建串口设备
		//将char[]转化为LPCWSTR
		CString str = CString(ComStr);
		USES_CONVERSION;
		LPCWSTR lpCom = new WCHAR[str.GetLength()+1];
		wcscpy((LPTSTR)lpCom , T2W((LPTSTR)str.GetBuffer(NULL)));

		m_hCom=CreateFile(lpCom,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);
		//清除str
		str.ReleaseBuffer();
		delete lpCom;

		if (m_hCom==INVALID_HANDLE_VALUE)
		{
			bRet = FALSE;
			break;
		}

		//获取并设置串口属性
		memset(&dcb,0,sizeof(dcb));
		dcb.DCBlength = sizeof(DCB) ;
		if(!GetCommState(m_hCom,&dcb))
		{
			bRet = FALSE;
			break;
		}

		dcb.fBinary = 1;
		dcb.BaudRate=m_BaudRate;
		dcb.ByteSize=m_ByteSize;
		dcb.Parity=m_Parity;
		dcb.StopBits=m_StopBit;
		dcb.fParity=0;
		dcb.fDtrControl=1;
		dcb.fOutxCtsFlow=0;
		dcb.fOutxDsrFlow=0;
		dcb.fRtsControl=1;
		dcb.fAbortOnError=1;
		dcb.fTXContinueOnXoff=1;
		dcb.fOutX=0;
		dcb.fInX=0;
		if(!SetCommState(m_hCom,&dcb))
		{
			bRet = FALSE;
			break;
		}		
		
		//设置串口读写时间属性
		TimeOut.ReadIntervalTimeout=MAXDWORD;
		TimeOut.ReadTotalTimeoutMultiplier=0;
		TimeOut.ReadTotalTimeoutConstant=0;
		TimeOut.WriteTotalTimeoutMultiplier=1;
		TimeOut.WriteTotalTimeoutConstant=1;
		if(!SetCommTimeouts(m_hCom,&TimeOut))
		{
			bRet = FALSE;
			break;
		}
		
		//设置OVERLAPPED的读写事件
		memset(&m_osRead,0,sizeof(OVERLAPPED));
		memset(&m_osWrite,0,sizeof(OVERLAPPED));
		memset(&m_osWait,0,sizeof(OVERLAPPED));
		m_osRead.hEvent  = CreateEvent(NULL,TRUE,FALSE,NULL);
		m_osWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
		m_osWait.hEvent  = CreateEvent(NULL,TRUE,FALSE,NULL);
		if(!(m_osRead.hEvent && m_osWrite.hEvent && m_osWait.hEvent))
		{
			bRet = FALSE;
			break;
		}
			
		//设置串口事件
		if(!SetCommMask(m_hCom,EV_RXCHAR))
		{
			bRet = FALSE;
			break;
		}

		//清空串口
		PurgeComm(m_hCom,PURGE_TXCLEAR|PURGE_RXCLEAR);
		break;
	}

	//如果初始化失败则对句柄进行处理
	if(!bRet)
	{
		if((m_hCom!=NULL)&&(m_hCom!=INVALID_HANDLE_VALUE)) CloseHandle(m_hCom);
		m_hCom = NULL;
	}
    return bRet;
}

//读数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据缓冲区指针
//  int BufLen:输入参数,数据缓冲区长度
//  int& nRead:输出参数,读到的数据长度
//  返回值:读到有效数据为TRUE,否则为FALSE
//
BOOL CSerialComm::Read(BYTE* pBuf,int BufLen,int& nRead)
{
	int BgnPos = -1,EndPos = -1,i; 
	DWORD nReadCount = 0;

	if(m_RecvBufLen>(MAX_BUF_LEN/2)) m_RecvBufLen = 0;
	ReadComm(&m_RecvBuf[m_RecvBufLen],100,&nReadCount);
	m_RecvBufLen += nReadCount;
	
	if(nReadCount>0)
	{
		nReadCount = nReadCount;
	}

	nRead = 0;
	if(m_RecvBufLen<=0) return FALSE;

	//查找帧头
	for(i=0;i0)
	{		
		BOOL bDelete = FALSE;
		nRead = 0;
		for(i=BgnPos+2;i=BufLen) break;
		}

		BOOL bRet = FALSE;

		switch(m_Check)
		{
		case ctCRC:
			if(CRCCheck(pBuf,nRead))
			{
				bRet = TRUE;
				nRead -= 2;
			}
			else
			{
				nRead = 0;
			}
			break;
		default:
			bRet = TRUE;
			break;
		}

		if(EndPos+20)
		{
			memmove(&m_RecvBuf[0],&m_RecvBuf[BgnPos],m_RecvBufLen-BgnPos);
			m_RecvBufLen -= BgnPos;
		}

		return FALSE;
	}
}

/************************************************************************/
//读数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据缓冲区指针
//  int BufLen:输入参数,数据缓冲区长度
//  int& nRead:输出参数,读到的数据长度 
//  返回值:读到有效数据为TRUE,否则为FALSE
//
BOOL CSerialComm::ReadBtyDat(BYTE* pBuf,int BufLen,int& nRead)
{
	int BgnPos = -1,EndPos = -1,i; 
	DWORD nReadCount = 0;

	if(m_RecvBufLen>(MAX_BUF_LEN/2)) 
		m_RecvBufLen = 0;
	ReadComm(&m_RecvBuf[m_RecvBufLen],/*100*/BufLen,&nReadCount);
	m_RecvBufLen += nReadCount;
	//?
	if(nReadCount>0)
	{
		nReadCount = nReadCount;
	}

	nRead = 0;
	if(m_RecvBufLen<=0)
	{
		return FALSE;
	}

	//查找帧头
	for(i=0;i0)
	{		
		//BOOL bDelete = FALSE;
		nRead = 0;
		for(i=BgnPos+2;i<=EndPos;i++)
		{			
			pBuf[nRead++] = m_RecvBuf[i];
			if(nRead>=BufLen) break;
		}

		BOOL bRet = FALSE;
		switch(m_Check)
		{
		case ctCRC:
			if(CRCCheck(pBuf,nRead))
			{
				bRet = TRUE;
				//nRead -= 2;
			}
			else
			{
				nRead = 0;
			}
			break;
		default:
			bRet = TRUE;
			break;
		}

		if(EndPos+10)
		{
			memmove(&m_RecvBuf[0],&m_RecvBuf[BgnPos],m_RecvBufLen-BgnPos);
			m_RecvBufLen -= BgnPos;
		}

		return FALSE;
	}
}
/************************************************************************/
//写数据
//参数说明:
//  BYTE* pBuf:输入参数,需要发送的数据指针
//  int BufLen:输入参数,需要发送的数据长度
//  返回值:BOOL,正确发送为TRUE,否则为FALSE
//
BOOL CSerialComm::Write(BYTE* pBuf,int BufLen)
{
	WORD C = 0;
	int Len = 0;
	DWORD nWritten = 0;
	BYTE Buf[MAX_BUF_LEN];

	if((NULL==pBuf)||(BufLen<=0)) return FALSE;

	if(m_Check==ctCRC)
	{
		//生成校验
		C = CRC(pBuf,BufLen);
	}

	Buf[Len++] = 0x10;
	Buf[Len++] = 0x02;
	for(int i=0;i

 

Thread_WaitCommMask.cpp


BOOL CTestDlg::OnInitDialog(void)
{	
	CDialog::OnInitDialog();

	hThread = CreateThread(NULL,0,ThreadFunc,(LPVOID)m_hWnd,0,NULL);

	return 0;
}

DWORD WINAPI ThreadFunc(LPVOID lpParameter)
{
	//HWND hWnd = (HWND)lpParameter;
	static int count = 0;
	CString str;
	int nReadCount;
	DWORD dwMask,dwTrans,dwError;
	COMSTAT comStat;
	BYTE m_RecvBuf[MAX_BUF_LEN];
	while(1)
	{	
		ResetEvent(theApp.m_SerialComm->m_osWait.hEvent);
		if(!WaitCommEvent(theApp.m_SerialComm->m_hCom,&dwMask,&theApp.m_SerialComm->m_osWait))
		{	
			if(GetLastError() == ERROR_IO_PENDING)
			{
				GetOverlappedResult(theApp.m_SerialComm->m_hCom,&theApp.m_SerialComm->m_osWait,&dwTrans,true);
			}

		}
		CString str;
		str.Format(_T("%d"),dwMask);
		AfxMessageBox(str);
		if((dwMask & EV_RXCHAR) == EV_RXCHAR)
		{
			theApp.m_SerialComm->ReadBtyDat(m_RecvBuf,100,nReadCount);
			if(nReadCount > 0)
			{	
				//电压 (m_RecvBuf[2]<<8)|m_RecvBuf[1]
				str.Format(_T("cout = %d str = %02x %02x %02x %02x"),count++,m_RecvBuf[0],m_RecvBuf[1],m_RecvBuf[2],m_RecvBuf[3]);
				SetDlgItemText((HWND)lpParameter,IDC_EDIT2,str);
				//::PostMessage((HWND)lpParameter , UM_RECVCOMMDATA , 0, 0);
			}
		}
		//if()
		//{
		//其它事件
		//}

		Sleep(10);
	}

	return true;
}

 

你可能感兴趣的:(MFC,串口通信,c++)