Quantcast
Viewing all articles
Browse latest Browse all 4829

MicroPython • Bluetooth code issues.

Hi All.
I want my Pico-W # 1( The Peripheral ) to send a message to Pico-W # 2 ( The Central ). The message is " Hello, nice to see you!'. I want this message printed on the Thonny Shell of Pico-W # 2 ( The Central ).

So I put together 2 codes from a million example sources.

When I run the Pico-W # 1( The Peripheral ) code, I get the following and nothing happens .
MPY: soft reboot
Starting advertising


When I run the Pico-W # 2 ( The Central ) code, I get the following and nothing happens .
MPY: soft reboot
Scanning for peripherals...
Scanning for peripherals...
Scanning for peripherals...


1) Can someone pelase tell me how to proceed on this issue so that things can move forward. This is worse than the code having syntax errors etc and thereby not working lol.
2) Also, one of the examples I used wanted me to include a certain ble_advertising.py in the same folder as main.py. I did that and Thonny still complained that it couldnt find ble_advertising.py and it cant import it. Why would Thonny say that? Why would it complain that it was unable to 'find, or unable to import, ' ble_advertising.py when it was right in front of my face, in the same directory, with the same exact spelling?! ( I was so mad at Thonny for not importing a .py file that was in front of my face, that I removed that entire file and directly included that code in the main code. )

Ty for the reply.

Below is the Pico-W # 2 ( The Central ) code

Code:

import bluetoothimport structimport timefrom machine import Pinfrom micropython import const_ADV_TYPE_FLAGS = const(0x01)_ADV_TYPE_NAME = const(0x09)_ADV_TYPE_UUID16_COMPLETE = const(0x3)_ADV_TYPE_UUID32_COMPLETE = const(0x5)_ADV_TYPE_UUID128_COMPLETE = const(0x7)_ADV_TYPE_APPEARANCE = const(0x19)# Define UUIDs and services_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")_UART_TX = (    bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),    bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)_UART_RX = (    bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),    bluetooth.FLAG_WRITE | bluetooth.FLAG_WRITE_NO_RESPONSE,)_UART_SERVICE = (    _UART_UUID,    (_UART_TX, _UART_RX),)# Advertisement payload functiondef advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):    payload = bytearray()    def _append(adv_type, value):        nonlocal payload        payload += struct.pack("BB", len(value) + 1, adv_type) + value    _append(        _ADV_TYPE_FLAGS,        struct.pack("B", (0x01 if limited_disc else 0x02) + (0x18 if br_edr else 0x04)),    )    if name:        _append(_ADV_TYPE_NAME, name)    if services:        for uuid in services:            b = bytes(uuid)            if len(b) == 2:                _append(_ADV_TYPE_UUID16_COMPLETE, b)            elif len(b) == 4:                _append(_ADV_TYPE_UUID32_COMPLETE, b)            elif len(b) == 16:                _append(_ADV_TYPE_UUID128_COMPLETE, b)    if appearance:        _append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance))    return payload# Peripheral class for BLE communicationclass BLESimplePeripheral:    def __init__(self, ble, name="mpy-uart"):        self._ble = ble        self._ble.active(True)        self._ble.irq(self._irq)        ((self._handle_tx, self._handle_rx),) = self._ble.gatts_register_services((_UART_SERVICE,))        self._connections = set()        self._write_callback = None        self._payload = advertising_payload(name=name, services=[_UART_UUID])        self._advertise()    def _irq(self, event, data):        if event == bluetooth.EVT_GATTS_WRITE:            conn_handle, value_handle = data            value = self._ble.gatts_read(value_handle)            if value_handle == self._handle_rx and self._write_callback:                self._write_callback(value)        elif event == bluetooth.EVT_GAP_CONNECTED:            conn_handle, _, _ = data            self._connections.add(conn_handle)            print("Connected. Hello, nice to see you!")        elif event == bluetooth.EVT_GAP_DISCONNECTED:            conn_handle, _, _ = data            self._connections.remove(conn_handle)            self._advertise()    def send(self, data):        for conn_handle in self._connections:            self._ble.gatts_notify(conn_handle, self._handle_tx, data)    def is_connected(self):        return len(self._connections) > 0    def _advertise(self, interval_us=500000):        print("Starting advertising")        self._ble.gap_advertise(interval_us, adv_data=self._payload)    def on_write(self, callback):        self._write_callback = callbackdef demo():    ble = bluetooth.BLE()    p = BLESimplePeripheral(ble)    def on_rx(v):        print("RX", v)    p.on_write(on_rx)    while True:        time.sleep(1)if __name__ == "__main__":    demo()
Below is the Pico-W # 1( The Peripheral ) code:

