C++ and QT SerialPort demo

55 篇文章 0 订阅
16 篇文章 1 订阅

Serial port is a tool that PC often interacts with MCU.Then,I'm going to write a simple demo with C++ and QT.

I mainly introduce the code , UI design, please solve by yourself.

Let's go:

  • import the lib.----->
#include <QtSerialPort\qserialport.h>
#include <QtSerialPort\qserialportinfo.h>
  • design the function----->
//------------------------------------------
void FindSerial();//查找串口号
void DeletePullSerial();//删除拔出的串口USB
void InitComboBox();//初始化选择框索引
void InitSerial();//串口初始化
//------------------------------------------
  • Definition of variables----->
private:
//------------------------------------------
QSerialPort *serial;//定义一个串口对象
QTimer TimerSerial;//定时器
QByteArray RxData;//定义字节数组保存串口发送过来的数据

uint64_t ReceivDatSize;//接收到的总字节数
//------------------------------------------
  • UI initialization needs to add serial port timing serial port scan----->You can see the structure of the code as the following:

Cameratest::Cameratest(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
}
  •  Append the following code,below the ui.setupUi(this);
OnButtonSingalSlotInit(); //Singal --- Slot
serial = new QSerialPort(this);//动态分配
//============================================================================
//------------------------------------------------------------
QIcon icon("./Camera_48px.ico");
setWindowIcon(icon);
//------------------------------------------------------------	
TimerSerial.start(1500);//需要通过定时器延时动态扫描串口拔插
FindSerial();//查找串口号
InitComboBox();//初始化串口信息
//下位机发送信号过来触发信号
QObject::connect(serial, &QSerialPort::readyRead, this, &Cameratest::ReadData);
//定时器信号 用来扫描串口
connect(&TimerSerial, &QTimer::timeout,
	[=]()
{
	FindSerial();//查找串口号		
});
//============================================================================
  •  The function to achieve:

(1)FindSerial function,The method of automatically finding available serial ports is set directly and automatically.Return true on success or false otherwise.you can refer to the following code:

void Cameratest::FindSerial()
{
	//自动寻找可用串口的方法 直接自动设置
	foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
	{
		QSerialPort serial;
		serial.setPort(info);

		//如果成功,则返回true否则返回false
		if (serial.open(QIODevice::ReadWrite))
		{
			int itemnumber = ui.SerialPortNum->count();//获取当前列表个数

			int Noitem = 0;//标志位判断是否已经添加
			for (int i = 0; i < itemnumber; i++)//遍历当前保存的所有项目
			{
				if (ui.SerialPortNum->itemText(i) == serial.portName())//如果查找到可用串口当前标志位加1
				{
					Noitem++;
				}
			}
			//标志位等于0表明当前查找到串口,可添加
			if (Noitem == 0)
			{
				Noitem = 0;
				ui.SerialPortNum->addItem(serial.portName());
			}
			DeletePullSerial();//删除拔出的USB串口
			serial.close();
		}
	}
}

(2)DeletePullSerial Function:you can refer to the following code:No serial number can be deleted automatically

void Cameratest::DeletePullSerial()
{
	int DeleNumber = 0;
	foreach(const QSerialPortInfo &info1, QSerialPortInfo::availablePorts())
	{
		QSerialPort serial;
		serial.setPort(info1);
		if (ui.SerialPortNum->itemText(DeleNumber) != serial.portName())
		{
			ui.SerialPortNum->removeItem(DeleNumber);
		}
		DeleNumber++;
	}
	DeleNumber = 0;
}

 (3)The serial port initializes the relevant functions----->You can see the structure of the code as the following:you can set the baudrate、databits、parity、stopbits、flowcontrol.

void Cameratest::InitComboBox()
{
	//设置波特率  
	serial->setBaudRate(38400);//38400
	//设置数据位数  
	serial->setDataBits(QSerialPort::Data8);
	//设置奇偶校验  
	serial->setParity(QSerialPort::NoParity);
	//设置停止位  
	serial->setStopBits(QSerialPort::OneStop);
	//设置流控制  
	serial->setFlowControl(QSerialPort::NoFlowControl);
}
void Cameratest::InitSerial()
{
	//1、设置串口
	serial->setPortName(ui.SerialPortNum->currentText());
	//2、打开串口
	if (!serial->open(QIODevice::ReadWrite))
	{
		ui.Record->append("串口打开失败");
	}
	else
	{
		ui.Record->append("串口打开成功");
	}
	//3、设置波特率
	serial->setBaudRate(38400);//38400
	//4、设置校验位
	serial->setParity(QSerialPort::NoParity);
	//5、设置数据位
	serial->setDataBits(QSerialPort::Data8);
	//6、设置停止位  
	serial->setStopBits(QSerialPort::OneStop);
	//7、设置流控制  
	serial->setFlowControl(QSerialPort::NoFlowControl);
}

 (4)singal and slot,you can the  use this code to connect the slot function:the singal you  can use the readRead,After the PC receives the data, it directly triggers the signal and connects the ReadData Function:

QObject::connect(serial, &QSerialPort::readyRead, this, &Cameratest::ReadData);

(5)ReadData Function :you can refer to the following code:

void Cameratest::ReadData()
{
	RxData = serial->readAll();
	ReceivDatSize += RxData.size();//统计接收字符大小
	if (RxData.isEmpty())//如果没有数据退出减少吗、内存占用
	{
		return;
	}
    //-----------------------------------------
    // other code
    //-----------------------------------------
	
}

 (6)How do you process the received data?You can follow my process of thought----->

//E5 5E 06 01 0D 0E 
if ((RxData.data()[1] == 0xE5))
{
	;
}

 (7)PC data to the MCU:

serial->write(RxData);

(8)Add processing code according to your own requirements

I hope I can help you,If you have any questions, please  comment on this blog or send me a private message. I will reply in my free time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值