I am a Beginner in Arduino Programming. I am working on a project where I control A DC motor with IR sensor and arduino.
Until here it is fine. But I want the Motor to stop after one second even though the IR sensor detects the Obstacle
Here's My Program
Pin 2- IR Sensor Pin 4,5,6- Motor
enter code here
//Included Libraries
#include <motor.h>
//MACROS are defined here
Motor Motor1(4, 5, 6);
void setup() {
//put your setup code here, to run once:
pinMode(2, INPUT);
}
void loop() {
//put your main code here, to run repeatedly:
if(digitalRead(2)) {
Motor1.moveMotor(2.55*0);
}
else {
Motor1.moveMotor(2.55*100);
}
}
Can anyone help out in this Program. I Just want the Motor to stop after one second. Thank you in advance!
1 Answer 1
You need to use read the time (millis()
) when you start the motor and read it frequently while the motor is running to know when to stop it. You also need to keep track of the sensor, and don't start the motor again until after you've seen the sensor turn off (detect no obstacle). Here is an outline of the logic in psuedo-code; turn this into a detailed loop()
function in C++:
if the motor is ON {
if (millis() - motorStartMillis) > 1000 {
stop the motor;
}
else if sensor is ON {
if the sensor was OFF {
start the motor;
motorStartMillis = millis();
sensorWasOn = true;
}
}
else { // sensor must be off
sensorWasOn = false;
}
Explore related questions
See similar questions with these tags.
{}
button to format it.Motor1.moveMotor(2.55*100); delay(1000); Motor1.moveMotor(0);
work for you?StateChangeDetection