SDS011传感器字节输出异常及Python3脚本无限循环问题求助
Hey there, let's figure out why your sensor_read function is stuck in an infinite loop—this is a common pitfall when adapting Python 2 code to Python 3, so let's break it down step by step:
1. The Core Problem: Bytes vs. String Mismatch
In Python 3, the ser.read() method returns bytes objects, not regular strings. Your code is comparing the returned byte to the string "\xaa", which will never match because they're different data types. That's why your loop never exits.
2. Broken Frame Reading Logic
Even if you fixed the type mismatch, your current code has a logic flaw: you're reading 1 byte, then immediately reading 10 more bytes before confirming you've found the frame header. This means you might skip over the actual 0xaa header or read incomplete frames, making the sensor data impossible to parse correctly.
Fixed Version of the sensor_read Function
Here's the corrected code that addresses both issues:
def sensor_read(): while True: # Read one byte at a time until we find the frame header (0xaa in bytes) byte = ser.read(size=1) if byte == b"\xaa": # Now read the remaining 10 bytes of the frame d = ser.read(size=10) # Check if we got a full frame and the confirmation byte is correct if len(d) == 10 and d[0] == b"\xc0": process_frame(byte + d) # Optional: break after processing one valid frame, or remove to keep reading continuously break
Key Changes Explained:
- Bytes Comparison: Used
b"\xaa"andb"\xc0"instead of string literals to match the bytes returned byser.read(). - Proper Frame Sync: We first loop until we find the
0xaaheader, then read the rest of the frame. This ensures we only process valid, complete sensor frames. - Length Check: Added
len(d) == 10to make sure we actually read all 10 bytes of the frame (serial reads can sometimes return partial data if there's noise or the sensor is still initializing).
Do You Need to Wait Minutes?
No—SDS011 sensors typically start outputting data within a few seconds of powering on. The infinite loop is definitely a code issue, not a timing problem.
内容的提问来源于stack exchange,提问作者Marie03

