您现在的位置是:网站首页> C/C++
QT硬件相关编程
- C/C++
- 2022-04-07
- 1111人已阅读
QT读写NFC
QT +=nfc core gui
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNearFieldManager>
#include <QtNfc/qnearfieldtarget.h>
QT_FORWARD_DECLARE_CLASS(QNearFieldManager)
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
QByteArray HexStringToByteArray(QString HexString);
QString ByteArrayToHexString(QByteArray data);
private slots:
void targetDetected(QNearFieldTarget *target);
void targetLost(QNearFieldTarget *target);
private:
QNearFieldManager *m_manager;
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_manager = new QNearFieldManager(this);
if (!m_manager->isAvailable()) {
QMessageBox::information(0, "title", "NFC not available", QMessageBox::Yes, QMessageBox::Yes);
qDebug() << "NFC not available";
return;
}
m_manager->startTargetDetection();
connect(m_manager, &QNearFieldManager::targetDetected,
this, &MainWindow::targetDetected);
connect(m_manager, &QNearFieldManager::targetLost,
this, &MainWindow::targetLost);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::targetDetected(QNearFieldTarget *target)
{
QByteArray m_IDArray=target->uid();
QString sID=ByteArrayToHexString(m_IDArray);
QMessageBox::information(0, "读到卡", sID, QMessageBox::Yes, QMessageBox::Yes);
}
void MainWindow::targetLost(QNearFieldTarget *target)
{
target->deleteLater();
}
QByteArray MainWindow::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 = s.toInt(&ok,16)&0xFF;
if(ok){
ret.append(c);
}else{
//qDebug()<<"非法的16进制字符:"<<s;
QMessageBox::warning(0,tr("错误:"),QString("非法的16进制字符: \"%1\"").arg(s));
}
}
}
//qDebug()<<ret;
return ret;
}
QString MainWindow::ByteArrayToHexString(QByteArray data){
QString ret(data.toHex().toUpper());
int len = ret.length()/2;
//qDebug()<<len;
for(int i=1;i<len;i++)
{
//qDebug()<<i;
ret.insert(2*i+i-1," ");
}
return ret;
}
Qt中低功耗蓝牙模块使用
QT += bluetooth
bluedevice.h
#ifndef BLUEDEVICE_H
#define BLUEDEVICE_H
#include <QObject>
#include<QBluetoothDeviceDiscoveryAgent>
#include<QBluetoothDeviceInfo>
#include<QBluetoothUuid>
#include<QBluetoothServiceInfo>
#include<QLowEnergyController>
#include<QLowEnergyService>
#include<QLowEnergyDescriptor>
class BlueDevice: public QObject{
Q_OBJECT
public:
BlueDevice();
QString getAddress(QBluetoothDeviceInfo device) const;
private:
QList<QBluetoothDeviceInfo> device_list; //存放搜索到到蓝牙设备列表
QBluetoothDeviceDiscoveryAgent *m_deviceDiscoveryAgent; //设备搜索对象
QLowEnergyController *m_controler; //单个蓝牙设备控制器
QLowEnergyService *m_service; //服务对象实例
};
#endif // BLUEDEVICE_H
bluedevice.cpp
#include "bluedevice.h"
#include <QDebug>
#include<QTimer>
BlueDevice::BlueDevice() {
qDebug() << "enter bludedevice constructor....";
m_deviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
m_deviceDiscoveryAgent->setLowEnergyDiscoveryTimeout(5000);
//每次发现新设备时触发
connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this ,[this]() {
qDebug() << "find a new bluebooth device";
});
//蓝牙设备搜索完成后,筛选出目标设备进行连接,并进行相关信号与槽函数的绑定
connect(m_deviceDiscoveryAgent,&QBluetoothDeviceDiscoveryAgent::finished, this, [this]() {
device_list = this->m_deviceDiscoveryAgent->discoveredDevices();
//遍历显示设备详情
QList<QBluetoothDeviceInfo>::iterator it;
for(it=device_list.begin(); it != device_list.end(); it++) {
// 外围蓝牙设备对象
QBluetoothDeviceInfo tmp_device = *it;
QString device_name = tmp_device.name();
//qDebug() <<"device name:::" << device_name;
//qDebug() << "device address:::" << this->getAddress(tmp_device);
//打印搜索出来的全部低功耗蓝牙
if (tmp_device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
qDebug() << " low Energy device ....";
qDebug() <<"22222device name:::" << device_name;
}
//正则匹配目标设备,
QString pattern_str = "^Eric.*"; //qt中正则匹配任意个字符,需要使用.*而不是*
QRegExp rx(pattern_str);
if(!rx.exactMatch(device_name)) {
continue;
}
qDebug() <<"device name:::" << device_name;
qDebug() << "device address:::" << this->getAddress(tmp_device);
// 创建蓝牙设备控制器对象
m_controler = new QLowEnergyController(tmp_device, this);
// 监听目标设备连接成功消息,连接成功后,搜索目标设备等服务列表
connect(m_controler, &QLowEnergyController::connected, this, [this](){
qDebug() << "m_controler connected ......";
//必须要在连接建立后 执行开始寻找service的函数
//之前调试,就是因为没有在设备连接后主动请求获取服务列表信息,后续监听便没有触发
m_controler->discoverServices();
});
// 监听发现服务消息,如果服务的uuid 为约定好的要使用服务类型,则进行后续处理
connect(m_controler,&QLowEnergyController::serviceDiscovered, this, [this](QBluetoothUuid serviceUuid) {
if(serviceUuid == QBluetoothUuid( quint16(0xffd0))) { //我们用的服务类型是0xffd0对应的uuid
//发现匹配的服务后,使用控制器对象创建服务对象
m_service = m_controler->createServiceObject(serviceUuid,this);
if(m_service) {
// 服务对象创建成功后,坚挺服务状态变化,如果状态变成已发现,则进行后续服务下特征对象获取
connect(m_service,&QLowEnergyService::stateChanged, this, [this]() {
qDebug() << "service state change" << m_service->state() << ",||||||";
//发现服务, 建立characteristic对象实例
if(m_service->state() == QLowEnergyService::ServiceDiscovered) {
QLowEnergyCharacteristic hrChar = m_service->characteristic(QBluetoothUuid(quint16(0xfff6)));
if(!hrChar.isValid()) {
qDebug() << "characteristic fff6 error:::";
}
// 设置特征对象可用
//enable the chracteristic notification by write 0x01 to client characteristic configuration
QLowEnergyDescriptor m_notificationDesc = hrChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (m_notificationDesc.isValid()) {
if(hrChar.properties() & QLowEnergyCharacteristic::Notify) {
qDebug() << "";
}
m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100"));
}
}
});
// 通过监听特征对象的变化,不断获得鞋垫压力数据。
connect(m_service,&QLowEnergyService::characteristicChanged, this,
[this](QLowEnergyCharacteristic c,QByteArray value) {
qDebug() << "characteristicChanged state change::" <<c.uuid()<< ",||||||";
qDebug() << "value length::" << value.length();
qDebug() << "value length::" << value;
QByteArray sub_1 = value.mid(0,2);
QByteArray sub_2 = value.mid(2,2);
QByteArray sub_3 = value.mid(4,2);
bool ok;
// num 1,2,3 分别对应三个压力感应点的压力值
int num_1 = QString(sub_1.toHex()).toInt(&ok,16);
qDebug() << "num_1:::" << num_1;
int num_2 = QString(sub_2.toHex()).toInt(&ok,16);
qDebug() << "num_1:::" << num_2;
int num_3 = QString(sub_3.toHex()).toInt(&ok,16);
qDebug() << "num_1:::" << num_3;
}
);
// 触发服务详情发现函数 ,不要忘记调用
m_service->discoverDetails();
}
}
});
connect(m_controler,&QLowEnergyController::discoveryFinished, this, [this]() {
qDebug() << "finish service discovery";
});
//连接外围设备
m_controler->connectToDevice();
//QTimer *timer = new QTimer(this);
//connect(timer, &QTimer::timeout, this, [this](){ qDebug() <<"state:::" << this->m_controler->state();});
//timer->start(1000);
}
});
// 开始外围设备搜索
m_deviceDiscoveryAgent->start();
}
// mac和其他系统上address获取有少许差异,参见官方文档
QString BlueDevice::getAddress(QBluetoothDeviceInfo device) const
{
#ifdef Q_OS_MAC
// On OS X and iOS we do not have addresses,
// only unique UUIDs generated by Core Bluetooth.
return device.deviceUuid().toString();
#else
return device.address().toString();
#endif
}
//void BlueDevice::getNewService(QBluetoothServiceInfo info) {
// qDebug() << "ppppp uuuuuuuuuu";
//}
Qt 串口通信(QSerialPort)
QT += serialport
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QComboBox>
#include <QPushButton>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void initUI();
QStringList getPortNameList();//获取所有可用的串口列表
void openPort();//打开串口
public slots:
void receiveInfo();
private:
Ui::Widget *ui;
QSerialPort* m_serialPort; //串口类
QStringList m_portNameList;
QComboBox* m_PortNameComboBox;
QPushButton* m_OpenPortButton;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QLayout>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_serialPort = new QSerialPort();
initUI();
m_portNameList = getPortNameList();
m_PortNameComboBox->addItems(m_portNameList);
connect(m_OpenPortButton,&QPushButton::clicked,this,&Widget::openPort);
}
Widget::~Widget()
{
if (m_serialPort->isOpen())
{
m_serialPort->close();
}
delete m_serialPort;
delete ui;
}
void Widget::initUI()
{
this->setWindowTitle("码农小明 test QSerialPort");
m_OpenPortButton = new QPushButton();
m_OpenPortButton->setText("打开串口");
m_PortNameComboBox = new QComboBox();
QHBoxLayout *m_layout = new QHBoxLayout();
m_layout->addWidget(m_PortNameComboBox);
m_layout->addWidget(m_OpenPortButton);
this->setLayout(m_layout);
}
QStringList Widget::getPortNameList()
{
QStringList m_serialPortName;
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
m_serialPortName << info.portName();
qDebug()<<"serialPortName:"<<info.portName();
}
return m_serialPortName;
}
void Widget::openPort()
{
if(m_serialPort->isOpen())//如果串口已经打开了 先给他关闭了
{
m_serialPort->clear();
m_serialPort->close();
}
m_serialPort->setPortName(m_PortNameComboBox->currentText());//当前选择的串口名字
if(!m_serialPort->open(QIODevice::ReadWrite))//用ReadWrite 的模式尝试打开串口
{
qDebug()<<"打开失败!";
return;
}
qDebug()<<"串口打开成功!";
m_serialPort->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);//设置波特率和读写方向
m_serialPort->setDataBits(QSerialPort::Data8); //数据位为8位
m_serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
m_serialPort->setParity(QSerialPort::NoParity); //无校验位
m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
}
//接收到单片机发送的数据进行解析
void Widget::receiveInfo()
{
QByteArray info = m_serialPort->readAll();
qDebug()<<"receive info:"<<info;
}
m_serialPort->write("ccc");
m_serialPort->flush();
下一篇:QT实测经验教训