Ai
1 Star 0 Fork 0

bigzhu/step-fpga-ctrl

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
serial.cpp 2.90 KB
一键复制 编辑 原始数据 按行查看 历史
bigzhu 提交于 2024-03-06 13:26 +08:00 . first commit
#include "serial.h"
Serial::Serial()
{
m_serialPort = new QSerialPort;
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
connect(m_timer, &QTimer::timeout, this, [=]() {
m_readBuf.append(m_serialPort->readAll());
emit readSignal();
});
}
Serial::~Serial()
{
delete m_serialPort;
m_timer->stop();
delete m_timer;
}
// 扫描可用串口
QStringList Serial::scanSerial()
{
QStringList serialStrList;
// 读取串口信息
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
m_serialPort->setPort(info);
serialStrList.append(m_serialPort->portName());
}
return serialStrList;
}
// 打开串口
bool Serial::open(QString serialName, int baudRate)
{
// 设置串口名
m_serialPort->setPortName(serialName);
// 打开串口(以读写方式)
if(m_serialPort->open(QIODevice::ReadWrite))
{
m_serialPort->setBaudRate(baudRate); // 设置波特率(默认为115200)
m_serialPort->setDataBits( QSerialPort::Data8); // 设置数据位(数据位为8位)
m_serialPort->setParity( QSerialPort::NoParity); // 设置校验位(无校验位)
m_serialPort->setStopBits( QSerialPort::OneStop); // 设置停止位(停止位为1)
m_serialPort->setFlowControl( QSerialPort::NoFlowControl); // 设置流控制(无数据流控制)
// 当下位机中有数据发送过来时就会响应这个槽函数
connect(m_serialPort, SIGNAL(readyRead()), this, SLOT(readData()));
return true;
}
return false;
}
// 关闭串口
void Serial::close()
{
m_timer->stop();
m_serialPort->clear();
m_serialPort->close();
}
// 发送数据给下位机
void Serial::sendData(QByteArray &sendData)
{
// 发送数据帧
if (m_serialPort->isWritable()) {
m_serialPort->write(sendData);
}
}
// 读取下位机发来数据
void Serial::readData()
{
// 超时50毫秒再去读取
m_timer->start(10);
m_readBuf.append(m_serialPort->readAll());
}
// 获得读取数据缓冲区
QByteArray Serial::getReadBuf()
{
return m_readBuf;
}
// 清除读取数据缓冲区
void Serial::clearReadBuf()
{
m_readBuf.clear();
}
// 将16进制字符串转换为对应的字节序列
QByteArray Serial::hexStringToByteArray(QString HexString)
{
bool ok;
QByteArray ret;
HexString = HexString.trimmed();
HexString = HexString.simplified();
QStringList sl = HexString.split(" ");
foreach (QString s, sl)
{
if(!s.isEmpty())
{
char c = static_cast<char>(s.toInt(&ok, 16) & 0xFF);
if(ok)
{
ret.append(c);
}
else
{
qDebug()<<"非法的16进制字符:"<<s;
QMessageBox::warning(nullptr, tr("错误:"), QString("非法的16进制字符: \"%1\"").arg(s));
}
}
}
return ret;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/bigstep/step-fpga-ctrl.git
git@gitee.com:bigstep/step-fpga-ctrl.git
bigstep
step-fpga-ctrl
step-fpga-ctrl
master

搜索帮助