Windows 下串口类

//Windows 下串口类

//MySerialPort.h
/

#ifndef __MY_SERIAL_PORT_H__
#define __MY_SERIAL_PORT_H__

/

#include

/

#define MAX_DEVICE_BUFFER_SIZE 0x100

/

class CMySerialPort
{
public:
CMySerialPort();
virtual~CMySerialPort();

public:
//打开串口(串口名,波特率,数据位,校验位,停止位)
BOOL _Open(const LPTSTR _lpszPortName,
   DWORD _dwBaudRate = 4800,BYTE _nByteSize = 8,
   BYTE _nParity = NOPARITY,BYTE _nStopBits = ONESTOPBIT);
//关闭串口
void _Close();

public:
//读串口
DWORD _Read(void* _pvData,DWORD _dwMaxSize);
//写串口
DWORD _Write(const void* _pvData,DWORD _dwSize);

private:
HANDLE m_hPort;

};

/

#endif //__MY_SERIAL_PORT_H__

/


//MySerialPort.cpp
/

#include "stdafx.h"
#include "MySerialPort.h"

/

CMySerialPort::CMySerialPort()
{
m_hPort = INVALID_HANDLE_VALUE;
}

CMySerialPort::~CMySerialPort()
{
_Close();
}

BOOL CMySerialPort::_Open(const LPTSTR _lpszPortName,
   DWORD _dwBaudRate,BYTE _nByteSize,BYTE _nParity,BYTE _nStopBits)
{
DCB dcb;
COMMTIMEOUTS TimeOuts;

m_hPort = CreateFile(_lpszPortName,//COM1口
   GENERIC_READ|GENERIC_WRITE, //允许读和写
   0, //独占方式
   NULL,
   OPEN_EXISTING, //打开而不是创建
   0, //同步方式
   NULL);
if(INVALID_HANDLE_VALUE == m_hPort)
{
   return FALSE;
}

SetupComm(m_hPort,MAX_DEVICE_BUFFER_SIZE,MAX_DEVICE_BUFFER_SIZE); //输入缓冲区和输出缓冲区的大小都是100

//设定读超时
TimeOuts.ReadIntervalTimeout=MAXDWORD;
TimeOuts.ReadTotalTimeoutMultiplier=0;
TimeOuts.ReadTotalTimeoutConstant=0;
//在读一次输入缓冲区的内容后读操作就立即返回,
//而不管是否读入了要求的字符。

//设定写超时
TimeOuts.WriteTotalTimeoutMultiplier=100;
TimeOuts.WriteTotalTimeoutConstant=500;
SetCommTimeouts(m_hPort,&TimeOuts); //设置超时

GetCommState(m_hPort,&dcb);
dcb.BaudRate=_dwBaudRate; //波特率
dcb.ByteSize=_nByteSize; //每个字节有几位
dcb.Parity=_nParity; //奇偶校验位
dcb.StopBits=_nStopBits; //停止位
SetCommState(m_hPort,&dcb);

return TRUE;
}

void CMySerialPort::_Close()
{
if(INVALID_HANDLE_VALUE != m_hPort)
{
   CloseHandle(m_hPort);
   m_hPort = INVALID_HANDLE_VALUE;
}
}

DWORD CMySerialPort::_Read(void* _pvData,DWORD _dwMaxSize)
{
DWORD dwReaded = 0;
BOOL bReadStat = FALSE;

if (INVALID_HANDLE_VALUE != m_hPort)
{
   bReadStat = ReadFile(m_hPort,_pvData,_dwMaxSize,&dwReaded,NULL);

   if (bReadStat)
   {
    return dwReaded;
   }
}

return -1;
}

DWORD CMySerialPort::_Write(const void* _pvData,DWORD _dwSize)
{
DWORD dwWrited = 0;
BOOL bReadStat = FALSE;

if (INVALID_HANDLE_VALUE != m_hPort)
{
   bReadStat = WriteFile(m_hPort,_pvData,_dwSize,&dwWrited,NULL);

   if (bReadStat)
   {
    return dwWrited;
   }
}

return -1;
}

/

你可能感兴趣的:(Windows 下串口类)