蓝牙部分
这个帖子非常简化,能用就行的话就这个用用。
三十岁学编程的蓝牙包装库
esp32的一套视频课程非常不错
下面是一个简单蓝牙主机的验证实例程序,比较好理解,但是由于没有使用中断驻留所以在循环里执行,适合学习。
import ubluetooth
import machine,time
class ESP32_BLE():
def __init__(self,name):
self.led=machine.Pin(2,machine.Pin.OUT,value=0)
self.name=name
self.ble = ubluetooth.BLE()
self.ble.active(True)
self.disconnected()
self.ble.irq(self.ble_irq)
self.register()
self.advertiser()
self.bleMsg=''
def connected(self):
self.led.on()
def disconnected(self):
self.led.off()
def ble_irq(self,event,data):
if event == 1 :
self.connected()
elif event == 2 :
self.disconnected()
elif event == 3 :
buffer=self.ble.gatts_read(self.rx)
self.bleMsg=buffer.decode('UTF-8')
print(self.bleMsg,buffer)
def register(self):
NUS_UUID= '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
RX_UUID = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
TX_UUID = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
BLE_NUS = ubluetooth.UUID(NUS_UUID)
BLE_RX = (ubluetooth.UUID(RX_UUID),ubluetooth.FLAG_WRITE)
BLE_TX = (ubluetooth.UUID(TX_UUID),ubluetooth.FLAG_NOTIFY)
BLE_UART = (BLE_NUS,(BLE_TX,BLE_RX,))
SERVICES = (BLE_UART,)
((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))+name
self.ble.gap_advertise(100,adv_data)
print(adv_data)
print('\r\n')
ble = ESP32_BLE('esp32ble')
print('connected')
while 1 :
if len(ble.bleMsg)>0:
print(ble.bleMsg)
ble.send('sladf\r\n')
print('send')
ble.bleMsg=''
if ble.led.value()== 0:
time.sleep(3)
if ble.led.value()== 0:
ble = ESP32_BLE('esp32ble')