Reputation: 9
I am currently trying to make an operating plinko machine with a claw that moves back and forth via an h bridge reversing a dc motor every few seconds. I need my pushbutton to stop the DC motor in the middle of a delay. I know that this can be done using the millis()
function, but I am still pretty confused on how to use it for the scenario (seeing that I am only a beginner.)
#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;
}
}
Upvotes: 0
Views: 1560
Reputation: 962
You should NEVER use delay().. its bad practice.. and is considered a 'code-blocking' function. as previously stated.. use millis()
by using millis() you can then check for your button state as normal.
Upvotes: 0
Reputation: 1093
You can use interrupts for this.
But you will need to connect the button to specific pins on the Arduino. If you are using the Arduino Uno you will have to connect the button to pin number 2 or 3. The list of boards and interrupt pins which can be used are given here https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const int btn_pin=2; //you could use 3
First you will have to define a function that stops the motors
void stopMotors(){
digitalWrite(Pin_1A, HIGH); //I am assuming this is the configuration stops the motor in your system.
digitalWrite(Pin_2A, HIGH);
}
Use the following in your setup function.
attachInterrupt(digitalPinToInterrupt(btn_pin), stopMotor, FALLING);
While I feel using interrupts is the easier solution for you, you can use millis in the following manner
long time=millis()+1000; //Change this number to the delay you want.
while((time>millis())&&(digitalRead(btn_pin)==HIGH)); //pin state becomes an escape.
I hope this helps.
Upvotes: 1