我只把主要的代码贴出来方面大家看
这个是读串口函数:
int Serial::write(const char *buf, size_t len){
int wr_bytes = ::write(fd_com, buf, len);
if (wr_bytes ==-1)
return -1;
return wr_bytes;}
这个是写串口函数
int Serial::read(char *buf, size_t len){
int re_bytes = ::read(fd_com,buf, len);
if (re_bytes ==-1)
return -1;
return re_bytes;
}
在线程里面调用读函数
while(1)
{
sleep(1);
r= serial->read(buff,sizeof(buff));
if(c > 0)
{
data += buff;
}
else
continue;
data = data.mid(1);
emit signalDataReady(data);
}
}
这个是在mainwindow里写串口
void MainWindow::press_pushButton_clicked(){
QString infor = ui->lineEdit->text();
w = myserial ->write(infor.toAscii().data(), infor.toAscii().length());}
然后把读到的函数显示到界面上
void MainWindow::slotShowData(QString data)
{
ui->textBrowser->setText(data);
count++;
ui->lcdnumber->display(count);
}
这是两个信号和槽函数
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(press_pushButton_clicked()));
connect(re, SIGNAL(signalDataReady(QString)), this, SLOT(slotShowData(QString)));
函数太长各位有可能看不下去 我大概说下 我自己写了一个串口的类 在linux下 然后在创建了一个读线程 在线程里面读串口 在maindown里设置了一个push按钮 按下按钮 往串口里写数据 然后读线程是一开始就运行的 把读到的数据显示到界面上
现在的问题是 在调用读和写函数的时候 fd都返回-1 不能进行读写
串口打开是正确的 open的返回值是1