ESP32服务器端编码
开发环境:Thonny python,ESP32-WROVER-DEV 服务器
Firmware:ESP32_GENERIC-SPIRAM-20220618-v1.19.1.bin。
Python的代码如下:
#work normally, with ESP32_GENERIC-SPIRAM-20220618-v1.19.1.bin ,2025.6.11
from machine import Pin
from machine import Timer
from time import sleep_ms
import bluetoothBLE_MSG = ""class ESP32_BLE():def __init__(self, name):self.led = Pin(2, Pin.OUT)self.timer1 = Timer(0)self.name = nameself.ble = bluetooth.BLE()self.ble.active(True)self.ble.config(gap_name=name)self.disconnected()self.ble.irq(self.ble_irq)self.register()self.ble.gatts_write(self.rx, bytes(100))self.ble.gatts_write(self.tx, bytes(100))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_MSGif event == 1: #_IRQ_CENTRAL_CONNECT 客户端链接了此设备self.connected()print(">>irq connected<<")elif event == 2: #_IRQ_CENTRAL_DISCONNECT 客户端断开此设备self.advertiser()self.disconnected()print(">>irq disconnected<<")elif event == 3: #_IRQ_GATTS_WRITE 客户端发送了数据#buffer存编码的数据 buffer = self.ble.gatts_read(self.rx)#BLE_MSG存解码过的数据BLE_MSG = buffer.decode('UTF-8').strip()print(BLE_MSG)print(">>irq %s<<"%BLE_MSG)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('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + nameself.ble.gap_advertise(100, adv_data)print(adv_data)print("\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__":ble = ESP32_BLE("ESP32BLE")but = Pin(0, Pin.IN)but.irq(trigger=Pin.IRQ_FALLING, handler=buttons_irq)led = Pin(2, Pin.OUT)#根据接受的数据内容判断该执行什么操作while True:if BLE_MSG == 'led_on':print(BLE_MSG)BLE_MSG = ""led.value(1)print('LED is ON.' if led.value() else 'LED is OFF')ble.send('LED is ON 12345678901234567890.' if led.value() else 'LED is OFF')elif BLE_MSG == 'led_off':print(">>%s<<"%BLE_MSG)BLE_MSG = ""led.value(0)print('LED is ON.' if led.value() else 'LED is OFF')ble.send('LED is ON.' if led.value() else 'LED is OFF')if BLE_MSG == 'up':print(BLE_MSG)BLE_MSG = ""led.value(1)print('LED is ON.' if led.value() else 'LED is OFF')sleep_ms(100)
测试功能和结果:
- 上位机:WCHBleDemo,“Write” led_on, led_off, 可以控制D2蓝色led 点亮和熄灭。
- 按下开发板上的按钮IO0,可以有LED变化和上传消息。