【发布时间】:2021-10-23 07:17:41
【问题描述】:
我想为具有三个按钮和一个步进电机的系统创建一个 Arduino 程序。如果按下按钮 1,步进器应该向前移动 50 步。如果按下按钮 2,步进器应后退 50 步。如果按下按钮 3,则步进器应在向后 50 步后向前移动 50 步。
我使用了 Arduino 的步进器库并编写了以下代码。函数Forward()、Backward() 和Continuous() 实现每个按钮要执行的操作。每个函数逐步移动电机并将动作记录在串行输出上。
但我无法达到我想要的结果:步进器不会后退而只会前进。更准确地说:
-
Forward()按预期工作 -
Backward()产生预期的日志输出(最多计算步数 50),但电机只向前移动而不是向后移动。 -
Continuous()函数也不起作用:在前进 50 步后(移动并记录步数),它会继续前进,只为计数器记录 1。
我需要你的帮助。如何使电机在Backward() 中后退?以及如何纠正Continuous()实现前进后退,并产生正确的后退步数?
这是我的代码:
#include <Stepper.h>
int forward_button = 2;
int backward_button = 3;
int cont_button = 4;
int button_cond1;
int button_cond2;
int button_cond3;
int del = 50;
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
int steps;
void Forward() { // should go forward by 50 steps
int stepCount = 0;
while (stepCount < 50) {
steps = 1;
myStepper.step(steps);
stepCount++;
delay(del);
Serial.print("Forward steps :");
Serial.println(stepCount);
}
}
void Backward() { // should go backward by 50 steps
int stepCount = 0;
while (stepCount < 50) {
steps = 1;
myStepper.step(steps);
stepCount++;
delay(del);
Serial.print("Backward steps :");
Serial.println(stepCount);
}
}
void Continuous() { // should go forward by 50 steps, then backwards
int stepCount = 0;
while (stepCount < 50) {
steps = 1;
myStepper.step(steps);
stepCount++;
delay(del);
Serial.print("Continuous steps :");
Serial.println(stepCount);
}
while (50 < stepCount <= 200) {
int stepCount = 0;
steps = 1;
myStepper.step(steps);
stepCount++;
delay(del);
Serial.print("Continuous steps :");
Serial.println(stepCount);
}
}
void setup() {
// initialize the serial port:
Serial.begin(9600);
pinMode(forward_button, INPUT_PULLUP);
pinMode(backward_button, INPUT_PULLUP);
pinMode(cont_button, INPUT_PULLUP);
//myStepper.setSpeed(60);
}
void loop() {
// step one step:
button_cond1 = digitalRead(forward_button);
button_cond2 = digitalRead(backward_button);
button_cond3 = digitalRead(cont_button);
if ((button_cond1 == LOW) && (button_cond2 == HIGH) && (button_cond3 == HIGH)) {
Forward();
}
else if ((button_cond1 == HIGH) && (button_cond2 == LOW) && (button_cond3 == HIGH)) {
Backward();
}
else if ((button_cond1 == HIGH) && (button_cond2 == HIGH) && (button_cond3 == LOW)) {
Continuous();
}
}
【问题讨论】:
-
stepsPerRevolution在 Backward() 中更改但未使用。它不会改变步进器发生的情况。 -
为什么要更改
stepsPerRevolution,尤其是在 Stepper 对象被初始化之后?你试过myStepper.step(-1)吗?你定义了一个Forward()和一个Backward()函数,为什么不在Continuous()中使用它们呢? -
其实我忘了删除它们。我只尝试了 .step(1) 和 .step(-1) 而不是它们,但结果是一样的
-
我现在要编辑问题中的代码
-
while (50 < stepCount <= 200) {看起来不对..