0

我一直在试验 Adafruit ItsyBitsy (nRF52840) 和 CircuitPython。我可以将开发板设置为 BLE 外围设备,没问题……但事实证明,将其设置为中央设备更加困难。

这是我在 Board1(我的 Central)上使用的代码:

import time

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()

# uart = UARTService()

uart_connection = None

while True:
    if not uart_connection:
        print("Trying to connect...")
        for adv in ble.start_scan(ProvideServicesAdvertisement):
            if UARTService in adv.services:
                uart_connection = ble.connect(adv)
                print("Connected")
                break
        ble.stop_scan()

    if uart_connection and uart_connection.connected:
        uart_service = uart_connection[UARTService]
        while uart_connection.connected:
            time.sleep(5)
            uart_service.write("hello world").encode("utf-8")

我在这里从这个示例代码修改:https ://learn.adafruit.com/circuitpython-ble-libraries-on-any-computer/ble-uart-example

这是我在 Board2 上的代码——当我在手机上使用我的 UART 应用程序测试它时,它绝对有效:

import time
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

while True:
    ble.start_advertising(advertisement)
    print("Waiting to connect")
    while not ble.connected:
        pass
    print("Connected")
    while ble.connected:
        s = uart.readline()
        if s:
            print(s)
            try:
                result = str(eval(s))
            except Exception as e:
                result = repr(e)
            uart.write(result.encode("utf-8"))

中央板肯定会发现并连接到外围设备。我无法判断的是 UART 通道是否建立正确。据我所知,Central 没有通过 UART 连接发送任何内容(或者可能正在发送某些内容,但 Peripheral 没有收到任何内容)。

有任何想法吗?

4

0 回答 0