You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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 with b'' 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's Serial.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/ttyACM0 or /dev/ttyUSB0. You can list available ports with the command ls /dev/tty* in the terminal.
  • Permissions: If you get a "permission denied" error, add your user to the dialout group with sudo usermod -aG dialout $USER, then log out and back in.

内容的提问来源于stack exchange,提问作者papisilv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:57:59