下面讲述原理,也可以下载完整实验源码:
源码下载
前言
QT没有提供串口类,使用的是linux提供的函数。
linux下设备和文件使用一样,用open函数打开串口,设置等都提供了函数的,需要自己组合一下,封装成你要的函数。
1.QT串口发送数据
要使用串口,需先打开串口,封装的函数如下:
int open_port(constchar* dev_path)
{
int fd;
//open uart
fd = open(dev_path, O_RDWR|O_NOCTTY|O_NDELAY);
if(fd <0)
{
perror("open serial port");
return-1;
}
if(fcntl(fd, F_SETFL,0)<0)//设置为阻塞模式,后面启动的线程会阻塞,串口有数据才读
perror("fcntl F_SETFL\n");
/*if(isatty(STDIN_FILENO) == 0)//再次验证是否为终端设备,我用的刷卡器,屏蔽了这个,不然会失败
{
perror("standard inpput is not a terminal device");
}*/
return fd;
}
接下来需要设置串口的波特率、校验、结束位等,封装的函数如下:
int set_com_config(int fd,int baud_rate,int data_bits,char parity,int stop_bits)
{
struct termios new_