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)) {
    else {

Can anyone help out in this Program. I Just want the Motor to stop after one second. Thank you in advance!

  • First, edit your question, select all of your code, and tap the {} button to format it.
    – Duncan C
    Jun 5, 2020 at 19:52
  • 1
    Also, you need to explain your goal more clearly. What should start your motor? The IR sensor? You say "I want the Motor to stop after one second as soon as the sensor detects the Obstacle." I don't understand what that means. You want it to run for at least one second no matter what, and after a second passes, have the IR sensor stop it if it detects and obstacle?
    – Duncan C
    Jun 5, 2020 at 19:56
  • after one second” alongside “as soon as” is a contradiction. Jun 5, 2020 at 19:58
  • 1
    Does Motor1.moveMotor(2.55*100); delay(1000); Motor1.moveMotor(0); work for you? Jun 5, 2020 at 20:42
  • 1
    look at example sketches in the Arduino IDE ... look at the one named StateChangeDetection
    – jsotola
    Jun 6, 2020 at 18:52

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.