06 Get Chassis Feedback

From Waveshare Wiki
Jump to: navigation, search

Getting Chassis Feedback Information

After the product is powered on, the lower computer continuously sends various feedback information to the upper computer by default. You can use this feedback to obtain the current working status of the product.

Typically, you need to continuously receive the feedback information from the lower computer. However, in this example, we only capture one JSON feedback message from the lower computer (you can comment out or delete the break line to continuously receive feedback).

Select the code block below and run it with Ctrl+Enter. When it receives the first complete JSON message with T value 1001, it will break out of the loop and output the feedback information, which includes current wheel speeds, IMU data, pan‑tilt angle (if installed), robotic arm angle (if installed), power supply voltage, etc.

from base_ctrl import BaseController
import json

# Function to detect the Raspberry Pi model
def is_raspberry_pi5():
    with open('/proc/cpuinfo', 'r') as file:
        for line in file:
            if 'Model' in line:
                if 'Raspberry Pi 5' in line:
                    return True
                else:
                    return False

# Determine the GPIO serial device name based on the Raspberry Pi model
if is_raspberry_pi5():
    base = BaseController('/dev/ttyAMA0', 115200)
else:
    base = BaseController('/dev/serial0', 115200)

# Use an infinite loop to continuously listen for serial data
while True:
    try:
        # Read one line from the serial port, decode it as a 'utf-8' string, and try to convert it to a JSON object
        data_recv_buffer = json.loads(base.rl.readline().decode('utf-8'))
        # Check if the parsed data contains the 'T' key
        if 'T' in data_recv_buffer:
            # If the value of 'T' is 1001, print the received data and break the loop
            if data_recv_buffer['T'] == 1001:
                print(data_recv_buffer)
                break
    # If an exception occurs while reading or processing the data, ignore it and continue listening for the next line
    except:
        pass

Non‑blocking method to obtain JSON messages from the serial port

The following code is only for understanding the underlying principle of reading JSON messages from the serial port. Do not execute this code block.

class ReadLine:
    # Constructor, initializes an instance of the ReadLine class
    # s: The serial port object passed in, used for serial communication.
    def __init__(self, s):
        self.buf = bytearray()  # Initialize a bytearray to store data read from the serial port that has not yet been processed
        self.s = s  # Save the passed serial port object for subsequent reading of serial data

    def readline(self):
        i = self.buf.find(b"\n") # Check if there is a newline character in the buffer
        if i >= 0:
            r = self.buf[:i+1] # If a newline character exists, extract the data before it
            self.buf = self.buf[i+1:] # Update the buffer, removing the processed data
            return r
        while True:
            i = max(1, min(512, self.s.in_waiting)) # Get the number of readable bytes, up to 512 bytes
            data = self.s.read(i) # Read data from the serial port
            i = data.find(b"\n") # Look for a newline character
            if i >= 0:
                r = self.buf + data[:i+1] # If a newline character is found, combine the already read data with the buffer data
                self.buf[0:] = data[i+1:] # Update the buffer, removing the processed data
                return r
            else:
                self.buf.extend(data) # If no newline character is found, add the data to the buffer
  • This method reads data from the serial port and returns a complete line of JSON data (delimited by the newline character \n).
  • If a complete line of data already exists in the buffer, it is returned directly.
  • If there is no complete line in the buffer, it uses the in_waiting method to get the number of readable bytes in the serial buffer, reading up to 512 bytes.
  • It reads data from the serial port and merges it with the existing buffer.
  • It looks for a newline character in the newly read data; if found, it extracts a complete line and updates the buffer.
  • If no newline character is found, it appends the newly read data to the buffer and continues reading until a newline is found.

Function Characteristics

  • Non‑blocking: This function uses a non‑blocking read method. Even if no data is available on the serial port, it does not block program execution; it waits until data is available.
  • Efficient: It uses a small buffer, reading up to 512 bytes at a time, reducing memory consumption and processing data promptly to avoid buffer overflow.
  • Flexible: It can flexibly read data of arbitrary length and automatically handles newline‑separated data, making it very suitable for reading structured data such as JSON.
  • Reliable: It accounts for various situations during processing, such as insufficient buffer data or read data without a newline character, ensuring accuracy and stability.
  • This function is ideal for real‑time reading of JSON data from a serial port, especially when non‑blocking reading is required.