Esp32 wireless data transceiver debugger based on mpy

Design Intent

The original intention of this design is to prepare for the debugging and data monitoring of the electronic design competition stage.
After practical application, the effect is remarkable, and the debugging efficiency is greatly improved. This design aims to solve the problem that the serial port debugging module cannot transmit and receive wirelessly
Therefore, based on the WIFI and Bluetooth functions of esp32, an application that can adjust parameters wirelessly and view data in real time through the TCP protocol has been made.

Design ideas

This design uses both WIFI and Bluetooth functions of esp32, and the two functions do not affect each other.

bluetooth function

The Bluetooth function is mainly used to communicate with the app on the mobile phone and realize data transmission and reception. Users can realize wireless parameter adjustment and data monitoring through the Bluetooth function of this design.

WIFI function

The WIFI function is mainly used to connect to the current existing WIFI LAN, and then realize the connection to the TCP server through the socket module of python. Through the TCP server, this design can send data to the server through the TCP protocol, so as to realize remote data transmission and reception.

Bluetooth section

The Bluetooth part of this design uses Bluetooth Low Energy version 4.0. The following is a brief introduction to Bluetooth Low Energy:

Quoted from ChatGPT

Low Energy Bluetooth (BLE for short) is a Bluetooth wireless communication technology designed for low-power applications. It is an important function introduced in the Bluetooth 4.0 version, which is designed to meet the application scenarios with high requirements on battery life and device size.

Compared with traditional Bluetooth technology, Bluetooth Low Energy has made many optimizations in terms of power consumption, enabling devices to communicate with lower energy consumption, thereby extending battery life. It is usually used in scenarios that need to run for a long time and have strict requirements on power consumption, such as smart wearable devices, health monitoring devices, smart homes, and Internet of Things devices.

Bluetooth low energy uses a communication mode called “advertise-scan-connect”. The device can broadcast in a low-power mode, and the sent data contains its own identity information. Other devices can go into scan mode, receive broadcasts and detect surrounding Bluetooth Low Energy devices. Once a device finds the broadcast information it is interested in, it can initiate a connection and exchange data.

BLE uses the 2.4GHz ISM frequency band at the physical layer, sharing the same frequency range as traditional Bluetooth. It has a short communication distance (usually between 10 and 100 meters), but a relatively high data transfer rate (usually around 1 Mbps). In addition, BLE also uses a fast connection and disconnection mechanism to further reduce energy consumption.

Bluetooth low energy offers several advantages, including low power consumption, low cost, broad device compatibility, and ease of development. It provides an efficient wireless communication solution for IoT devices, advancing areas such as wearable technology, smart home and health monitoring.

The bluetooth of this design uses the bluetooth library of micropython. For the official documentation, see micropython low-power bluetooth

Its main code is as follows:

