vc打开关闭串口程序
作者:cnfgg 日期:2009-07-27
vc打开关闭串口的程序代码如下:
复制内容到剪贴板
程序代码
程序代码UINT CSeries::ReadProc(LPVOID lpParam);
BOOL CSeries::Init(int port,
DWORD BaudRate, //波特率
BYTE StopBits, //停止位
BYTE Parity, //奇偶校验位
BYTE ByteSize, //数据位
int BuffCount)
{
if(bInit)
{
strErrorMsg="串口已经被你打开!";
return FALSE;
}
portID=port;
char szPort[32];
wsprintf( szPort, "COM%d", portID);
m_hComm = CreateFile( szPort,
GENERIC_READ | GENERIC_WRITE, //读写模式
0, //不共享
NULL, //默认安全模式
OPEN_EXISTING, //打开方式:打开已经存在的端口
NULL,
NULL);
if( m_hComm == INVALID_HANDLE_VALUE )
{
strErrorMsg.Format("串口%d打开失败!",portID);
return FALSE;
}
DCB dcb;
if (GetCommState(m_hComm,&dcb) == FALSE)
{
strErrorMsg="获取串口配置失败!";
return FALSE;
}
dcb.BaudRate=BaudRate;
dcb.StopBits=StopBits;
dcb.Parity=Parity;
dcb.ByteSize=ByteSize;
if (SetCommState(m_hComm,&dcb) == 0)
{
strErrorMsg="设置串口配置失败!";
return FALSE;
}
if(BuffCount > 0)
{
SetupComm(m_hComm, BuffCount , BuffCount);
}
COMMTIMEOUTS comTimeOut; // COMMTIMEOUTS对象
comTimeOut.ReadIntervalTimeout = 3; // 接收时,两字符间最大的时延
comTimeOut.ReadTotalTimeoutMultiplier = 3; // 读取每字节的超时
comTimeOut.ReadTotalTimeoutConstant = 2; // 读串口数据的固定超时
// 总超时 = ReadTotalTimeoutMultiplier * 字节数 + ReadTotalTimeoutConstant
comTimeOut.WriteTotalTimeoutMultiplier = 3; // 写每字节的超时
comTimeOut.WriteTotalTimeoutConstant = 2; // 写串口数据的固定超时
SetCommTimeouts(m_hComm,&comTimeOut); // 将超时参数写入设备控制
m_hEndThreadEvent =::CreateEvent(NULL,TRUE,FALSE,NULL);
m_pThreadRead = ::AfxBeginThread(ReadProc,this);
if(!m_pThreadRead)
{
strErrorMsg="创建读串口线程失败!";
return FALSE;
}
bInit=TRUE;
return TRUE;
}
BOOL CSeries::Close()
{
if(bInit==FALSE)
{
strErrorMsg="串口已经关闭!";
return FALSE;
}
SetEvent(m_hEndThreadEvent);
if(CloseHandle(m_hComm) == 0) // 调用该函数关闭串口
{
CString strTemp;
strErrorMsg.Format("串口%d关闭失败!",portID);
return FALSE;
}
bInit=FALSE;
return TRUE;
}
评论: 0 | 引用: 0 | 查看次数: -
发表评论
上一篇
下一篇

文章来自:
Tags:
相关日志: