【发布时间】:2017-11-08 20:38:06
【问题描述】:
我正在从事另一个学校项目,我正在尝试制作障碍课程(模型尺寸)。对于这个项目,我使用了 2 个伺服电机,我想用 2 个不同的按钮来控制它们。所以 1 个按钮连接到 1 个伺服电机,另一个按钮连接到另一个伺服。我实际上正在努力让两个按钮都与伺服电机一起工作。
当我连接 1 个按钮和 1 个伺服电机时,一切都完全按照我想要的方式工作。我按下按钮,伺服电机旋转 90 度,5 秒后返回。
代码:
#include <Servo.h>
Servo myservo;
const int servoPin = D8; // Servo pin
const int buttonPin = D7; // Pushbutton pin
void setup() {
myservo.attach(servoPin);
pinMode(buttonPin, INPUT);
}//setup
void loop() {
if (digitalRead(buttonPin) == HIGH) {
myservo.write(180);
delay(50); // waits 50ms to reach the position
delay(15000);//15 seconden wachten
myservo.write(0);
delay(50); // waits 50ms to reach the position
}
}//loop
但是我在一个论坛上读到,当您想使用多个伺服电机时,您必须以不同的方式编写代码。你必须包括这样的伺服电机:
#include <Servo.h>
Servo myservoa, myservob;
当我更改代码时,一切都停止了工作,我真的不明白我在这里做错了什么。我希望伺服电机同时工作,有 2 个不同的按钮。
新代码:
#include <Servo.h>
Servo myservoa, myservob;
const int servoPin1 = D8; // Servo pin
const int servoPin2 = D6; // Servo pin
const int buttonPin1 = D7; // Pushbutton pin
const int buttonPin2 = D5; // Pushbutton pin
void setup() {
myservoa.attach(servoPin1);
myservob.attach(servoPin2);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
}//setup
void loop() {
if (digitalRead(buttonPin1) == HIGH) {
myservoa.write(90);
delay(50); // waits 50ms to reach the position
delay(5000);// 5 seconden wachten
myservoa.write(0);
delay(50); // waits 50ms to reach the position
}
if (digitalRead(buttonPin2) == HIGH) {
myservob.write(90);
delay(50); // waits 50ms to reach the position
delay(5000);// 5 seconden wachten
myservob.write(0);
delay(50); // waits 50ms to reach the position
}
}//loop
希望有人能帮帮我!
编辑:
所以我发现 2 个伺服电机实际上对我的 NodeMCU 来说太多了。 cmets 中的代码运行良好!现在我正在尝试将伺服电机与小型振动电机结合起来。 2 个传感器可以很好地协同工作,但我无法让振动电机正常工作。
我希望振动电机在按下按钮后振动 5 秒钟。 5 秒后它必须自动停止。使用代码,振动电机仅在我按下按钮时振动。未按下按钮时,振动电机直接停止。
代码:
#include <Servo.h>
Servo myservo;
const int servoPin = D8; // Servo pin
const int vibratiePin = D3; // Servo pin
const int buttonPin1 = D6; // Pushbutton pin
const int buttonPin2 = D5; // Pushbutton Pin
unsigned long stopA = 0;
unsigned long stopB = 0;
bool controlA = false;
bool controlB = false;
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
myservo.attach(servoPin);
pinMode(vibratiePin, OUTPUT);
}//setup
void loop() {
unsigned long now = millis();
if(controlA && stopA < now) {
myservo.write(0);
controlA = false;
} else if (!controlA && digitalRead(buttonPin1) == HIGH) {
controlA = true;
myservo.write(90);
stopA = millis() + 5000;
}
if(controlB && stopB < now) {
digitalWrite(vibratiePin, LOW);
controlB = false;
stopB = millis() + 5000;
} else if (!controlB && digitalRead(buttonPin2) == HIGH) {
controlB = true;
digitalWrite(vibratiePin, HIGH);
}
stopB = now;
}
我希望有人能看到这里的问题,因为我不明白我做错了什么。
【问题讨论】: