串口通讯

声明:

HANDLE m_hCom;      // 串口句柄
 OVERLAPPED m_osRead,m_osWrite;  // 指向重叠结构变量的指针 

打开串口:

CString strCom;
 m_Com.GetWindowText(strCom);
 m_hCom=CreateFile(strCom,
  GENERIC_READ | GENERIC_WRITE,
  0,
  NULL,
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  NULL);
 if(m_hCom==INVALID_HANDLE_VALUE)
 {
  MessageBox("打开串口失败!","错误",MB_OK|MB_ICONERROR);
  return;
 }
 SetupComm(m_hCom,1024,512);

发送数据:

bool fState;
 DWORD length=dwlength;// 数据长度
 byte bytSendAddress;
 byte bytSendData[32];
 int i, j;
 j = 0;
 bytSendAddress = buf[0];
 for(i=1;i<=length;i++)
 {
  bytSendData[j] = buf[i];
  j++;
 }
 DCB myDCB;
 GetCommState(m_hCom,&myDCB);
 myDCB.BaudRate = CBR_4800;
 myDCB.fBinary = TRUE;
 myDCB.fParity = TRUE;
 myDCB.ByteSize = 8;
 myDCB.Parity = MARKPARITY;
 myDCB.StopBits = ONESTOPBIT;
 SetCommState(m_hCom,&myDCB);
 fState=WriteFile(m_hCom,&bytSendAddress,1,NULL,&m_osWrite);
 for(int x=0;x<1000000;x++)
 {
  for(int y=0;y<2.5;y++){} // 延迟
 }
 GetCommState(m_hCom,&myDCB);
 myDCB.Parity = SPACEPARITY;
 fState=WriteFile(m_hCom,&bytSendData,length-1,NULL,&m_osWrite);
 SetCommState(m_hCom,&myDCB);
 fWriteAdr = true;
 Sleep(iSleep);
 if(!fState)
 {
  if (GetLastError()==ERROR_IO_PENDING)
  {
   GetOverlappedResult(m_hCom,&m_osWrite,&length,TRUE);//wait
  }
 }

接收数据:

DWORD length=0;
 COMSTAT ComStat;                     
 DWORD dwErrorFlags;
 ClearCommError(m_hCom,&dwErrorFlags,&ComStat); 
 length=min(dwlength, ComStat.cbInQue);
 ReadFile(m_hCom,&receiveLSControl,length,&length,&m_osRead);//receiveLSControl byte数组

关闭串口:

CloseHandle(m_hCom);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值