example BLE micropython

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
julien
Posts: 11
Joined: Fri Mar 27, 2020 10:16 pm

example BLE micropython

Post by julien » Sat Jul 04, 2020 3:14 pm

Hello,

I am looking for sample program to send and received data over BLE in MicroPython for ESP32.
Thanks to help.
Regards.

julien

redyellow
Posts: 12
Joined: Tue Jun 30, 2020 10:19 am

Re: example BLE micropython

Post by redyellow » Sat Jul 04, 2020 5:07 pm


User avatar
HexVitor
Posts: 6
Joined: Sat Dec 28, 2019 2:11 am
Location: Brazil

Re: example BLE micropython

Post by HexVitor » Sun Jul 05, 2020 2:26 pm

Hi, I am developing a code and it is like that at the moment. To use it, just have a serial communication application via BLE on the smartphone (I use the Serial Bluetooth Terminal).

Serial Bluetooth Terminal: https://play.google.com/store/apps/deta ... l&hl=pt_BR

Settings (App):
1. Terminal: Font size(14), Font style(Normal), Charset(UTF-8), Display mode(Text), Auto scroll(on),
Show connection messages(on), Show timestamps(on), Timestamp(I left default), Buffer size(10 kB).
2. Receive: Newline(LF).
3. Send: Newline(LF), Edit mode(Text), Line delay(0 ms), Character delay(0 ms), Local echo(on), Clear input(on).
4. Misc(I left default).

MCU: ESP-WROOM-32 (ESP32D0WDQ6)
Firmware: MicroPython v1.12 (for ESP32 with IDF4, 2019.12.20) https://micropython.org/resources/firmw ... -v1.12.bin
IDE: Thonny Python IDE
SO: Windows 10 Home Single Language 2004

Use ble.send ("<message>") to send messages to the smartphone.
Messages sent to ESP32 are displayed on the terminal.
Blinking blue LED indicates that BLE communication is available.

Code: Select all

from machine import Pin, Timer
from time import sleep_ms
import ubluetooth
from esp32 import raw_temperature

class BLE():


    def __init__(self, name):
        
        self.name = name
        self.ble = ubluetooth.BLE()
        self.ble.active(True)

        self.led = Pin(2, Pin.OUT)
        self.timer1 = Timer(0)
        self.timer2 = Timer(1)
        
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()


    def connected(self):
        
        self.timer1.deinit()
        self.timer2.deinit()


    def disconnected(self):
        
        self.timer1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led(1))
        sleep_ms(200)
        self.timer2.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led(0))
    

    def ble_irq(self, event, data):

        if event == 1:
            '''Central disconnected'''
            self.connected()
            self.led(1)
        
        elif event == 2:
            '''Central disconnected'''
            self.advertiser()
            self.disconnected()
        
        elif event == 4:
            '''New message received'''
            
            buffer = self.ble.gatts_read(self.rx)
            message = buffer.decode('UTF-8')[:-1]
            print(message)
            
            if received == 'blue_led':
                blue_led.value(not blue_led.value())

            
    def register(self):
        
        # Nordic UART Service (NUS)
        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')
        self.ble.gap_advertise(100, bytearray('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name)
        
# test
blue_led = Pin(2, Pin.OUT)
ble = BLE("ESP32")

BikerMark
Posts: 3
Joined: Fri Dec 18, 2020 6:59 pm

Re: example BLE micropython

Post by BikerMark » Thu Jan 21, 2021 4:57 pm

@HexVitor thnx for sharing, your code worked well for me!

One typo I found in the IRQ and share here for anyone to come by:

Code: Select all

        elif event == 4:
should be:

Code: Select all

        elif event == 3:
And I cannot figure out why

Code: Select all

if received == 'blue_led':
is not recognizing the litteral string. If I add an else-statement, the latter is triggered.
Did you (or anybody else) find out about that?

Thnx again!

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: example BLE micropython

Post by pythoncoder » Fri Jan 22, 2021 11:12 am

The variable received is not set anywhere. The code

Code: Select all

if received == 'blue_led':
should throw an exception. Should it read

Code: Select all

if message == 'blue_led':
?
Peter Hinch
Index to my micropython libraries.

Blip!
Posts: 3
Joined: Sun Jan 24, 2021 5:52 pm

Re: example BLE micropython

Post by Blip! » Sun Jan 24, 2021 6:11 pm

Good and simple sample, @HexVitor. Easy to follow!
There are 3 bugs, however.

The last string compare put me off a little, until I realized the [:-1] stripping did not remove '\r' (aka carriage return). .strip() is a better way of removing blanks...

Code: Select all

elif event == 4:
...
if received == 'blue_led':
...
message = buffer.decode('UTF-8')[:-1]
... should be ...

Code: Select all

elif event == 3:
...
if message == 'blue_led':
...
message = buffer.decode('UTF-8').strip()
In addition, `led.value()` should be used in place of `blue_led.value()`

2black0
Posts: 1
Joined: Sun May 31, 2020 1:24 pm

Re: example BLE micropython

Post by 2black0 » Fri Mar 12, 2021 1:49 am

thanks for the code, I do some modification here: https://github.com/2black0/MicroPython-ESP32-BLE

stepfl
Posts: 1
Joined: Sat Jan 22, 2022 5:11 pm

Re: example BLE micropython . what about passkey?

Post by stepfl » Sat Jan 22, 2022 5:16 pm

Is there any possibility to include a passkey to the BLE? I didn't find any hint to this point...
Sorry about my english - I'mnot used to write in this language..

best greetings, stepfl

outkasst1
Posts: 2
Joined: Sun Jul 03, 2022 11:56 pm

Re: example BLE micropython

Post by outkasst1 » Thu Jul 07, 2022 2:11 am

Hi,

I need the same BLE Micropython code to send and receive data, but on a RP2040 Connect board with Mycropython installed..
Can anyone with the knowledge please help?

thx

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: example BLE micropython

Post by jimmo » Thu Jul 07, 2022 2:30 am

outkasst1 wrote:
Thu Jul 07, 2022 2:11 am
I need the same BLE Micropython code to send and receive data, but on a RP2040 Connect board with Mycropython installed..
Take a look at aioble. There are some examples there in the readme as well as in the examples directory. Feel free to ask more questions.

https://github.com/micropython/micropyt ... oth/aioble

Post Reply