motor stop after 3 seconds

I’ve tried this code to make one project but the motor keeps on spinning without stopping after 3 seconds. Can anyone help? Thanks in advance!

sketch_jun02a.ino (1.86 KB)

Please include short programs in your Post like this

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
#define motorPin 3
//
int motorState = 0;             // motorState used to set the LED
unsigned long previousMillis;        // will store last time LED was updated
unsigned long startTime;
long interval = 1000;
boolean lastTrip;
//
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
int triggerDistance = 10;
//long duration, distance; // Duration used to calculate distance
//
void setup()
{
  pinMode(motorPin, OUTPUT);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
//
void loop()
{
  long distance = getDistance();
  if (distance > maximumRange)
  {
    Serial.println(F("Too Far!!"));
    digitalWrite(LEDPin, HIGH);
  }
  if (distance < minimumRange)
  {
    Serial.println(F("Too Close!!"));
    digitalWrite(LEDPin, LOW);
  }
  boolean tripped = (distance <= triggerDistance ? 1 : 0); // flag if triggered
  if (tripped)
  {
    if (tripped != lastTrip)
    {
      startTime = millis();
      motorState = 1;
    }
  }
  lastTrip = tripped;
  if (motorState == 1)
  {
    runMotor();
  }
}
//
long getDistance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  long dist = duration/58.2;
  return dist;
}
//
void runMotor()
{
  if( millis() - startTime < 3000UL) // Three Second Interval
  {
    analogWrite(motorPin, 25);
    //or digitalWrite(motorPin, HIGH);
  }
  else
  {
    analogWrite(motorPin, 0);
    //or digitalWrite(motorPin, LOW);
    motorState = 0;
  }
}

You need to add some Serial.print() statements so you can see if the value of startTime is being set correctly.

…R

@jeevanreddy312

TOPIC SPLIT
PLEASE DO NOT HIJACK / NECRO POST !

Could you take a few moments to Learn How To Use The Forum.
Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.