#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;
}
hohoxioxio
- 粉丝: 2
- 资源: 2
最新资源
- (源码)基于C语言的系统服务框架.zip
- (源码)基于Spring MVC和MyBatis的选课管理系统.zip
- (源码)基于ArcEngine的GIS数据处理系统.zip
- (源码)基于JavaFX和MySQL的医院挂号管理系统.zip
- (源码)基于IdentityServer4和Finbuckle.MultiTenant的多租户身份认证系统.zip
- (源码)基于Spring Boot和Vue3+ElementPlus的后台管理系统.zip
- (源码)基于C++和Qt框架的dearoot配置管理系统.zip
- (源码)基于 .NET 和 EasyHook 的虚拟文件系统.zip
- (源码)基于Python的金融文档智能分析系统.zip
- (源码)基于Java的医药管理系统.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
- 3
- 4
- 5
- 6
前往页