|
各位老师好!
近期想用MicroPython在ESP32-S3硬件平台开发"蓝牙透传功能",下面是我写的代码,我是参考官方手册来写的(bluetooth — 低级蓝牙 — MicroPython中文 1.17 文档) ,但是 跑到ble.send() 的时候会报错 ,请大家帮忙看看,感谢!
另外还有个小问题:我在开发ESP32-S3的时候,不知道 当前版本的固件,能够支持哪些Micropython模块, 有时候就发现 同样的程序 1.20.0 版本不能运行,1.19.0版本又可以运行, 不知道MicroPython固件版本的差异点在哪,我要如何参考当前版本进行开发? 球球了,救救孩子吧
from machine import Pin
from machine import Timer
from time import sleep_ms
from machine import UART
import bluetooth
import binascii
BLE_STA = 0
BLE_MSG = ""
UART_MSG = ""
# 初始化串口
uart1 = UART(1, baudrate=9600, rx=11, tx=10, bits=8, parity=None, stop=1)
class ESP32_BLE():
def __init__(self, name):
self.led = Pin(2, Pin.OUT)
self.timer0 = Timer(0)
self.name = name
self.ble = bluetooth.BLE()
self.ble.active(True)
self.ble.config(gap_name=name)
self.disconnected()
self.ble.irq(self.ble_irq)
self.register()
self.advertiser()
def connected(self):
global BLE_STA
self.led.value(1)
self.timer0.deinit()
BLE_STA = 1
print('连接成功')
def disconnected(self):
global BLE_STA
self.timer0.init(period=250, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))
BLE_STA = 0
print('断开连接')
def ble_irq(self, event, data):
global BLE_MSG
if event == 1: # _IRQ_CENTRAL_CONNECT 手机链接了此设备
self.connected()
elif event == 2: # _IRQ_CENTRAL_DISCONNECT 手机断开此设备
self.advertiser()
self.disconnected()
elif event == 3: # _IRQ_GATTS_WRITE 手机发送了数据
buffer = self.ble.gatts_read(self.rx)
BLE_MSG = buffer.decode('UTF-8').strip()
MSG_hex = binascii.hexlify(BLE_MSG).decode()
# 转换为十六进制
uart1.write(MSG_hex)
print("蓝牙接收到数据:", MSG_hex)
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):
data_bytes = bytes(data + '\n', 'UTF-8')
self.ble.gatts_notify(0, self.tx, data_bytes)
def advertiser(self):
name = bytes(self.name, 'UTF-8')
adv_data = bytearray('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name
self.ble.gap_advertise(100, adv_data)
print(adv_data)
print("\r\n")
if __name__ == "__main__":
ble = ESP32_BLE("NKD5-S")
while True:
if uart1.any():
UART_MSG = uart1.read()
if BLE_STA == 1:
print("连接蓝牙,转发数据")
ble.send("123 22")
else:
print("未连接,不转发")
print("串口接收到数据:", UART_MSG)
UART_MSG = ""
sleep_ms(100)
|
|