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

如何在Python中通过串口等待Arduino命令执行完成?

解决Raspberry Pi与多Arduino串口同步问题

第一步:修改Arduino端代码

每台Arduino在完成步进电机动作后,必须主动向Raspberry Pi发送完成信号。示例代码如下:

void setup() {
  Serial.begin(9600);
  // 初始化步进电机引脚等代码
}

void loop() {
  if (Serial.available() > 0) {
    String command = Serial.readStringUntil('\n');
    // 解析命令并执行步进电机动作的代码
    // ...(此处编写驱动步进电机的逻辑)
    
    // 动作完成后发送结束信号,必须加换行符方便Python端读取
    Serial.println("end");
  }
}

注意:两台Arduino的代码都要做此修改,且串口波特率要和Python端保持一致

第二步:Python端实现wait_for_string功能

pyserial没有内置该方法,我们可以自己封装一个函数,循环读取串口数据直到目标字符串出现:

import serial

# 初始化两个串口对象(根据实际端口和波特率调整)
serial = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
serial2 = serial.Serial('/dev/ttyACM1', 9600, timeout=1)

def wait_for_string(ser, target):
    while True:
        # 按行读取串口数据,自动处理换行符
        line = ser.readline().decode('utf-8').strip()
        if target in line:
            break

def control_arduino(command, nextcommand):
    # 给第一台Arduino发命令,注意加换行符匹配Arduino的读取逻辑
    serial.write((command + '\n').encode('utf-8'))
    wait_for_string(serial, "end")
    
    # 第一台完成后,给第二台发命令
    serial2.write((nextcommand + '\n').encode('utf-8'))
    wait_for_string(serial2, "end")
    
    print("ended doing x")

注意事项

  • 确保Raspberry Pi的串口权限正常,可通过sudo chmod 666 /dev/ttyACM0(对应端口)解决权限问题
  • 串口超时时间可根据实际动作时长调整,避免无限等待
  • 命令传递时统一用换行符作为结束标记,避免数据粘包问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:39:57