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

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 serial and have a typo in creating the serial object (ser.serial.Serial should be ser = serial.Serial).
  • Incorrect Data Access: tedData is a list, and tedData[0] holds your 282-byte bytes block. When you tried tedData[249:250], you're slicing the list instead of the actual bytes data.
  • Wrong struct.unpack Usage:
    • The format string is incorrect: <s is for a string, not a short integer—you need <h for a little-endian 16-bit signed short (or <H for unsigned).
    • You passed a tuple as the first argument to unpack, but it expects a single format string.
  • String Concatenation Error: struct.unpack returns 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 <h to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:48:24