我目前正在尝试使用RPi上托管的Nodebot johnny-five.io来控制连接到Arduinos的伺服系统的配置。我的主要目标是从头开始做一个六足机器人;我不喜欢工具包的想法,因为它都是你拼凑起来的千篇一律的代码和部件,它或多或少是一辆遥控汽车,你什么都没学到。
我刚刚学到了伺服的基础知识(我选择了伺服而不是步进电机)。不幸的是,默认情况下,伺服速度不能通过PWM控制,只能通过位置控制。因此,绕过这一点的方法是创建一个环路,该环路一次将伺服增加1度(或更多),并在环路中延迟X ms,直到伺服达到所需的位置。现在,这是很好的,所有如果你只控制一个伺服在同一时间或X数量的伺服移动到一个设定的位置到另一个。但我想要一个流畅的运动;我希望一条腿在另一条腿停止之前开始移动。运动中真正的流畅性,为了实现这一点,我需要一个无限循环来检查API将接收的控制命令设置的输入状态。
这里的问题是while循环不是异步的。因此,我需要找到一种方法来启动一个循环,该循环将不同的伺服设置在不同的速度范围和不同的位置,并在循环结束时检查新的输入状态更新。我需要在不造成内存泄漏的情况下做到这一点。
一种方法是为每个伺服创建一组异步工作的依赖脚本(每条腿3个伺服,6条腿,18个伺服,因此18个微型依赖项),但我不确定这是否会给RPi带来太多开销或太大的压力。
我是不是想多了?
发布于 2018-09-16 04:41:33
您可以创建一个简单的伺服类,并使用“update”方法为每个实例提供自己的速度和起始位置。使用较长的延迟可使伺服运动较慢。在主循环中,你可以不断地检查一些输入,如果需要的话,告诉伺服系统移动,使用update方法。
#include <Servo.h>
class HexapodLegServo
{
Servo servo; // Servo instance
int pos; // Position/angle of the servo
int delay_millis; // 'Delay' between each update
long prev_millis;
int degree_change; // Angle increase each update
int start_pos; // Position to start at
int pin; // Pin servo is connected to
public:
HexapodLegServo (int whichPin, int delayMillis=15, int startPos=0)
{
pin = whichPin;
delay_millis = delayMillis;
start_pos = startPos;
degree_change = 1;
}
void attachToPin()
{
servo.attach(pin);
setStartPos();
}
void setStartPos() // Set initial position of the servo
{
servo.write(start_pos);
pos = start_pos;
}
void update() // Servo sweeps from end to end, and back
{
if (millis()-prev_millis > delay_millis)
{
prev_millis = millis();
servo.write(pos);
pos += degree_change;
if ((pos <= 0) || (pos >= 180))
{
degree_change *= -1; // Start moving in the reverse direction
}
}
}
};
// Main script
const int BUTTON = 4; // Button on pin 4
HexapodLegServo right_leg(9);
HexapodLegServo left_leg(10, 30, 90);
void setup()
{
Serial.begin(9600);
pinMode(BUTTON, INPUT_PULLUP); // Using a button to tell servos when to move
right_leg.attachToPin();
left_leg.attachToPin();
}
void loop()
{
if (digitalRead(BUTTON) == LOW) // If button is pushed (can be any type of input)
{ // update the position of the servos continuously
right_leg.update();
left_leg.update();
}
}https://stackoverflow.com/questions/52337543
复制相似问题