Python-a protocol suitable for communication between upper and lower computers based on python or Micropython

Because the single-chip microcomputer that bloggers like to use is developed based on micropython, they all use python programming, which can be compatible with the data format between pythons. At the same time, on the basis of serial communication between PYB and Raspberry Pi, we need to standardize the format of the communication data. Tuples, as the multi-data storage format with the smallest memory footprint in Python, can be said to be a better choice than lists, dictionaries, etc., so this blog is based on tuples as the main data format for communication.

Local conversion format to simulate communication process

Here we need to pack the data in PYB into a tuple, and then convert it into a string format with a newline character, and then perform encoding conversion, and send it to the receiving end of the host computer through UART serial communication.
In the host computer, it is necessary to decode the entire line of data received first, and then

# 源数据
tp = (1, (2,3), 5)
# 测试eval()函数,python内置的eval函数可以将列表、元组格式的字符串转换回原格式。
n = eval(str(tp))
print(n, type(n))
# 编码
n1 = str(n) +"/n"
a = n1.encode("utf-8")

# 上位机端接收到编码后的数据,进行解码操作
a.decode("utf-8")
print(a, type(a))
# 转换回元组格式
a = str(a)[2:-3]
print(a, type(a))
b = eval(a)
print(b, type(b))

# 判断最终的格式是否为元组,且和原来相同
if type(b) == tuple:
    print("is tuple")

Run result display

Insert picture description here

It shows that there is no problem with our code operation. Okay, let's proceed to the actual machine communication process.

Communication between PYB and Raspberry Pi realizes mutual transmission of tuple data

If you haven't realized the communication between PYB and Raspberry Pi, please read the blog first: Micropython-UART serial communication based on GPIO of Raspberry Pi . After running this demo, we will enter the step of mutual transmission of tuple data.

Just upload the code, you can just look at the final rendering, just copy the code to run.

Host computer (Raspberry Pi)

# -*- coding:utf-8 -*-
import serial
import time
ser = serial.Serial("/dev/ttyAMA0", 115200)
ser.flushInput()  
ser.write("begin".encode("utf-8")) 

tp = (12,34, (56,78), 910)

def main():
    while True:
        count = ser.inWaiting() 
        if count != 0:
            recv = ser.read(count) 
            #ser.write("I'm raspberry pi!".encode("utf-8")) 
            ser.write(str(tp).encode("utf-8"))   
            ser.write("\n".encode("utf-8"))  
            try:
                print(ser.readline())
            except:
                pass
            ser.flushInput()

 
if __name__ == '__main__':
    main()

Lower computer (PYB is used here)

import utime
import serial
from pyb import UART


class Serial:
    def __init__(self, uart):
        self.uart = uart

    def data_check(self):
        '''
        函数功能:返回串口接收状态
        '''
        return self.rev_data()

    def send_data(self, data="hi i'm pyboard!\n"):
        '''
        函数功能:串口发送数据
        入口参数:需要发送的打包好的数据(字符串格式)
        '''
        if type(data) != str:
            data = str(data)
        data.encode("utf-8")
        self.uart.write(data)

    def rev_data(self):
        '''
        函数功能:读取上位机发送的运动控制指令
        入口参数:
        返回值  :接收到的数据
        '''
        start = utime.ticks_ms()
        data = self.uart.readline()
        if data != None:
            # print("get data!!!!!")
            try:
                data = self.analysis_data(data)
            except:
                pass
            end = utime.ticks_ms()
            print("running time:", end - start)
            print(data)    
            return True
        else:
            return False
    
    def format_data(self, motion=0, angle=0, encoders=(0,0), imu=(0,0,0)):
        '''
        函数功能:将需要发送的所有数据封装起来
        入口参数:
        返回值  :封装后的数据元组
        '''
        data = (motion, angle, encoders, imu)
        return str(data + "\n")
    
    def analysis_data(self, data):
        data.decode("utf-8")
        data = str(data)[2:-3] # 将 “\n” 和 b'' 去除
        data = eval(data) # 转化回元组形式
        print(type(data))
        return data
        
uart = UART(2, 115200)
ser = serial.Serial(uart)
while True:
	ser.rev_data()

PYB receiving

Insert picture description here

Reference article:

Guess you like

Origin blog.csdn.net/qq_45779334/article/details/112797226