Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-30b-a3b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

How to read serial port data from RPI 3B+ with python

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Kimikimi-k2-0711-preview’s answer.
  1. User

    How to read serial port data from RPI 3B+ with python

  2. Qwen Assistant

    To read serial port data from a Raspberry Pi 3B+ using Python, follow these steps:


    1. Configure the Raspberry Pi for UART

    By default, the Raspberry Pi's UART is used for the serial console. To use it for your application:

    • Disable the serial console:

      1. Run sudo raspi-config.
      2. Navigate to Interfacing Options > Serial.
      3. Choose No to disable the serial console.
      4. Reboot the Pi: sudo reboot.
    • Verify UART availability: After rebooting, check the available serial devices:

      ls /dev/tty*
      

      You should see /dev/ttyAMA0 (primary UART) or /dev/ttyS0 (mini UART). Use /dev/ttyAMA0 for the primary UART.


    2. Install PySerial

    Install the pyserial library using pip:

    pip install pyserial
    

    Or, for Python 3:

    sudo apt update
    sudo apt install python3-serial
    

    3. Python Code to Read Serial Data

    Here's a basic example to read data from the serial port:

    import serial
    import time
    
    # Configure the serial port
    try:
        ser = serial.Serial(
            port='/dev/ttyAMA0',       # Use '/dev/ttyS0' for mini UART
            baudrate=9600,              # Match the baud rate of your device
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1                 # Non-blocking read
        )
        print("Serial port opened successfully.")
    except serial.SerialException as e:
        print(f"Failed to open serial port: {e}")
        exit()
    
    # Read data continuously
    try:
        while True:
            if ser.in_waiting > 0:
                data = ser.readline().decode('utf-8').strip()
                print(f"Received: {data}")
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("Exiting...")
    finally:
        ser.close()
        print("Serial port closed.")
    

    4. Key Notes

    • Permissions: Run the script with sudo if you encounter permission errors:

      sudo python3 your_script.py
      

      Alternatively, add your user to the dialout group:

      sudo usermod -a -G dialout $USER
      

      Log out and back in for changes to take effect.

    • Hardware Connections: Ensure your device is connected to the Pi's GPIO pins 14 (TX) and 15 (RX) for the primary UART.

    • Baud Rate: Match the baud rate (9600 in the example) with your device's configuration.

    • Alternative Devices: If using a USB-to-serial adapter, the device will appear as /dev/ttyUSB0 (or similar). Replace port accordingly.


    5. Troubleshooting

    • No device found: Verify the correct port name and check connections.
    • Permission denied: Ensure the user has access to the serial port.
    • No data received: Check the baud rate, parity, and hardware wiring.

    By following these steps, you can successfully read serial data from the Raspberry Pi 3B+ using Python. Let me know if you need help with specific hardware setups!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.