64,683
社区成员
发帖
与我相关
我的任务
分享
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QMutex>
#include<QTime>
//串口读数线程
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
~Thread();
void OpenSerialPort();
char buf[2];
int fd;
QTime timer;
protected:
virtual void run();
};
#endif // THREAD_H
#include "Thread.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#define BAUDRATE B115200
#define RE_DEVICE "/dev/ttyUSB1"
Thread::Thread()
{
OpenSerialPort();
memset((char*)&buf,0,sizeof(buf));
}
Thread::~Thread()
{
close(fd);
}
void Thread::OpenSerialPort()
{
int result,status;
struct termios oldtio, newtio; //termios结构是用来保存波特率,字符大小等
fd=open(RE_DEVICE,O_RDWR|O_NOCTTY);
if(fd<0)
{
perror("error");
exit(1);
}
result=tcgetattr(fd,&oldtio); //保存当前设置到oldtio
if (result != 0)
{
printf("tcgetattr fd fail\n");
}
bzero(&newtio,sizeof(newtio)); //清除newtio结构,并重新对它的成员设置如下
newtio.c_cflag=BAUDRATE|CS8|CLOCAL|CREAD; //9600、8位、忽略DCD信号、启用接收装置
newtio.c_iflag|=IGNPAR; //忽略奇偶
newtio.c_oflag=0;
newtio.c_lflag=0;
newtio.c_cc[VMIN]=0;
newtio.c_cc[VTIME]=100; //在规定时间(VTIME)内读取(VMIN)个字符;
tcflush(fd,TCIFLUSH); //清除所有队列在串口的输入与输出;
status=tcsetattr(fd,TCSANOW,&newtio); //把我们的设置写入termios
if (status != 0)
{
printf("tcsetattr fd fail\n");
}
}
void Thread::run()
{
while(true)
{
timer.start();
if(!read(fd,buf,1))
{
qDebug("Time1 elapsed: %d ms", timer.elapsed());
continue;
}
emit finished();
qDebug("Time2 elapsed: %d ms", timer.elapsed());
}
}