在上一篇文章中,我们介绍了串口编程的CnComm多线程串口通讯库v1.5代码,接下来我们说说怎么来使用。
1、类库文件:cncomm.h 加入VC++工程
2、StdAfx.h中加入 #include "CnComm.h"
3、界面头文件加入COM口定义 CnComm com1;
4、界面头文件加入消息响应函数 afx_msg LRESULT OnReceive(WPARAM, LPARAM);
5、初始化打开串口 com1.Open(5);
6、设置波特率等参数(可选)
com1.SetState(DWORD dwBaudRate, BYTE btParity = NOPARITY, BYTE btByteSize = 8, BYTE btStopBits = ONESTOPBIT);
dwBaudRate:波特率,9600,19200,38400等;
btParity:奇偶校验,{ NOPARITY 无校验, ODDPARITY 偶校验, EVENPARITY 奇校验, MARKPARITY 1校验, SPACEPARITY 0校验}
btByteSize:数据位数,{4, 5, 6, 7, 8}
btStopBits:停止位数,{ ONESTOPBIT 1位 , ONE5STOPBITS 1.5位 , TWOSTOPBITS 2位}
7、串口绑定界面 com1.SetWnd(this->GetSafeHwnd());
8、加入接收函数消息映射 ON_MESSAGE(ON_COM_RECEIVE, OnReceive)
9、实现接收数据函数OnReceive
LRESULT CCOMReadDlg::OnReceive(WPARAM wparam, LPARAM lparam)
{
char buffer[1024];
int len = com1.Read(buffer,1023);
buffer[len] = _T('\0');
CString strRec;
if (isHex)
{
char hex_buffer[1024*3];
com1.Ascii2Hex(buffer, hex_buffer);
strRec += hex_buffer;
}
else
strRec += buffer;
m_strRec.SetWindowText(strRec);
// MessageBox(strRec);
return TRUE;
}
10、串口发送数据
void CCOMReadDlg::OnSend()
{
// TODO: Add your control notification handler code here
UpdateData();
char* buffer = new char[m_sendData.GetLength()*2+1];
#ifdef UNICODE
int len = wcstombs(buffer, (LPCTSTR)m_sendData, m_sendData.GetLength());
buffer[len]= 0;
#else
strcpy(buffer, (LPCTSTR)m_sendData);
int len = m_sendData.GetLength();
#endif
if (isHex)
{
int HexCnt = com1.Hex2Ascii(buffer, buffer);
if (com1.IsOverlappedMode() || com1.IsTxBufferMode())
com1.Write(buffer, HexCnt);
else
{
for (int i = 0; i<HexCnt; i++ )
i += com1.Write(buffer + i, HexCnt - i);
}
}
else
{ //! 重叠模式下或者缓冲区模式下 可以不检查输出返回值,并直接输出
if (com1.IsOverlappedMode() || com1.IsTxBufferMode())
com1.Write(buffer);
else
{//! 阻塞非缓冲区模式 必须检查返回值,确保数据完全发送出
for (int i = 0; i<len; i++ )
i += com1.Write(buffer + i, len - i);
}
}
delete[] buffer;
}