一、目的
使用Micropython开发,控制FireBeetle 2 ESP32-S3开发板上的蓝牙,从而与手机APP通信。
二、BLE
蓝牙通讯技术不必多赘述。
蓝牙规范一般将蓝牙3.0 之前的BR/EDR蓝牙称为传统蓝牙 ,而将蓝牙4.0 之后的LE蓝牙称为低功耗蓝牙 (BLE)
三、手机APP
IOS APP
Android APP
四、代码
注意:请使用最新的MicroPython固件(老版本估计可能出现一些问题)
下面代码是运行在固件:v1.20.0(2023-04-26)
import time
from machine import Pin
from machine import Timer
from time import sleep_ms
import bluetooth
BLE_MSG = ""
class ESP32_BLE:
def __init__(self, name):
self.led = Pin(21, Pin.OUT)
self.timer1 = Timer(0)
self.name = name
self.ble = bluetooth.BLE()
self.ble.active(True)
self.connections = set()
self.ble.config(gap_name=name)
self.disconnected()
self.ble.irq(self.ble_irq)
self.register()
self.advertiser()
def connected(self):
self.led.value(1)
self.timer1.deinit()
def disconnected(self):
self.timer1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))
def ble_irq(self, event, data):
global BLE_MSG
if event == 1:
self.connected()
elif event == 2:
self.advertiser()
self.disconnected()
elif event == 3:
buffer = self.ble.gatts_read(self.rx)
BLE_MSG = buffer.decode('UTF-8').strip()
def register(self):
service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
services = (
(
bluetooth.UUID(service_uuid),
(
(bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY),
(bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
)
),
)
((self.tx, self.rx,),) = self.ble.gatts_register_services(services)
def send(self, data):
self.ble.gatts_notify(0, self.tx, data)
def advertiser(self):
name = bytes(self.name, 'UTF-8')
adv_data = bytearray(u'\\x02\\x01\\x02'.encode('utf-8')) + bytearray((len(name) + 1, 0x09)) + name
self.ble.gap_advertise(100, adv_data)
print(adv_data)
print("\\r\\n")
def buttons_irq(pin):
time.sleep_ms(50)
led.value(not led.value())
print('LED is ON.' if led.value() else 'LED is OFF')
if __name__ == "__main__":
ble = ESP32_BLE("ESPTest")
but = Pin(47, Pin.IN)
but.irq(trigger=Pin.IRQ_FALLING, handler=buttons_irq)
led = Pin(21, Pin.OUT)
while True:
if BLE_MSG == 'ledState':
print("Command: " + BLE_MSG)
BLE_MSG = ""
print('LED state on\\n' if led.value() else 'led state is off\\n')
elif BLE_MSG == 'ledON':
print("Command: " + BLE_MSG)
BLE_MSG = ""
if led.value() != 1:
led.value(1)
print('led is on\\n' if led.value() else 'led is off\\n')
elif BLE_MSG == 'ledOFF':
print("Command: " + BLE_MSG)
BLE_MSG = ""
if led.value() != 0:
led.value(0)
print('led is on\\n' if led.value() else 'led is off\\n')
sleep_ms(100)
五、运行效果(视频)
连接+调试
|