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

如何通过PySerial跳过特定字节,避免读取无用的27、28字节?

Can PySerial skip reading specific bytes?

Great question! Let's break down how this works with PySerial and serial communication in general.

First, a key reality: Serial communication operates as a byte stream—your serial hardware (and PySerial by extension) can't "skip" bytes before they're received. The port will capture all incoming bytes, and PySerial just exposes that stream to your code. So you can't tell the hardware to ignore bytes 27 and 28 entirely, but you can optimize your reading logic to avoid storing or processing those unwanted bytes, which achieves your goal of not dealing with them unnecessarily.

Here's a clean, intentional approach tailored to your 33-byte frame:

  1. Read the first 26 bytes (the ones you need: positions 1-26)
  2. Read the next 2 bytes (positions 27-28) but discard them immediately (no need to assign them to a variable you'll use)
  3. Read the final 5 bytes (positions 29-33) which you need

Here's the code example:

import serial

# Initialize your serial port (adjust port, baud rate, timeout to match your setup)
ser = serial.Serial('COM3', 9600, timeout=2)

try:
    # Grab the first 26 useful bytes
    useful_part1 = ser.read(26)
    # Skip the 2 unwanted bytes by reading them without storing
    ser.read(2)
    # Grab the remaining 5 useful bytes
    useful_part2 = ser.read(5)
    
    # Combine the parts you care about
    final_data = useful_part1 + useful_part2
    
    # Use your data here (example: print as hex)
    print(f"Received useful data: {final_data.hex()}")
finally:
    # Always close the port when done
    ser.close()

Quick notes to keep in mind:

  • This works reliably only if your data is sent as fixed-length 33-byte frames. If there's any risk of frame misalignment (e.g., dropped bytes, line noise), add a frame sync step first—like looking for a unique header byte/sequence at the start of each frame. This ensures you're starting to read at position 1, not somewhere in the middle.
  • While you technically still "read" the 2 unwanted bytes, this approach is more intentional than reading all 33 bytes and slicing later. It makes your code's purpose clear, and avoids holding unnecessary data in memory longer than needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:21:06