如何使用 pyfirmata、python 和 Arduino 同时移动两个舵机

How to move two servos at the same time using pyfirmata, python and Arduino

我正在尝试对机器人手臂进行编程,我需要两个伺服系统同时 运行 并且能够 运行 在不同的方向上,例如从 90° 到 180° 和另一个伺服从 90° 到 0°,我正在使用 Arduino,python 和 pyfirmata 任何帮助都会很好谢谢!

import pyfirmata
import time

board = pyfirmata.Arduino('/dev/cu.usbmodem14201')

armlower2 = board.get_pin('d:6:s')
armlower1 = board.get_pin('d:10:s')

for angle in range(90, 180, 1):
    armlower2.write(angle)
    time.sleep(0.015)

for angle in range(180, 90, -1):
    armlower2.write(angle)
    time.sleep(0.015)

for angle in range(90, 0, -1):
    armlower1.write(angle)
    time.sleep(0.015)

for angle in range(0, 90, 1):
    armlower1.write(angle)
    time.sleep(0.015)

这会移动舵机,但一次只能移动一个?

你应该围绕“当前值”和“想要的值”的概念编写你的主循环,即你想要的值与你当前所在的值(角度)。这可以扩展到任意数量的电机,使用电机数组,并在循环中遍历它们的值。但是对于两个,您可以简单地执行以下操作。

// The angle values you want to achieve, and what they currently are
GLOBAL want1, want2
GLOBAL current1, current2
LOOP {
    LOCAL updelta = 1
    LOCAL downdelta = -1
    if want1 > current1
        movearm1(updelta)
        current1 = current1 + updelta
    else if want1 < current1
        movearm1(downdelta)
        current1 = current1 + downdelta
    if want2 > current2
        movearm2(updelta)
        current2 = current2 + updelta
    else if want2 < current2
        movearm2(downdelta)
        current2 = current2 + downdelta

    sleep(0.015)
}

最简单的方法是使用 threading,这是一个非常简单的示例:

import threading

def move_armlower2(): 
    for angle in range(90, 180, 1):
        armlower2.write(angle)
        time.sleep(0.015)

    for angle in range(180, 90, -1):
        armlower2.write(angle)
        time.sleep(0.015)

def move_armlower1():
    for angle in range(90, 0, -1):
        armlower1.write(angle)
        time.sleep(0.015)

   for angle in range(0, 90, 1):
        armlower1.write(angle)
        time.sleep(0.015)

threads = [
    threading.Thread(target=move_armlower2), # Creating threads
    threading.Thread(target=move_armlower1) 
]

for th in threads:
    th.start() # Starts the thread

for th in threads:
    th.join() # Waits for the thread to terminate

参考文献: