serial.hpp
/******************************************/
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<limits.h>
#include<dirent.h>
#include<termios.h>
#include<errno.h>
#include<stdio.h>
#include<sys/select.h>
#include<string.h>
#include<QUdpSocket>
#include<QHostAddress>
/********************************************/
/************************************************/
int tty_fd ;
int nread;
QByteArray buff;
char serial_buf[1024];
QUdpSocket *sender = nullptr;
void openH12(void);
/***********************************************/
open serial.cpp
void UDPLink::openH12()
{
tty_fd = open("/dev/ttyHS1",O_RDWR | O_NOCTTY | O_NONBLOCK);
if (-1 == tty_fd) {
qDebug()<<"skydroid H12UART:Can't Open Serial Port";
}else{
qDebug()<<"skydroid H12UART:Open Serial Port";
}
struct termios opt;
//获取驱动程序默认参数
tcgetattr(tty_fd,&opt);
bzero(&opt,sizeof (opt));
opt.c_cflag |= CLOCAL | CREAD;
opt.c_cflag &= ~CSIZE;
opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/
opt.c_oflag &= ~OPOST; /*Output*/
//设置串口输出波特率
cfsetospeed(&opt, B921600);
//设置串口输入波特率
cfsetispeed(&opt, B921600);
//设置数据位数 8位数据位
opt.c_cflag |= CS8;
//校验位 无校验位
opt.c_cflag &= ~PARENB;
//设置停止位 1位停止位
opt.c_cflag &= ~CSTOPB;
//设置停止time
opt.c_cc[VTIME]=10;
opt.c_cc[VMIN]=1;
//更新配置
tcflush(tty_fd,TCIOFLUSH);
fcntl(tty_fd, F_SETFL, 1); //串口阻塞 0阻塞1非阻塞
if (tcsetattr(tty_fd, TCSANOW, &opt) != 0) //激活新设置
{
tty_fd = open("/dev/ttyHS1",O_RDWR | O_NOCTTY | O_NDELAY);
qDebug()<< "激活新设置失败:";
qDebug() << strerror(errno);
}
QUdpSocket *sender = new QUdpSocket;
nread = read(tty_fd,serial_buf,1024);
qDebug() << serial_buf ;
for(int i=0;i<nread;i++)
buff[i]=serial_buf[i];
sender->writeDatagram(buff,nread,QHostAddress::Broadcast,14550);
emit bytesReceived(this, buff);
qDebug()<<"0000000000000000000002222222222222222222222222000000000000000000";
}