#include<afx.h>
#include "RS232dll.h"
bool OpenSerial(CString m_sPort)
{
COMMTIMEOUTS TimeOuts;
if (m_bOpen)
{
return TRUE;
}
m_hCom = CreateFile(m_sPort, // communication port string (COMX)
GENERIC_READ | GENERIC_WRITE, // read/write types
0, // comm devices must be opened with exclusive access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // Async I/O
0);
DCB dcb;
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = 9600; // 波特率
dcb.fParity = FALSE;
dcb.ByteSize = 8; // 每字节位数
dcb.Parity = NOPARITY;//无奇偶检验
dcb.StopBits = ONESTOPBIT;//1个停止位
if (m_hCom == INVALID_HANDLE_VALUE)
{
return FALSE;
}
memset(&m_osRead, 0, sizeof(OVERLAPPED));
memset(&m_osWrite, 0, sizeof(OVERLAPPED));
SetupComm(m_hCom, MAXBLOCK,MAXBLOCK);
SetCommMask(m_hCom, EV_RXCHAR);
TimeOuts.ReadIntervalTimeout = MAXDWORD;// 把间隔超时设为最大,把总超时设为0将导致ReadFile立即返回并完成操作
TimeOuts.ReadTotalTimeoutMultiplier = 0;
TimeOuts.ReadTotalTimeoutConstant = 0;
TimeOuts.WriteTotalTimeoutMultiplier = 0; // 设置写超时以指定WriteComm成员函数中的GetOverlappedResult函数的等待时间
TimeOuts.WriteTotalTimeoutConstant = 5000;
SetCommTimeouts(m_hCom, &TimeOuts);
m_bOpen = TRUE;
MessageBox(NULL,m_sPort,m_sPort,MB_OK);
return TRUE;
}
void CloseSerial()
{
if(m_bOpen)
{
SetCommMask(m_hCom, 0);
CloseHandle(m_hCom);
m_bOpen = FALSE;
MessageBox(NULL,"Close","Close",MB_OK);
}
}
DWORD ReadSerial(unsigned char* chBuf, DWORD dwLength)
{
DWORD nLen;
COMSTAT comStat;
DWORD dwErrorFlags;
ClearCommError(m_hCom, &dwErrorFlags, &comStat);
nLen = min(dwLength, comStat.cbInQue);
ReadFile(m_hCom, chBuf, nLen, &nLen, &m_osRead);
return nLen;
}
DWORD WriteSerial(unsigned char *chBuf, DWORD dwLength)
{
BOOL bState;
COMSTAT comStat;
DWORD dwErrorFlags;
ClearCommError(m_hCom, &dwErrorFlags, &comStat);
bState = WriteFile(m_hCom, chBuf, dwLength, &dwLength, &m_osWrite);
if(!bState)
{
if(GetLastError() == ERROR_IO_PENDING)
{
GetOverlappedResult(m_hCom, &m_osWrite, &dwLength, TRUE);// 等待
}
else
{
dwLength = 0;
}
}
return dwLength;
}
- 1
- 2
- 3
- 4
- 5
- 6
前往页