class ESP32_BLE():
    def __init__(self, name):
        self.led = Pin(2, Pin.OUT)
        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. value(1)
        self.timer1.deinit()

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

    def ble_irq(self, event, data):
        global BLE_MSG_x, BLE_MSG_y, BLE_MSG_flii, connected
        if event == 1: #_IRQ_CENTRAL_CONNECT The phone is connected to this device
            self. connected()
            connected = True
        elif event == 2: #_IRQ_CENTRAL_DISCONNECT The phone disconnects the device
            self.advertiser()
            self. disconnected()
            connected = False
        elif event == 3: #_IRQ_GATTS_WRITE mobile phone sent data
            buffer = self.ble.gatts_read(self.rx)
            print(buffer)
            Speed_left = str(int(struct. unpack('f', buffer[1:5])[0]))
            P = str(struct.unpack('f', buffer[5:9])[0])
            I = str(struct.unpack('f', buffer[9:13])[0])
            D = str(struct.unpack('f', buffer[13:17])[0])
            uart1.write(f"8,{<!-- -->P},{<!-- -->I},{<!-- -->D},{<!-- --> Speed_left},\r\\
") # write 5 bytes
            self.send(f"P:{<!-- -->P} I:{<!-- -->I} D:{<!-- -->D}")
            print(f"P:{<!-- -->P} I:{<!-- -->I} D:{<!-- -->D} \\
 Speed_left:{<!- - -->Speed_left}")
    def register(self):
        service_uuid = '6E400004-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400005-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400006-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 + '\\
')

    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x06') + bytearray((len(name) + 1, 0x09)) + name
        self.ble.gap_advertise(100, adv_data)
        print(adv_data)
        print("\r\\
")

The register() function is used to register the Bluetooth service, and the services are provided to the ble object to register the Bluetooth service (GATT Server). The three UUIDs are used as access services to manage device connections and advertisements.
reader_uuid and reader_uuid are used to handle Bluetooth receiving service and sending service respectively.
The ble_irq() function is used to handle various interrupt events of the ble Bluetooth object. This design uses connection events (_IRQ_CENTRAL_CONNECT), disconnection events (_IRQ_CENTRAL_DISCONNECT), and received data events (_IRQ_GATTS_WRITE)
The user can make corresponding processing according to various events in the Bluetooth interrupt so as to achieve the purpose expected by the user.

WIFI section

The WIFI part of this design uses the 2.4G WIFI protocol. The following is a brief introduction of 2.4G WIFI:

Quoted from ChatGPT

2.4GHz Wi-Fi is a wireless local area network technology that works in the 2.4GHz frequency band. It is a common and widely used wireless networking technology in home and office environments.

2.4GHz Wi-Fi is based on the IEEE 802.11 family of standards, the most common of which is 802.11b/g/n. It uses radio waves in the 2.4GHz frequency band for data transmission and can provide reliable wireless network connections.

Wi-Fi in the 2.4GHz band has some features and advantages:

Wide coverage: The signal in the 2.4GHz band can penetrate obstacles (such as walls) relatively well during propagation, so it has a wide coverage.
Compatibility: 2.4GHz Wi-Fi has existed for many years, has been widely supported and adopted, and many devices are able to connect and use 2.4GHz networks.
Strong signal penetration: The relatively low frequency of 2.4GHz signals can penetrate objects better. Therefore, in some environments with poor signal coverage, such as rooms with thick walls, 2.4GHz Wi-Fi signals perform better. good.
However, 2.4GHz Wi-Fi also has some limitations:

Channel interference: The 2.4GHz frequency band is used by many other devices, such as Bluetooth devices, microwave ovens, etc., which may cause channel interference and affect the performance and stability of Wi-Fi.
Limited bandwidth: The bandwidth of the 2.4GHz band is relatively narrow, usually only 20MHz or 40MHz. In contrast, Wi-Fi in the 5GHz band provides wider bandwidth and is more suitable for high-speed data transmission.
Limitation on the number of connections: Due to the bandwidth and channel limitations of the 2.4GHz frequency band, when a large number of devices are connected at the same time, it may cause network congestion and performance degradation.
In conclusion, 2.4GHz Wi-Fi is a common wireless LAN technology with wide application and compatibility. It performs well in terms of coverage and signal penetration, but suffers from band congestion and bandwidth limitations. With the development of wireless technology, Wi-Fi in the 5GHz frequency band has gradually been widely used, providing higher speed and less interference, becoming a better choice.

Its main code is as follows:

ssid = "OrayBox-BA2C"
key = "1234567890"

def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan. active(True)
    while True:
        if not wlan.isconnected():
            print('connecting to network...')
            try:
                wlan. connect(ssid, key)
            except:
                time. sleep(5)
            while not wlan.isconnected():
                pass
        else:
            break
    print('network config:', wlan.ifconfig())

The above code realizes the esp32 blocking connection to WIFI. When there is no WIFI connection, the system will reconnect every 5 seconds until the connection is successful. After the connection is successful, the ip of the device will be printed out.

TCP section

The TCP protocol in wireless communication used in this design, the following is a brief introduction of the TCP protocol:

Quoted from ChatGPT
TCP (Transmission Control Protocol, Transmission Control Protocol) is a transport layer protocol commonly used in computer networks. It provides reliable, connection-oriented data transmission for ensuring reliable delivery of data over the network.

Following are some key features and functions of the TCP protocol:

  1. Reliability: TCP uses a reliable data transmission mechanism to ensure the integrity and correctness of data by using technologies such as sequence numbers, confirmations, and retransmissions. It detects and corrects missing, duplicate, and out-of-sequence data, ensuring data arrives at its destination in the correct order.

  2. Connection-oriented: In TCP communication, the sender and receiver need to establish a connection before communicating. The establishment of a connection includes a three-way handshake process to ensure that both the sender and receiver are ready to communicate. After the communication is over, the connection needs to be released to ensure the release and management of network resources.

  3. Flow Control and Congestion Control: TCP handles network congestion and resource management through flow control and congestion control mechanisms. Flow control is used to control the rate at which the sender sends data to ensure that the receiver can process and receive the data. Congestion control is used to detect network congestion and adjust the sending rate to avoid network overload and collapse.

  4. Multiplexing: TCP supports multiplexing, that is, transmitting data from multiple applications simultaneously on a single TCP connection. It uses port numbers to distinguish between different applications or services, ensuring that data is properly transferred to the appropriate application.

  5. Efficiency: While TCP provides many features in terms of reliability and connection management, it also strives to provide efficient data transfer. By using mechanisms such as sliding window and congestion control, TCP can optimize the transmission speed of data and the utilization of network resources.

TCP is one of the most commonly used transmission protocols in the Internet, and it is widely used in many application scenarios, such as web browsing, email, file transfer, etc. It provides reliable data transmission and connection management, providing an important foundation for network communication.

Its main code is as follows:

def TCP_Connect():
    # 1. Create socket
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
    # 2. Bind local information bind
    #tcp_server_socket.bind(("Fill in your TCP server IP address here", fill in the TCP server port here))
    tcp_server_socket.connect(("Fill in your TCP server IP address here", fill in the TCP server port here))
    # 3. Make the default socket active to passive listen, so that you can receive other people's data
    print("----Connect to the server successfully----")
    
    while True:
        recv_data = uart1. readline()
        #print(recv_data)
        # Receive a row of data
        if recv_data:
            recv_data = recv_data.decode('utf-8')
            tcp_server_socket.send(recv_data)
            print("The received data is:", recv_data)
    tcp_server_socket. close()

The above code realizes the simulation of esp to the tcp client and the connection to the TCP server. When the connection to the TCP server is successful, the system will print “connect to the server successfully” and enter a loop.
After entering the loop, the system starts to receive the uart serial port cyclically. When the serial port has data incoming, the system will send the data incoming from the serial port to the TCP server, so as to realize the remote display of the data.

.
.
.
.
.
.

words written on the back

This code still has many bugs. First of all, when TCP sends data, it is not sure whether the delay of the TCP server is too high or the esp32 network problem. When sending data with the TCP protocol, the amount of data is large, and the delay of the data will be relatively large. Gao, if you encounter other problems, you can leave a message at the bottom or contact me on the sidebar, and I will reply as soon as possible~