dfrobot_wx 发表于 2017-7-23 17:52:21

esp32 micropython ble_center初体验

本帖最后由 dfrobot_wx 于 2017-7-23 17:52 编辑

本例程所需原料
硬件
1.FireBeetle-ESP32主板
2.Bluno主板
软件
1. uPyCraft
esp32端代码如下:
import gc
import sys
import network as n
import gc
import time

b = n.Bluetooth()

found = {}
complete = True
connectname = ""
mac=b'\x00\x00\x00\x00\x00\x00'
def bcb(b,e,d,u):
global complete
global found
global connectname
global mac
if e == b.CONNECT:
      print("CONNECT")
elif e == b.DISCONNECT:
      print("DISCONNECT")
elif e == b.SCAN_RES:
    if complete:
      found = {}
      adx, name,ssic= d
      if connectname == str(name):
      mac = adx
      print(d)
      if adx not in found:
          found = name
      else:
      print('else')
      print(d)

elif e == b.SCAN_CMPL:
    ok = True
    print("Scan Complete")
    complete = True
    print ('\nFinal List:')
    for adx, name in found.items():
      print ('Found:' + ':'.join(['%02X' % i for i in adx]), name)
      print('connect ',name)
else:
    print ('Unknown event', e,d)

def cb (cb, event, value, userdata):
print('charcb ', cb, userdata, ' ', end='')
if event == b.READ:
    print('Read')
    return 'ABCDEFG'
elif event == b.WRITE:
    print ('Write', value)
elif event == b.NOTIFY:
    print ('Notify', value)
def conn(bda):
b.ble_settings(adv_is_scan_rsp = False)
conn = b.connect(bda)
i=0
while not conn.is_connected():
    i=i+1
    time.sleep(.1)
    print ('Connected')
    time.sleep(2) # Wait for services
    service = ( == b'\x00\x00\xDF\xB0'] + )
    if service:
      print(service.chars())
      char = ( == b'\x00\x00\xDF\xB1'] + )
      char.callback(cb)
      if char:
      char.callback(cb)
    if i == 10:
      print('time out')
      break
return conn
def onScanComplete():
time.sleep(2)
def set_connetname(name):
return "b'%s'" % name
def scan():
global connectname
connectname = set_connetname("Bluno")
b.ble_settings(adv_is_scan_rsp = True)
b.scan_start(5)
time.sleep(10)
b.callback(bcb)
scan()
print('mac:',mac)
conn(mac)

1. 使用uPyCraft下载到板子上并运行
2. BLE开始扫描并连接设备


3. 成功连接上设备



4. 打开串口调试工具,向BLUNO串口发送数据



5、Esp32收到的数据



这个例程在连接过程中有时会出现不稳定现象,望各位大神指正。
该例程中使用的从机模块是bluno,各位师兄可以使用其他的ble模块,只需要在esp32程序中的更改相应的设备名以及需要监听的uuid即可。


秦皇岛岛主 发表于 2017-7-25 08:37:28

[赞],点击[ http://pinyin.cn/e19975 ]查看表情

zyber 发表于 2018-7-28 20:07:23

你好 ,我用时用的程序连一个蓝牙手柄 显示连接不上,
0;31mE (996959) BT: btm_sec_clr_temp_auth_service() - no dev CB

E (996959) BT: bta_gattc_conn_cback() - cif=4 connected=0 conn_id=4 reason=0x0008
E (996959) BT: Device not found

E (996959) BT: bta_gattc_mark_bg_conn unable to find the bg connection mask for: ff:ff:97:01:cd:64
页: [1]
查看完整版本: esp32 micropython ble_center初体验