【问题标题】:How do you end a delay for Arduino你如何结束 Arduino 的延迟
【发布时间】:2018-05-14 23:19:57
【问题描述】:

我目前正在尝试制作一个可操作的 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;

  }

}

My cad circuitry

【问题讨论】:

  • 欢迎来到stackoverflow!只是想说,当您寻求原始代码的帮助时,最好对您的代码进行注释并特别标记您需要帮助的地方。这为我们省去了很多麻烦。
  • 好的,感谢您的建议,注意

标签: c++ arduino embedded delay


【解决方案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);

虽然我觉得使用中断对你来说是更简单的解决方案,但你可以通过以下方式使用毫秒

long time=millis()+1000; //Change this number to the delay you want.
while((time>millis())&&(digitalRead(btn_pin)==HIGH)); //pin state becomes an escape.

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您永远不应该使用 delay().. 这是不好的做法.. 并且被认为是“代码阻塞”功能。如前所述.. 使用millis()

    通过使用millis(),您可以正常检查您的按钮状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      相关资源
      最近更新 更多