利用CSerialPort 类进行通信串口

 

 

<textarea cols="50" rows="15" name="code" class="cpp">示例代码: 打开串口 CSerialPort m_Port; //CSerialPort类对象 if (m_Port.InitPort(this, m_nCom, m_nBaud,m_cParity,m_nDatabits,m_nStopbits,m_dwCommEvents,512)) { m_Port.StartMonitoring(); m_ctrlIconOpenoff.SetIcon(m_hIconRed); strStatus.Format("STATUS:COM%d OPENED,%d,%c,%d,%d",m_nCom, m_nBaud,m_cParity,m_nDatabits,m_nStopbits); //"当前状态:串口打开,无奇偶校验,8数据位,1停止位"); } else { AfxMessageBox("没有发现此串口或被占用"); m_ctrlIconOpenoff.SetIcon(m_hIconOff); } 函数原型: BOOL CSerialPort::InitPort(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message) UINT portnr, // portnumber (1..4) UINT baud, // baudrate char parity, // parity UINT databits, // databits UINT stopbits, // stopbits DWORD dwCommEvents,//EV_RXCHAR, EV_CTS etc UINT writebuffersize) // size to the writebuffer 发送数据: 示例代码: if(m_Port.m_hComm!=NULL) { m_Port.WriteToPort(data,len); //m_Port.WriteToPort((LPCTSTR)m_strSendData); } 函数原型: void WriteToPort(char* string); void WriteToPort(char* string,int n); void WriteToPort(LPCTSTR string); void WriteToPort(LPCTSTR string,int n); 接收数据: //添加消息映射函数 ON_MESSAGE(WM_COMM_RXCHAR, OnCommunication) //函数原型 LONG CSCommDlg::OnCommunication(WPARAM ch, LPARAM port) ch是接受的字符,port是com口号 关闭串口 m_Port.ClosePort(); </textarea> 

你可能感兴趣的:(c,String,null)