一、Qt建立藍(lán)牙通信
Qt具有跨平臺(tái)的特性所以非常適合寫通信的demo,但是在這個(gè)例程中Qt藍(lán)牙部分不支持Windows平臺(tái),安卓平臺(tái)使用沒問題。
Qt藍(lán)牙主要涉及到三個(gè)類的使用:
QBluetoothDeviceDiscoveryAgent //掃描周圍藍(lán)牙設(shè)備
QBluetoothLocalDevice //掃描本地藍(lán)牙
QBluetoothSocket //建立藍(lán)牙的socket讀寫
安卓不支持低功耗藍(lán)牙,但是socket既可以使用經(jīng)典藍(lán)牙也可以使用低功耗藍(lán)牙,本例程使用經(jīng)典藍(lán)牙socket收發(fā)數(shù)據(jù)
1、在.pro工程文件添加
Qt +=bluetooth
2、主要代碼Widget.h和Widget.c
#ifndef WIDGET_H
#define WIDGET_H
#pragma execution_character_set("utf-8") //解決中文亂碼
#include <QWidget>
#include <QObject>
#include <QtBluetooth/qbluetoothlocaldevice.h>
#include <qbluetoothaddress.h>
#include <qbluetoothdevicediscoveryagent.h>
#include <qbluetoothlocaldevice.h>
#include <qbluetoothsocket.h>
#include <QMap>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void model2_Init();
public slots:
void addBlueToothDevicesToList(const QBluetoothDeviceInfo&);
void readBluetoothDataEvent();
void bluetoothConnectedEvent();
void bluetoothDisconnectedEvent();
void onError(QBluetoothSocket::SocketError error);
void open_BLE();
void close_BLE();
void scanFinished();
private:
QBluetoothDeviceDiscoveryAgent *discoveryAgent;
QBluetoothLocalDevice *localDevice;
QBluetoothSocket *socket;
QByteArray blueArray;
QMap<QString,QBluetoothAddress>m;
QBluetoothDeviceInfo remoteDeviceInfo;
float ff;//隨機(jī)數(shù)緩存
float div;//每次下降數(shù)
float sx;//上限
float t;//時(shí)間
QString ss;//字符判斷是模式1還是模式2
QTimer *time;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void on_pushButton_5_clicked();
void on_pushButton_3_clicked();
void on_pushButton_7_clicked();
void on_pushButton_8_clicked();
void on_pushButton_9_clicked();
void on_pushButton_6_clicked();
void timeProcess();
void on_pushButton_10_clicked();
void on_label_7_linkActivated(const QString &link);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
## Widget.c
#include "widget.h"
#include "ui_widget.h"
#include <QRandomGenerator>
#include <QLowEnergyController>
//這個(gè)UUID要根據(jù)自己的使用情況來確定,我使用的是串口類的UUID,具體可https://www.jianshu.com/p/eb85cb690e86
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
//static const QLatin1String serviceUuid("FDA50693A4E24FB1AFCFC6EB07647825");
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->plainTextEdit->setDisabled(1);
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
localDevice = new QBluetoothLocalDevice(this);
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
time = new QTimer(this);
connect(time,SIGNAL(timeout()),this,SLOT(timeProcess()));
discoveryAgent->start();
ui->pushButton_4->setDisabled(1);
connect(discoveryAgent, SIGNAL(finished()), this, SLOT(scanFinished()));//搜索結(jié)束
connect(discoveryAgent,
SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this,
SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
);
connect(socket,SIGNAL(readyRead()),
this,
SLOT(readBluetoothDataEvent())
);
connect(socket,SIGNAL(connected()),
this,
SLOT(bluetoothConnectedEvent())
);
connect(socket,SIGNAL(disconnected()),
this,
SLOT(bluetoothDisconnectedEvent())
);
connect(socket,SIGNAL(error(QBluetoothSocket::SocketError)),this,SLOT(onError(QBluetoothSocket::SocketError)));
}
Widget::~Widget()
{
delete ui;
delete discoveryAgent;
delete localDevice;
delete socket;
delete time;
}
void Widget::onError(QBluetoothSocket::SocketError error)
{
QString str;
if(QBluetoothSocket::UnknownSocketError == error){
str = "UnknownSocketError";
}else if(QBluetoothSocket::NoSocketError == error){
str = "NoSocketError";
}else if(QBluetoothSocket::HostNotFoundError == error){
str = "HostNotFoundError";
}else if(QBluetoothSocket::ServiceNotFoundError == error){
str = "ServiceNotFoundError";
}else if(QBluetoothSocket::NetworkError == error){
str = "NetworkError";
}else if(QBluetoothSocket::UnsupportedProtocolError == error){
str = "UnsupportedProtocolError";
}else if(QBluetoothSocket::OperationError == error){
str = "OperationError";
}else if(QBluetoothSocket::RemoteHostClosedError == error){
str = "RemoteHostClosedError";
}
qDebug()<<error;
//emit backendRunMesgPost(str);
//emit backendRunMesgPost("SocketError");
}
void Widget::addBlueToothDevicesToList( const QBluetoothDeviceInfo &info )
{
remoteDeviceInfo = info;
qDebug()<<"進(jìn)入addBlueToothDevicesToList函數(shù)!";
QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
qDebug()<<label;
ui->comboBox->addItem(info.name());
if(label.contains("BT04-A")){
//找到需要連接的藍(lán)牙名字
int index = label.indexOf(' ');
if(index == -1){
qDebug()<<"index";
return;
}
QBluetoothAddress address(label.left(index));
m[info.name()] = address;//關(guān)聯(lián)藍(lán)牙名字和address
QString name(label.mid(index + 1));
qDebug() << "You has choice the bluetooth address is " << address<<name<<endl;
//qDebug() << "The device is connneting.... ";
//ui->plainTextEdit_2->setPlainText("You has choice the bluetooth address is "+name);
//ui->plainTextEdit_2->setPlainText("The device is connneting.... ");
//emit backendRunMesgPost("The device is connneting");
//socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
}
}
void Widget::readBluetoothDataEvent()
{
static int cnt = 0;
QByteArray line = socket->readAll();
if(line.startsWith("y") || line.startsWith("r"))
ss = line;
if(ss.startsWith("y"))
{
//ss = "d";
if(!line.startsWith('y'))
{
blueArray.append(line);
}
if(cnt < 4)
{
ui->plainTextEdit->appendPlainText(QString(blueArray));
cnt++;
}
else
{
cnt = 0;
ui->plainTextEdit->clear();
}
//ui->plainTextEdit->setPlainText(QString(blueArray));
ui->plainTextEdit_2->setPlainText("模式1");
emit ui->pushButton_3->clicked(1);
}
else if(ss.startsWith("r"))
{
ss = "d";
ui->plainTextEdit_2->setPlainText("模式2");
model2_Init();
emit ui->pushButton_10->clicked(1);
emit ui->pushButton_7->clicked(1);
ss = "d";
}
else if(line.startsWith("Flash"))
{
ui->plainTextEdit_2->setPlainText(QString(line));
ss = "d";
}
}
void Widget::bluetoothConnectedEvent()
{
qDebug() << "The android device has been connected successfully!";
ui->plainTextEdit_2->setPlainText("The android device has been connected successfully!");
}
void Widget::bluetoothDisconnectedEvent()
{
qDebug() << "The android device has been disconnected successfully!";
}
void Widget::open_BLE()
{
if( localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)//開機(jī)沒有打開藍(lán)牙
{
localDevice->powerOn();//調(diào)用打開本地的藍(lán)牙設(shè)備
discoveryAgent->start();//開始掃描藍(lán)牙
connect(discoveryAgent,
SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this,
SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
);
ui->plainTextEdit_2->setPlainText("手機(jī)藍(lán)牙已成功打開!");
}
else
{
qDebug() << "手機(jī)藍(lán)牙已成功打開!";
ui->plainTextEdit_2->setPlainText("手機(jī)藍(lán)牙已成功打開!");
}
}
void Widget::close_BLE()
{
socket->close();
ui->plainTextEdit_2->setPlainText("藍(lán)牙已斷開!");
}
void Widget::on_pushButton_clicked()//模式一
{
//ui->plainTextEdit->clear();
ui->pushButton_2->setDisabled(1);
ui->pushButton_7->setDisabled(1);
socket->write("y");
}
void Widget::on_pushButton_2_clicked()//模式二
{
model2_Init();
ui->pushButton->setDisabled(1);
ui->pushButton_3->setDisabled(1);
if(socket->state() == QAbstractSocket::ConnectedState)
{
socket->write("r");
}
}
void Widget::on_pushButton_4_clicked()//連接藍(lán)牙
{
discoveryAgent->stop();
if(ui->comboBox->currentText().startsWith("BT04-A"))
{
//低功耗藍(lán)牙連接方式
/*QLowEnergyController *lowBtControl = QLowEnergyController::createCentral(remoteDeviceInfo);
lowBtControl->connectToDevice();
*/
//經(jīng)典藍(lán)牙連接方式
qDebug() << "連接到的藍(lán)牙是" << m[ui->comboBox->currentText()]<<ui->comboBox->currentText();
socket->connectToService(m[ui->comboBox->currentText()],QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
ui->plainTextEdit_2->setPlainText("The device is connneting.... ");
if(socket->state() == QAbstractSocket::ConnectedState)
ui->plainTextEdit_2->setPlainText("藍(lán)牙連接成功!");
}
else
{
ui->plainTextEdit_2->setPlainText("沒有找到目標(biāo)藍(lán)牙!");
}
}
void Widget::on_pushButton_5_clicked()//斷開連接
{
close_BLE();
}
void Widget::on_pushButton_3_clicked()//模式一修改數(shù)字
{
if(socket->write("v"))
{
QString str;
str = ui->lineEdit_6->text();
str.append('z');
socket->write(str.toUtf8());
ui->plainTextEdit_2->setPlainText("成功發(fā)送一條數(shù)據(jù)!v");
}
}
void Widget::on_pushButton_7_clicked()
{
if(socket->write("s"))//發(fā)送隨機(jī)數(shù)
{
QString str = QString("%1").arg(sx);
if(str.length() > 4)
str = str.left(4);
str.append('x');
socket->write(str.toUtf8());
}
}
void Widget::on_pushButton_8_clicked()//切換模式
{
ui->pushButton->setEnabled(1);
ui->pushButton_2->setEnabled(1);
ui->pushButton_7->setEnabled(1);
ui->pushButton_3->setEnabled(1);
ui->plainTextEdit->setEnabled(1);
ui->plainTextEdit->clear();
ui->plainTextEdit->setDisabled(1);
time->stop();
}
void Widget::on_pushButton_9_clicked()
{
open_BLE();
}
void Widget::on_pushButton_6_clicked()
{
this->close();
}
void Widget::scanFinished()
{
ui->pushButton_4->setEnabled(1);
}
void Widget::timeProcess()
{
sx = sx - div;
QString str;
str = QString("%1").arg(sx);
qDebug()<<"sx is " + str<<endl;
if(sx <= ff)
{
sx = ff;
time->stop();
}
ui->plainTextEdit_2->setPlainText("成功發(fā)送一條數(shù)據(jù)!s"+str);
str = QString("%1").arg(div);
qDebug()<<"div is " + str<<endl;
emit ui->pushButton_7->clicked(1);
}
void Widget::model2_Init()
{
sx = ui->lineEdit_3->text().toUInt();
t = ui->lineEdit_4->text().toUInt();
div = (sx - ff)/(t*10);
}
void Widget::on_pushButton_10_clicked()
{
if(ui->lineEdit->text().isEmpty() == false && ui->lineEdit_2->text().isEmpty() == false )
{
std::uniform_real_distribution<float> dist(ui->lineEdit->text().toUInt(), ui->lineEdit_2->text().toUInt());
ff = dist(*QRandomGenerator::global());
ui->lineEdit_5->setText(QString::number(ff));
QString str = ui->lineEdit_5->text();
if(str.length() > 4)
str = str.left(4);
ff = str.toFloat();
ui->lineEdit_5->setText(QString::number(ff));
if(ui->lineEdit_3->text().isEmpty() == false && ui->lineEdit_4->text().isEmpty() == false)
{
time->start(6000);
}
}
}
二、通過藍(lán)牙模塊控制stm32f103c8t6驅(qū)動(dòng)VFD
藍(lán)牙模塊選擇BT08B藍(lán)牙串口模塊兼容HC-06,只需連接四個(gè)引腳 VCC 、GND、TX、RX即可文章來源:http://www.zghlxwxcb.cn/news/detail-482761.html
下面為VFD模塊驅(qū)動(dòng)程序,采用帶驅(qū)動(dòng)芯片的模塊,直流5V供電即可,stm32可直接驅(qū)動(dòng)模塊引出引腳文章來源地址http://www.zghlxwxcb.cn/news/detail-482761.html
1、VFD_Drive.h
#ifndef _VFD_DRIVE_H
#define _VFD_DRIVE_H
#include "stm32f10x.h"
void VFD_GPIOInit(void);//GPIO初始化
void WriteCMD(u8 cmd);//寫命令
void WriteDATA(u8 data);//寫數(shù)據(jù)
void Clear(void);//清屏
void Cursor_home(void);//光標(biāo)歸位
/*
該指令選擇在每次DDRAM或CGRAM訪問后AC(游標(biāo)位置)是遞增還是遞減,并確定在每次DDRAM寫入后顯示信息的移動(dòng)方向。
該指令還在每次DDRAM寫入后啟用或禁用顯示移位。
*/
void IncCursor(void);//光標(biāo)遞增(向右)
void DecCursor(void);//光標(biāo)遞減(向左)
void DisplayOFForON(u8 i,u8 j,u8 n);//光標(biāo)顯示還是不顯示,i = 1顯示i = 0不顯示,并指定是否閃爍j = 1閃爍,j = 0閃爍,n=1開光標(biāo),n=0關(guān)光標(biāo)
/*
該指令增加或減少AC(光標(biāo)位置),并將顯示信息向左或向右移動(dòng)一個(gè)字符的位置
*/
void CharLeft(void);//字符和光標(biāo)左移
void CharRight(void);//字符和光標(biāo)右移
void CursorLeft(void);//光標(biāo)左移
void CursorRight(void);//光標(biāo)右移
/*
設(shè)置并行口模式DL = 0為4位模式,DL = 1為8位模式
設(shè)置單行顯示還是兩行顯示,N = 0,單行顯示,N = 1兩行顯示
設(shè)置亮度BR = 0 100%亮度,BR = 1 75%亮度,BR = 2 50%亮度,BR = 3 25%亮度
*/
void FunSet(u8 DL,u8 N,u8 BR);//這里固定為兩行顯示,亮度100%,如需更改請(qǐng)查看手冊(cè)重寫函數(shù)
/*該指令將DB5-DB0指定的6位CGRAM地址放入AC(光標(biāo)位置)。后續(xù)的數(shù)據(jù)寫入(讀取)將會(huì)指向(從)CGRAM。*/
u8 CGRAM_addrSet(u8 addr);//返回傳入addr后的命令
/*該指令將DB6-DB0指定的7位DDRAM地址放入AC(光標(biāo)位置)。后續(xù)的數(shù)據(jù)寫入(讀取)將從DDRAM寫入(從DDRAM讀取)。*/
u8 DDRAM_addrSet(u8 addr);//返回傳入addr后的命令
/*該指令將DB7-DB0上的8位數(shù)據(jù)字節(jié)寫入AC尋址的DDRAM或CGRAM位置。
最近的DDRAM或CGRAM地址集指令決定是寫入DDRAM還是CGRAM。
該指令還根據(jù)輸入模式設(shè)置(Entry
到了這里,關(guān)于Qt實(shí)現(xiàn)安卓手機(jī)藍(lán)牙通信并控制stm32f103c8t6驅(qū)動(dòng)VFD屏的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!