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

Python控制Arduino驱动双舵机异常动作问题求助

问题描述

用Python控制Arduino驱动两台舵机,当前问题:无论向Arduino发送何种字符/数字,舵机都会触发动作(错误数据不应触发),甚至出现两台舵机同时转动的情况。

Python代码

import serial
import time

def iniciar():
    try:
        arduino = serial.Serial("COM7", 9600)
        time.sleep(2)

        while True:
            a = int(input(": "))
            arduino.write(b'a')
            if a == "x":
                    break

    finally:
        arduino.close()

#while True:
iniciar()

Arduino代码

#include <Servo.h>
Servo ON;
Servo OFF;
char pr;

void setup() {
Serial.begin(9600);

OFF.attach(8);
ON.attach(9);

}

void loop() {
  if(Serial.available()>0){
    pr = Serial.read();
    if(pr == 'b'){ 
      ON.write(0);  // tell servo to go to a particular angle
      delay(1000);
      ON.write(90);              
      delay(500);
    }
    if(pr == 'a'){
      OFF.write(0);  // tell servo to go to a particular angle
      delay(1000);
      OFF.write(90);              
      delay(500);
    }
  } 
}

问题分析与解决方案

核心问题(Python端)

  1. 固定发送字符:当前代码中,无论输入什么内容,都会执行arduino.write(b'a'),所以每次输入都会触发Arduino中pr == 'a'的分支,导致OFF舵机必然动作。
  2. 输入逻辑错误:
    • 先将输入转为int,但后续判断a == "x"(字符串),int与字符串永远不相等,循环无法正常退出;若输入x,转int会直接抛出异常,进入finally关闭串口,但异常前可能已发送b'a'。
  3. 未处理输入异常:输入非数字字符时会直接崩溃,导致串口意外关闭。

修正后的Python代码

import serial
import time

def iniciar():
    arduino = None
    try:
        arduino = serial.Serial("COM7", 9600, timeout=1)
        time.sleep(2)
        print("输入a控制OFF舵机,输入b控制ON舵机,输入x退出")
        
        while True:
            user_input = input(": ").strip()
            if user_input.lower() == 'x':
                break
            # 只发送有效指令
            if user_input in ['a', 'b']:
                arduino.write(user_input.encode('utf-8'))
            else:
                print("无效指令,请输入a/b/x")

    except serial.SerialException as e:
        print(f"串口打开失败: {e}")
    finally:
        if arduino and arduino.is_open:
            arduino.close()

iniciar()

Arduino代码优化(可选)

改用else if避免多条件同时触发的可能,并添加无效指令处理:

#include <Servo.h>
Servo ON;
Servo OFF;
char pr;

void setup() {
  Serial.begin(9600);
  OFF.attach(8);
  ON.attach(9);
}

void loop() {
  if(Serial.available()>0){
    pr = Serial.read();
    if(pr == 'b'){ 
      ON.write(0);
      delay(1000);
      ON.write(90);              
      delay(500);
    } else if(pr == 'a'){
      OFF.write(0);
      delay(1000);
      OFF.write(90);              
      delay(500);
    } else {
      Serial.println("无效指令");
    }
  } 
}

验证步骤

  1. 上传修正后的Arduino代码到开发板。
  2. 运行修正后的Python代码,输入a测试OFF舵机,输入b测试ON舵机,输入x退出,输入其他字符应无舵机动作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:45:13