您的位置:首页 > 其它

最近又开发串口通信程序总结1

2010-05-10 14:29 543 查看
CString GetTimeStr()
{
CTime time;
// 获取当前时间
time = CTime::GetCurrentTime();
CString sTime;
// 格式化时间串
sTime = time.Format("%Y%m%d_%H%M%S");
return sTime;
}


生成固定格式yyyymmdd_hhmimiss.txt文件

BOOL CComDlg::OpenComm(int Num)
{
COMMTIMEOUTS TimeOuts;

//    int i;
//    i=m_ComboSeriou.GetCurSel();
//    if(i==CB_ERR)
//        return FALSE;
m_ComboSeriou.GetLBText(Num,m_SeriouStr);
m_hCom=CreateFile(m_SeriouStr,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);
if(m_hCom==INVALID_HANDLE_VALUE)
{
AfxMessageBox("打开串口失败!");
m_bConnected=0;
return FALSE;
}

//    if(!m_bConnected)
//        return FALSE;
//设置工作者线程响应的事件
SetCommMask(m_hCom,EV_RXCHAR);
//设置读写缓冲区
SetupComm(m_hCom,MAXBLOCK,MAXBLOCK);
//设置超时
TimeOuts.ReadIntervalTimeout=MAXDWORD;
TimeOuts.ReadTotalTimeoutMultiplier=0;
TimeOuts.ReadTotalTimeoutConstant=0;
TimeOuts.WriteTotalTimeoutMultiplier=0;
SetCommTimeouts(m_hCom,&TimeOuts);
//创建工作者线程
if(SetCommParameter())
{
m_pThread=AfxBeginThread(ComProce,this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
if(m_pThread==NULL)
{
CloseHandle(m_hCom);
AfxMessageBox("线程创建失败!");
m_bConnected=0;
return FALSE;
}
else
{
//            m_bConnected=1;
m_pThread->ResumeThread();
}
}
else
{
CloseHandle(m_hCom);
AfxMessageBox("参数设置失败!");
m_bConnected=0;
return FALSE;
}
m_bConnected=1;
return TRUE;
}

BOOL CComDlg::SetCommParameter()
{
DCB dcb;
if(!GetCommState(m_hCom,&dcb))
return FALSE;
//设置基本参数
int baudindex=m_ComboBaud.GetCurSel();
m_ComboBaud.GetLBText(baudindex,m_BaudStr);
dcb.BaudRate=baudrate[baudindex];
//    CString test1;
//    test1.Format("%ld",dcb.BaudRate);
//    AfxMessageBox(test1);
int dataindex=m_ComboData.GetCurSel();
m_ComboData.GetLBText(dataindex,m_DataStr);
dcb.ByteSize=databit[dataindex];
//    CString test2;
//    test2.Format("%ld",dcb.ByteSize);
//    AfxMessageBox(test2);
int jiaoyanindex=m_ComboJiaoyan.GetCurSel();
m_ComboJiaoyan.GetLBText(jiaoyanindex,m_JiaoyanStr);
switch(jiaoyanindex)
{
case 0:
dcb.Parity=NOPARITY;
break;
case 1:
dcb.Parity=ODDPARITY;
break;
case 2:
dcb.Parity=EVENPARITY;
break;
default:;
}
//    CString test3;
//    test3.Format("%ld",dcb.Parity);
//    AfxMessageBox(test3);
int stopindex=m_ComboStop.GetCurSel();
m_ComboStop.GetLBText(stopindex,m_StopStr);
switch(stopindex)
{
case 0:
dcb.StopBits=ONESTOPBIT;
break;
case 1:
dcb.StopBits=TWOSTOPBITS;
break;
default:;
}
//    CString test4;
//    test4.Format("%d",dcb.StopBits);
//    AfxMessageBox(test4);
//流控制
dcb.fInX=TRUE;
dcb.fOutX=TRUE;
dcb.XonChar=XON;
dcb.XoffChar=XOFF;
dcb.XonLim=50;
dcb.XoffLim=50;

dcb.fNull=TRUE;

return(SetCommState(m_hCom,&dcb));
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: