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

树莓派3B+ USB RFID读卡器Serial.read()运行一段时间后报错

Fixing USB RFID Reader Disconnect/Read Errors on Raspberry Pi 3B+

Hey there, let's break down what's going on with your RFID reader issue—your core problem might actually be the device node you're using, and we'll walk through fixing that plus refining your code.

First: Why /dev/tty1 is the Wrong Choice

You noticed your reader is showing up as /dev/tty1 instead of the usual /dev/ttyUSB0//dev/ttyACM0, and that's a big red flag. /dev/tty1 is a virtual console (the first text-based screen output for your Pi), not a USB serial device. Even though you got a valid read once, it's likely a fluke from system redirection, and this mismatch is causing the "no data returned" errors when the console doesn't behave like a proper serial port.

Step 1: Find the Correct USB Serial Device Node

Let's locate the actual device path for your RFID reader:

  1. Unplug the RFID reader from your Pi.
  2. Run this command to list current serial devices:
    ls /dev/tty*
    
  3. Plug the reader back in, then run the same command again. Look for the new device that appeared—it'll be something like /dev/ttyUSB0 or /dev/ttyACM0.
  4. Double-check with dmesg to confirm:
    dmesg | grep tty
    
    You'll see a line like usb 1-1.2: ch341-uart converter now attached to ttyUSB0 that tells you the exact device.

Step 2: Revert Unnecessary UART Config Changes

Since you're using a USB reader (not the Pi's GPIO UART), the changes you made to /boot/config.txt (adding enable_uart=1) and /boot/cmdline.txt (removing console entries) are irrelevant here. You can revert those to default if you want to avoid messing with the Pi's onboard serial later.

Step 3: Fix Permissions (If Needed)

Your user might not have access to the serial device. Add yourself to the dialout group to fix this:

sudo usermod -aG dialout pi

Log out and back in for the changes to take effect.

Step 4: Refined Code for Reliable Reads

Your previous code had issues with blocking reads and outdated pyserial methods (like inWaiting()—newer versions use in_waiting). Here's a robust version that handles timeouts, disconnections, and proper data reading:

import serial
import time

def read_rfid():
    # Replace with your actual device path (e.g., /dev/ttyUSB0)
    serial_port = '/dev/ttyUSB0'
    baud_rate = 115200  # Confirm this matches your reader's default baud rate
    
    try:
        ser = serial.Serial(serial_port, baud_rate, timeout=1)
        print(f"Connected to RFID reader on {serial_port}")
        
        while True:
            # Check if data is available to read
            if ser.in_waiting > 0:
                # Read all available data and clean up whitespace
                card_data = ser.read(ser.in_waiting).decode('utf-8').strip()
                if card_data:
                    print(f"Scanned Card ID: {card_data}")
                # Clear the input buffer to avoid old data
                ser.flushInput()
            # Small delay to reduce CPU usage
            time.sleep(0.1)
            
    except serial.SerialException as e:
        print(f"Serial error occurred: {str(e)}")
        print("Make sure the reader is plugged in and the device path is correct.")
    except KeyboardInterrupt:
        print("\nExiting RFID reader program.")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("Serial port closed.")

if __name__ == "__main__":
    read_rfid()

Key Improvements:

  • Uses timeout=1 to prevent infinite blocking on ser.read()
  • Checks ser.in_waiting to only read when data is actually present
  • Decodes and strips whitespace to clean up the card ID output
  • Properly handles serial exceptions and keyboard interrupts
  • Ensures the serial port is closed cleanly when exiting

Troubleshooting Remaining Issues

If you still run into problems:

  1. Verify Baud Rate: Some RFID readers default to 9600 instead of 115200. Check your reader's manual or try changing the baud_rate value in the code.
  2. Check for Conflicting Processes: Make sure no other programs are using the serial port. Use this command to check:
    lsof /dev/ttyUSB0
    
    Kill any conflicting processes if found.
  3. Test the Reader on Another Device: Plug the reader into a Windows/macOS computer with a serial monitor to confirm it works consistently—this rules out a faulty reader.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:25:14