MicroPython Development ESP32 Getting Started Notes--Bluetooth


foreword

The blogger has learned to use C language to develop 51 single-chip microcomputers before. Although he has not played all kinds of peripherals and sensors, the blogger has basically learned some important peripherals and sensors through principles and small project experiments. played a bit. As we all know, 51 microcontrollers are relatively low-level, and the efficiency of developing some large projects will be relatively low, so it is necessary for us to learn about the development of stm32 and esp32.

The blogger hopes to come down and learn to use MicroPython to develop esp32. Start with esp32's special functions Bluetooth and WiFi, and then get in touch with sensors and peripherals that have not been played before: DHT11 temperature and humidity sensor, ultrasonic sensor, MG60s steering gear, PIR infrared sensors etc. Throughout the process, we will allow esp32 to interact with other devices through MQTT, Bluetooth, and WiFi.

1. Introduction to ESP32 and Micropython

insert image description here

ESP32 is a series of low-cost, low-power single-chip microcontrollers with integrated Wi-Fi and dual-mode Bluetooth. The ESP32 series adopts Tensilica Xtensa LX6 microprocessor, including dual-core and single-core versions, built-in antenna switch, RF radio frequency module, power amplifier, low noise receiving amplifier, filter and power management module. ESP32 can run applications as a stand-alone system or as a slave to a host MCU, providing Wi-Fi and Bluetooth functionality through SPI/SDIO or I2C/UART interfaces.

MicroPython is a very small Python interpreter that can run on microcontrollers and other embedded systems. Its design makes it easy to run on a microprocessor, and has a rich class library, especially suitable for developing embedded applications. The core functions of MicroPython can be completed in a few seconds, allowing developers to quickly build complete embedded systems without writing a lot of code. MicroPython can also be used to control sensors and perform other operations on microcontrollers, helping developers take advantage of the full capabilities of microcontrollers. In addition, MicroPython can also be used as a development platform for Internet-connected IoT devices, as well as other complex embedded applications. The MicroPython IDEs used by bloggers here are Thonny and Upycraft.

2. Introduction to Bluetooth module communication principle

insert image description here

Bluetooth technology stipulates that when each pair of devices conducts Bluetooth communication, one must be the master end and the other is the slave end to communicate. When communicating, the master end must search and initiate pairing. Can send and receive data.

When the Bluetooth master device initiates a call, it first searches for Bluetooth devices that can be found around. After the master device finds the slave Bluetooth device, it needs to input the PIN code of the slave device when pairing with the slave Bluetooth device, and some devices do not need to input the PIN code. After the pairing is completed, the slave Bluetooth device will record the trust information of the master device. At this time, the master can initiate a call to the slave device, and the paired device does not need to be re-paired in the next call. For paired devices, the Bluetooth headset as the slave can also initiate a link establishment request, but the Bluetooth module for data communication generally does not initiate a call. After the link is successfully established, two-way data communication can be carried out between the master and slave ends. In the communication state, both the master device and the slave device can initiate a disconnection and disconnect the Bluetooth link.

The pairing information between the two Bluetooth devices is set in advance before the Bluetooth device leaves the factory. The PIN code, address, etc. of the slave device are pre-stored on the master side. When the devices at both ends are powered on, the link will be established automatically, and the transparent serial port transmission does not require peripheral circuits. intervene. In the one-to-one application, the slave device can be set to two types, one is the silent state, that is, it can only communicate with the designated master, and will not be searched by other Bluetooth modules; the other is the development state, which can be designated by the master It can also be searched by other Bluetooth devices to establish a link. There are similarities between Bluetooth communication and I2C communication. Both host and slave exist. The responses of the host and slave follow certain standards, and both have unique addresses to search for pairing.

Bluetooth technology replaces cable connections with short-range, low-cost wireless connections, thereby providing a unified connection for existing data networks and small peripheral device interfaces.

insert image description here

3. Mobile phone and ESP32 Bluetooth communication

1. ESP32 Bluetooth breathing light code

First, define a Bluetooth class. The Bluetooth class includes initialization function, connection function, connection status judgment function, address registration function, sending data function, broadcast function, and then instantiated as ble. First, call the status judgment function to receive the return from other terminals. Data, and then decode according to UTF-8, if the message is to turn on the light, turn on the breathing light, if the message is to turn off the light, turn off the breathing light

from machine import Pin, PWM
from machine import Timer
from time import sleep_ms

import bluetooth

BLE_MSG = ""


class ESP32_BLE():
    def __init__(self, name):
        self.led = PWM(Pin(2))
        self.freq = PWM(Pin(2)).freq(1000)
        self.timer1 = Timer(0)
        self.name = name
        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.config(gap_name=name)
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()

    def connected(self):
        self.led.duty(1023)
        self.timer1.deinit()

    def disconnected(self):
        self.timer1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: led.duty(500))
        

    def ble_irq(self, event, data):
        global BLE_MSG
        if event == 1: #_IRQ_CENTRAL_CONNECT 手机链接了此设备
            self.connected()
        elif event == 2: #_IRQ_CENTRAL_DISCONNECT 手机断开此设备
            self.advertiser()
            self.disconnected()
        elif event == 3: #_IRQ_GATTS_WRITE 手机发送了数据 
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip()
            
    def register(self):        
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'

        services = (
            (
                bluetooth.UUID(service_uuid), 
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY), 
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ), 
        )

        ((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")





if __name__ == "__main__":
    ble = ESP32_BLE("ESP32BLE")

    led = PWM(Pin(2))

    while True:
        if BLE_MSG == 'LED ON':
            print(BLE_MSG)
            for i in range(0,1023):
                led.duty(i)
                sleep_ms(3)
            BLE_MSG = ""
            print('LED is ON.')
            ble.send('LED is ON.')
        
        elif BLE_MSG == 'LED OFF':
            print(BLE_MSG)
            for i in range(1023,-1,-1):
                led.duty(i)
                sleep_ms(3)
            BLE_MSG = ""
            print('LED is OFF.')
            ble.send('LED is OFF.')
        sleep_ms(100)

2. Mobile terminal preparation

insert image description here
To download the LightBlue software on the mobile phone, after downloading, you need to search for the Bluetooth name of the esp32 and connect it

insert image description here

After connecting, convert the hexadecimal encoding into UTF-8 encoding format, which must be consistent with the esp32 end

insert image description here

Then write the commands compiled on the esp32 side, namely "LED ON" and "LED OFF", and then click the button to find that the light on the esp32 is turned on or off in the form of a breathing light

insert image description here

After allowing the monitoring, you can receive the data sent by esp32. In the experiment, every time you send the command to turn on or off the breathing light on the mobile phone, your mobile phone will receive the corresponding reminder from esp32.

insert image description here

Summarize

The above are the introductory notes of esp32 bluetooth today. This note briefly introduces the application of esp32 bluetooth communication, but we can apply this principle to other aspects by analogy. For example, esp32 transmits the distance of ultrasonic sensors to mobile phones through bluetooth, Control the steering gear on the esp32 through Bluetooth, interesting experiments are waiting for the friends to explore.

Guess you like

Origin blog.csdn.net/m0_55202222/article/details/129252154