3 回答
TA贡献1876条经验 获得超6个赞
#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();
}
TA贡献1841条经验 获得超3个赞
串口通信一般为三步:打开串口,串口设置,向串口发送数据或者向串口接受数据:
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(),具体用法 百度一下
添加回答
举报