import neopixel from machine import UART,Pin import time import urandom from machine import Timer import bluetooth BLE_MSG = "" GBIO_IN = Pin(15) # 控制信号输入引脚 LED_NUM = 30 # LED灯的数量 uart = UART(2, 115200) np = neopixel.NeoPixel(GBIO_IN, LED_NUM) class ESP32_BLE(): def __init__(self, name): self.led = Pin(2, Pin.OUT) self.timer1 = 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): 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: #_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() 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 + '\n') def advertiser(self): name = bytes(self.name, 'UTF-8') adv_data = bytearray([0x02, 0x01, 0x06]) + bytearray([len(name) + 1, 0x09]) + name self.ble.gap_advertise(100, adv_data) print(adv_data) print("\r\n") np = neopixel.NeoPixel(GBIO_IN, LED_NUM) def set_color(r, g, b): for i in range(LED_NUM): np[i] = (r, g, b) np.write() def start_power(): # 设置所有LED为白色 set_color(255, 255, 255) def add_power(): # 设置所有LED为蓝色 set_color(0, 0, 255) time.sleep(1) # 设置所有LED为青色 set_color(0, 255, 255) time.sleep(2) # 设置所有LED为黄色 set_color(255, 255, 0) time.sleep(3) # 设置所有LED为红色 set_color(255, 0, 0) time.sleep(10) def led_off(): np.fill((0, 0, 0)) # GRB填充数据(RGB顺序, 0为不亮,255为全亮) np.write() # 写入数据 if __name__ == '__main__': ble = ESP32_BLE("ESP32BLE") while True: if BLE_MSG: print("接收到的信息:>>%s<<" % BLE_MSG) if BLE_MSG == "!B10;": # 按下app上数字1 start_power() elif BLE_MSG == "!B20:": # 按下app上数字2 add_power() # elif BLE_MSG == "!B309": # 按下app上数字3 # elif BLE_MSG == "!B408": # 按下app上数字4 led_off() # elif BLE_MSG == "!B507": # 按下app上up键 # # elif BLE_MSG == "!B705": # 按下app上left键 # # elif BLE_MSG == "!B804": # 按下app上right键 # # elif BLE_MSG == "!B606": # 按下app上DOWN键 BLE_MSG = "" time.sleep(1)