Linux下QT串口通信,收不到数据?

Linux下QT串口通信,收不到数据?


料青山看我应如是
浏览 2154回答 3
3回答

HUX布斯

#include "posix_qextserialport.h"#include <QMessageBox>#include <QIODevice>Posix_QextSerialPort *myCom;void Form7::openCom(){myCom = new Posix_QextSerialPort("/dev/ttyS0");myCom->open();}void Form7::senddata(){myCom->setBaudRate(BAUD115200);myCom->setFlowControl(FLOW_OFF);myCom->setParity(PAR_NONE);myCom->setDataBits(DATA_8);myCom->setStopBits(STOP_1);myCom->setTimeout(5,0);int a=myCom->writeBlock("1",1);QString str;str.setNum(a);QMessageBox::warning(this,"a",str);}void Form7::readCom(){char buf[256]={0};int a= myCom->readBlock(buf,256);QString str;str.setNum(a);QMessageBox::warning(this,"a",str);this->lineEdit6->setText(buf);}void Form7::Nclose(){myCom->close();}

偶然的你

串口通信一般为三步:打开串口,串口设置,向串口发送数据或者向串口接受数据:void OpenComm(){hCom=CreateFile("COM3",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);}void SetComm(){SetupComm(hCom,1024,1024);DCB dcb;dcb.BaudRate=115200;dcb.fParity=NOPARITY;dcb.ByteSize=8;dcb.StopBits=ONESTOPBIT;GetCommState(hCom,&dcb);if(!GetCommState(hCom,&dcb)){std::cerr<<"串口被占用"<<std::endl;return;}if(!SetCommMask(hCom,EV_RXCHAR|EV_TXEMPTY)){std::cerr<<"掩码设置失败"<<std::endl;}}void SendMessageOut(const BYTE snd[],int len){DWORD factdata=100;DWORD res=0;wOverLapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL); //创建事件BOOL tempflag = WriteFile(hCom,snd,len,&factdata,&wOverLapped);//在数据缓冲Ipbuffer不知道是否有问题if(tempflag!=0){std::cerr<<"等待信号"<<std::endl;res=WaitForSingleObject(wOverLapped.hEvent,5000);WriteFile(hCom,snd,len,&factdata,&wOverLapped);}if(res!=WAIT_OBJECT_0)std::cout<<"数据发送失败"<<std::endl;}这是向串口发送数据的,主要函数为WriteFile();读取ReadFile(),具体用法 百度一下
打开App,查看更多内容
随时随地看视频慕课网APP