我目前正在尝试制造一个带爪的操作plinko机器,它通过h桥来回移动,每隔几秒钟就会转动一个直流电机。我需要我的按钮在延迟中间停止直流电机。我知道这可以使用millis()函数完成,但我仍然很困惑如何将它用于场景(看到我只是一个初学者。)如果有人可以请帮助我,或更改我的代码,请这样做。
#include <Servo.h>
Servo servo;
const int btn_pin = 9;
const int servo_pin(8);
const int EN_Pin(3);
const int Pin_1A(4);
const int Pin_2A(2);
int btn_prev = HIGH;
void setup() {
servo.attach(servo_pin);
Serial.begin(9600);
pinMode(btn_pin, INPUT_PULLUP);
pinMode(7, OUTPUT);
pinMode(EN_Pin, OUTPUT);
pinMode(Pin_1A, OUTPUT);
pinMode(Pin_2A, OUTPUT);
}
void loop() {
int btn_state;
btn_state = digitalRead(btn_pin);
while ( btn_state == HIGH )
digitalWrite(Pin_1A, HIGH);
digitalWrite(Pin_2A, LOW);
analogWrite(EN_Pin, 255);
delay(1000);
digitalWrite(Pin_1A, LOW);
digitalWrite(Pin_2A, HIGH);
delay(1000);
if ( (btn_prev == HIGH) && (btn_state == LOW) ) {
digitalWrite(7, HIGH);
servo.write(45);
delay(2500);
servo.write(-45);
btn_prev = btn_state;
}
}
答案 0 :(得分:1)
您可以使用中断。
但是你需要将按钮连接到Arduino上的特定引脚。如果您使用的是Arduino Uno,则必须将按钮连接到2号或3号针脚。 这里给出了可以使用的板和中断引脚列表 https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const int btn_pin=2; //you could use 3
首先,您必须定义一个停止电机的功能
void stopMotors(){
digitalWrite(Pin_1A, HIGH); //I am assuming this is the configuration stops the motor in your system.
digitalWrite(Pin_2A, HIGH);
}
在设置功能中使用以下内容。
attachInterrupt(digitalPinToInterrupt(btn_pin), stopMotor, FALLING);
虽然我觉得使用中断对您来说更容易,但您可以通过以下方式使用millis
long time=millis()+1000; //Change this number to the delay you want.
while((time>millis())&&(digitalRead(btn_pin)==HIGH)); //pin state becomes an escape.
我希望这会有所帮助。
答案 1 :(得分:0)
你永远不应该使用延迟()..这是一种不好的做法..并被认为是一种“阻止代码”的问题。功能。如前所述..使用millis()
通过使用millis(),您可以正常检查按钮状态。