在Ubuntu虚拟机中用Python3+pyserial读取Arduino数据,如何去除b'...\r\n'保留纯文本
Clean Serial Data from Arduino in Python 3 with pyserial
Hey there! Let's fix that serial data formatting issue you're dealing with. When reading from Arduino via pyserial, you're getting byte strings like b' What\'s 9+10? \r\n'—here's how to turn that into clean, plain text like "What's 9+10?".
Step-by-Step Solution
The process has two key parts: converting the byte object to a string, and stripping unwanted whitespace/control characters.
1. Python Code Implementation
Here's how to modify your ardui.py to handle the data correctly:
import serial # Initialize serial connection (adjust port to match your system) ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) try: while True: # Check if there's data waiting to be read if ser.in_waiting > 0: # Read a line of data from Arduino raw_data = ser.readline() # Convert bytes to string, then strip all leading/trailing whitespace (including \r\n) clean_text = raw_data.decode('utf-8').strip() # Print or use the cleaned text print(clean_text) finally: # Make sure to close the serial port when done ser.close()
Breakdown of the Key Lines:
raw_data.decode('utf-8'): Converts the byte string (the one withb''around it) into a standard Python string. Most Arduino serial output uses UTF-8 encoding, but if you run into issues, you can try'ascii'instead..strip(): Removes all leading and trailing whitespace characters, including\r,\n, spaces, and tabs. This gets rid of the trailing newline from Arduino'sSerial.println()and any accidental leading spaces.
Your Arduino Code (Completed for Context)
Since you shared a partial snippet, here's a full, working version that would send the example message when the button is pressed:
int PB = 2; // Button connected to pin 2 void setup(){ Serial.begin(9600); pinMode(PB, INPUT_PULLUP); // Using internal pull-up resistor to avoid external components } void loop(){ int buttonState = digitalRead(PB); // Send message when button is pressed (LOW because of pull-up) if(buttonState == LOW){ Serial.println("What's 9+10?"); delay(500); // Debounce delay to prevent multiple triggers } }
Quick Notes
- Serial Port: On Ubuntu, your Arduino might show up as
/dev/ttyACM0or/dev/ttyUSB0. You can list available ports with the commandls /dev/tty*in the terminal. - Permissions: If you get a "permission denied" error, add your user to the
dialoutgroup withsudo usermod -aG dialout $USER, then log out and back in.
内容的提问来源于stack exchange,提问作者papisilv
相关产品推荐
相关产品推荐

