Python3中struct.unpack处理串口列表数据报错,求解决建议
Fixing Serial Data Parsing Error in Python 3
Hey there, let's work through your serial data parsing issue—those bytes-like object errors can be tricky when you're dealing with mixed list/bytes types! Let's break down what's going wrong and fix your code step by step.
Key Issues in Your Original Code
Let's highlight the main problems first:
- Serial Initialization Bug: You commented out
import serialand have a typo in creating the serial object (ser.serial.Serialshould beser = serial.Serial). - Incorrect Data Access:
tedDatais a list, andtedData[0]holds your 282-bytebytesblock. When you triedtedData[249:250], you're slicing the list instead of the actual bytes data. - Wrong
struct.unpackUsage:- The format string is incorrect:
<sis for a string, not a short integer—you need<hfor a little-endian 16-bit signed short (or<Hfor unsigned). - You passed a tuple as the first argument to
unpack, but it expects a single format string.
- The format string is incorrect:
- String Concatenation Error:
struct.unpackreturns a tuple, so you can't directly concatenate it with a string without extracting the value first.
Corrected Code
Here's the fixed version with explanations:
#!/usr/bin/env python3 import serial # Uncommented this—you need it to use serial! import struct # Fix serial initialization typo ser = serial.Serial("/dev/ttyUSB0", 19200) tedData = [] ser.write(b'\xaa') # Request packet # tedData[0] now holds the full 282-byte bytes block tedData.append(ser.read(282)) # Extract the 249th and 250th bytes (note: Python uses 0-indexing, so 248-250 slice) # Use '<h' for little-endian signed short; use '<H' if you need unsigned kwh_tuple = struct.unpack('<h', tedData[0][248:250]) # Extract the first (and only) value from the unpacked tuple kwh = kwh_tuple[0] # Convert kwh to string before concatenation (f-strings are cleaner for formatting!) print(f"KWH's Today = {kwh}") ser.close()
Additional Notes
- Indexing Clarification: If your hardware documentation refers to bytes starting at 1 (common in specs), then the 249th byte is index 248 and the 250th is index 249 in Python. The slice
[248:250]grabs exactly those two bytes. - Unsigned vs Signed: If your energy data is always positive, use
<H(unsigned short) instead of<hto avoid issues with sign bits. - Error Handling: For robustness, you might want to add checks to ensure
ser.read(282)actually returns 282 bytes (e.g.,if len(tedData[0]) != 282: print("Incomplete data received")).
内容的提问来源于stack exchange,提问作者PhippsJ
相关产品推荐
相关产品推荐

