"""
深圳市普中科技有限公司(PRECHIN 普中)
技術支援:www.prechin.net
PRECHIN
普中
實驗名稱:藍牙BLE通信
https://wokwi.com/projects/385882678121037825
接線說明:LED模組-->ESP32 IO
(D1)-->(15)
KEY模組-->ESP32 IO
(K1)-->(14)
實驗現象:程式下載成功後,軟體shell控制台輸出藍牙BLE名稱“ESP32BLE”,D1指示燈快閃,等待APP藍牙連接。
安卓手機系統,打開應用市場,搜索“BLE藍牙調試助手”下載,打開該APP,選擇藍牙名稱為“ESP32BLE”
連接,然後按照實驗現象操作即可。
注意事項:
"""
#導入Pin模組
from machine import Pin, Timer
from time import sleep_ms
import ubluetooth
BLE_MSG = ""
class ESP32_BLE():
def __init__(self, name):
self.name = name
self.ble = ubluetooth.BLE()
self.ble.active(True)
self.ble.config(gap_name=name)
# On-board LED pin (GPIO2 on many ESP32 boards)
self.led = Pin(2, Pin.OUT)
# Timer for blinking the LED when disconnected
self.timer1 = Timer(0)
# Start with disconnected blink pattern
self.disconnected()
# Register IRQ callback before registering services
self.ble.irq(self.ble_irq)
# Setup Nordic UART GATT service
self.register()
self.ble.gatts_write(self.rx, bytes(100)) #修改一次最大接收位元組數100
# Begin advertising
self.advertiser()
self.bleMsg = "" #接收的消息字符串
self.bleconnected = False
def connected(self):
self.led.value(1)
self.timer1.deinit()
self.bleconnected = True
def disconnected(self):
self.timer1.init(period=100, mode=Timer.PERIODIC,
callback=lambda t: self.led.value(not self.led.value()))
self.bleconnected = False
def ble_irq(self, event, data):
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)
self.bleMsg = buffer.decode('UTF-8').strip()
print("Received over BLE:", self.bleMsg)
def register(self):
# NUS base UUID and characteristic UUIDs
service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
services = (
(
ubluetooth.UUID(service_uuid), #服務ID,可以定義多個服務
(
(ubluetooth.UUID(sender_uuid), ubluetooth.FLAG_NOTIFY),
(ubluetooth.UUID(reader_uuid), ubluetooth.FLAG_WRITE),
)
),
)
# Register GATT services and save characteristic handles
((self.tx, self.rx,),) = self.ble.gatts_register_services(services)
def send(self, data):
#發送數據
if self.bleconnected == True :
self.ble.gatts_notify(0, self.tx, data + '\n')
def advertiser(self):
#廣播藍牙
name = bytes(self.name, 'UTF-8')
adv_data = bytearray(b'\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name
self.ble.gap_advertise(100, adv_data) #100us發佈一次廣播
print(adv_data + "\r\n")
def buttons_irq(pin):
led.value(not led.value())
print('LED is ON.' if led.value() else 'LED is OFF')
ble.send('LED is ON.' if led.value() else 'LED is OFF')
if __name__ == "__main__":
but = Pin(35, Pin.IN)
but.irq(trigger=Pin.IRQ_FALLING, handler=buttons_irq)
led = Pin(15, Pin.OUT)
# Create and start BLE UART device named "ESP32BLE"
ble = ESP32_BLE("ESP32BLE")
print("connected ....")
while True:
if(len(ble.bleMsg)>0):
if ble.bleMsg == 'read_LED':
#打印獲取到的數據
print(ble.bleMsg)
# 清空接收的數據
ble.bleMsg = ""
print('LED is ON.' if led.value() else 'LED is OFF')
ble.send('LED is ON.' if led.value() else 'LED is OFF')
sleep_ms(100)