Code:

import bluetoothimport structimport timefrom machine import Pinfrom micropython import const_ADV_TYPE_FLAGS = const(0x01)_ADV_TYPE_NAME = const(0x09)_ADV_TYPE_UUID16_COMPLETE = const(0x3)_ADV_TYPE_UUID32_COMPLETE = const(0x5)_ADV_TYPE_UUID128_COMPLETE = const(0x7)_ADV_TYPE_APPEARANCE = const(0x19)# Define UUIDs and services_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")_UART_TX = (    bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),    bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)_UART_RX = (    bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),    bluetooth.FLAG_WRITE | bluetooth.FLAG_WRITE_NO_RESPONSE,)_UART_SERVICE = (    _UART_UUID,    (_UART_TX, _UART_RX),)# Advertisement payload functiondef advertising_payload(limited_disc=False, br_edr=False, name=None, services=None, appearance=0):    payload = bytearray()    def _append(adv_type, value):        nonlocal payload        payload += struct.pack("BB", len(value) + 1, adv_type) + value    _append(        _ADV_TYPE_FLAGS,        struct.pack("B", (0x01 if limited_disc else 0x02) + (0x18 if br_edr else 0x04)),    )    if name:        _append(_ADV_TYPE_NAME, name)    if services:        for uuid in services:            b = bytes(uuid)            if len(b) == 2:                _append(_ADV_TYPE_UUID16_COMPLETE, b)            elif len(b) == 4:                _append(_ADV_TYPE_UUID32_COMPLETE, b)            elif len(b) == 16:                _append(_ADV_TYPE_UUID128_COMPLETE, b)    if appearance:        _append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance))    return payload# Peripheral class for BLE communicationclass BLESimplePeripheral:    def __init__(self, ble, name="mpy-uart"):        self._ble = ble        self._ble.active(True)        self._ble.irq(self._irq)        ((self._handle_tx, self._handle_rx),) = self._ble.gatts_register_services((_UART_SERVICE,))        self._connections = set()        self._write_callback = None        self._payload = advertising_payload(name=name, services=[_UART_UUID])        self._advertise()    def _irq(self, event, data):        if event == bluetooth.EVT_GATTS_WRITE:            conn_handle, value_handle = data            value = self._ble.gatts_read(value_handle)            if value_handle == self._handle_rx and self._write_callback:                self._write_callback(value)        elif event == bluetooth.EVT_GAP_CONNECTED:            conn_handle, _, _ = data            self._connections.add(conn_handle)            print("Connected. Hello, nice to see you!")        elif event == bluetooth.EVT_GAP_DISCONNECTED:            conn_handle, _, _ = data            self._connections.remove(conn_handle)            self._advertise()    def send(self, data):        for conn_handle in self._connections:            self._ble.gatts_notify(conn_handle, self._handle_tx, data)    def is_connected(self):        return len(self._connections) > 0    def _advertise(self, interval_us=500000):        print("Starting advertising")        self._ble.gap_advertise(interval_us, adv_data=self._payload)    def on_write(self, callback):        self._write_callback = callbackdef demo():    ble = bluetooth.BLE()    p = BLESimplePeripheral(ble)    def on_rx(v):        print("RX", v)    p.on_write(on_rx)    while True:        time.sleep(1)if __name__ == "__main__":    demo()

Statistics: Posted by Blue Mountain — Thu Jun 27, 2024 4:11 am



Viewing all articles
Browse latest Browse all 4829

Trending Articles