Qt串口编程
本文总结使用Qt集成的串口模块进行串口基本功能实现;
1. 头文件包含
#include <QtSerialPort/QSerialPort>//串口接口
#include <QtSerialPort/QSerialPortInfo>//串口接口信息
同时需在.pro文件中添加QT += serialport,因为串口功能作为独立的一个模块存在。
2. 遍历系统下的串口设备
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
//通常通过串口名称进行连接,例COM1,所以在此处获取串口名称
//qDebug() << "Name : " << info.portName();
//qDebug() << "Description : " << info.description();
//qDebug() << "Manufacturer: " << info.manufacturer();
//qDebug() << "Serial Number: " << info.serialNumber();
//qDebug() << "System Location: " << info.systemLocation();
}
3. 配置串口参数
//创建串口对象
QSerialPort *my_serialport= new QSerialPort;
//设置串口号
QString comname = "COM1";//可以在遍历设备中获取到可用设备;
//检索系统是否存在同名串口设备,有则设置;
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
if(info.portName()==comname)
{
my_serialport->setPortName(info.systemLocation());
}
}
//设置波特率,参数一是波特率,QSerialPort域下有所有的可选值,参数二是通信模式,包括单工,双工,全双工;
my_serialport->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);
//设置数据位,QSerialPort域下有所有的可选值
my_serialport->setDataBits(QSerialPort::Data8);
//设置校验位,QSerialPort域下有所有的可选值
my_serialport->setParity(QSerialPort::NoParity);
//设置停止位,QSerialPort域下有所有的可选值
my_serialport->setStopBits(QSerialPort::OneStop);
4. 打开&关闭串口
bool Rsl=my_serialport->open(QIODevice::ReadWrite);//打开串口并选择读写模式
if(Rsl)
{
//qDebug()<< "串口打开成功!"
}
my_serialport->close();//关闭串口
5. 数据发送
//write()函数有多个重载,详情可以把光标停在“write”上,按F2跳转到声明即可查看到所有重载函数,选择自己使用的;
char buf[128] = "senddata";
my_serialport->write(buf, sizeof(buf));
6. 数据接收
//read()函数也有多个重载,详情可以把光标停在“read”上,按F2跳转到声明即可查看到所有重载函数,选择自己使用的;
char buf[128] = {0};
my_serialport->write(buf, sizeof(buf));
7. 总结
串口的数据接收通常使用定时器进行不断查询,实现异步通信。
具体可参考我所用的Demo