• 大小: 2KB
    文件类型: .rar
    金币: 1
    下载: 0 次
    发布日期: 2021-06-01
  • 语言: 其他
  • 标签: 串口  COM  

资源简介

简单的串口类,包含.CPP和.H,两个文件,采用异步IO读写,实现串口的读写

资源截图

代码片段和文件信息

#include “StdAfx.h“
#include “CVisionSerial.h“

CVisionSerial::CVisionSerial(void)
{
hCom = NULL;
memset(&Overlapped0sizeof(Overlapped));
Overlapped.hEvent = CreateEvent(NULLFALSEFALSENULL);
}

CVisionSerial::~CVisionSerial(void)
{

}


int CVisionSerial::Init(LPCTSTR lpstrint BaudRateint ByteSizeint Parityint StopBitsint timer)
{

InitializeCriticalSection(&m_csCommunicationSync);

hCom = CreateFile(lpstr GENERIC_READ | GENERIC_WRITE 0 NULL
OPEN_EXISTING FILE_FLAG_OVERLAPPED 
NULL);

if (INVALID_HANDLE_VALUE == hCom)
{
CloseHandle(hCom);
return ERROR_OPENFAIL;
}

if (SetupComm(hCom32*102432*1024) == false)
return ERROR_SETBUFFER;

PurgeComm(hComPURGE_RXCLEAR | PURGE_TXCLEAR);
COMMTIMEOUTS TimeOuts;
TimeOuts.ReadIntervalTimeout = 100;
TimeOuts.ReadTotalTimeoutConstant = timer;
TimeOuts.ReadTotalTimeoutMultiplier = 0;

TimeOuts.WriteTotalTimeoutConstant = timer;
TimeOuts.WriteTotalTimeoutMultiplier = 0;

if (SetCommTimeouts(hCom&TimeOuts) == false)
return ERROR_CRPTIMEOUT;

DCB dcb;
if(GetCommState(hCom&dcb) == false)
return ERROR_PORTFAULT;

dcb.BaudRate = BaudRate;
dcb.ByteSize = ByteSize;
dcb.Parity = Parity;
dcb.StopBits = StopBits;

if (SetCommState(hCom&dcb) == false)
return ERROR_PORTFAULT;

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

return 0;
}

int CVisionSerial::SendData(char *buff int lenunsigned long *WrittenLen)
{

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

EnterCriticalSection(&m_csCommunicationSync);

BOOL bWriteStat = WriteFile(hCombufflenWrittenLen&Overlapped); //向用户传送数据

if (!bWriteStat)
{
if (GetLastError() == ERROR_IO_PENDING)
WaitForSingleobject(Overlapped.hEvent1000);
}
LeaveCriticalSection(&m_csCommunicationSync);
return bWriteStat;
}

void CVisionSerial::ReadData(char *buffunsigned long byteRead unsigned long *len)
{

EnterCriticalSection(&m_csCommunicationSync);
if (ReadFile(hCombuffbyteReadlen&Overlapped) == FALSE) //读取串口数据
{
int i=GetLastError();
if (GetLastError() == ERROR_IO_PENDING)
{
GetOverlappedResult(hCom&OverlappedlenTRUE);
}else
{
memset(buff0sizeof(buff));
}
}
LeaveCriticalSection(&m_csCommunicationSync);
}

HANDLE CVisionSerial::getHCOM()
{
return hCom;
}

void CVisionSerial::closeHCOM()
{
if (hCom != NULL)
{
CloseHandle(hCom);
}
}

void CVisionSerial::ClearOutBuffer()
{
::PurgeComm(hCom PURGE_TXABORT  | PURGE_TXCLEAR );
}

void CVisionSerial::ClearInBuffer()
{
::PurgeComm(hCom PURGE_RXABORT | PURGE_RXCLEAR);
}

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件       2730  2015-08-27 16:55  Serialport.cpp

     文件        774  2015-08-27 16:56  Serialport.h

----------- ---------  ---------- -----  ----

                 3504                    2


评论

共有 条评论