Line follower - run when see HIGH after a specific time.

Hey Arduino Forum.
I am trying to make my line follower better, and wanted to change my IF statements to only run the code if the sensors see HIGH or LOW in an amount of time.
How would i do this?

This is my code so far: (running with 3 sensors, and this code works, just wanna improve it)

//libraries
#include <TimerOne.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

//Ports assigned
int IR_left = 2; //IR sensor on port D2
int IR_right = 4; //IR sensor on port D4
int IR_mid = 3; //IR sensor on port D3
int normal = 100; // default Speed of motors (0-255)
int maxspeed = 255; //max speed of motors (0-255)
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *motor_right = AFMS.getMotor(1); //motor 1 on port M1
Adafruit_DCMotor *motor_left = AFMS.getMotor(2); //motor 2 on port M2

void setup(){
  AFMS.begin();
  motor_left->setSpeed(normal);
  motor_right->setSpeed(normal);
  Serial.begin(9600);
  pinMode(IR_left, INPUT);
  pinMode(IR_right, INPUT);
  pinMode(IR_mid, INPUT);
} 



void loop(){
  
  if ((LOW == digitalRead(IR_left)) && (LOW == digitalRead(IR_right)) && (HIGH == digitalRead(IR_mid))){
    motor_left->setSpeed(normal);
    motor_right->setSpeed(normal);
    motor_left->run(FORWARD);
    motor_right->run(FORWARD);
  }
  else {
    if(HIGH == digitalRead(IR_mid)){
      if(HIGH == digitalRead(IR_left)){
        motor_left->setSpeed(maxspeed);
        motor_right->setSpeed(normal);
      }
      else{
        motor_left->setSpeed(normal);
        motor_right->setSpeed(maxspeed);
      }
    }
    else{
      motor_left->run(BACKWARD);
      motor_right->run(BACKWARD);
    }
  }

}

If you want to know when an input has remained HIGH for a specified time, read the input state periodically. If it is LOW, save the current time in a global variable. If it is high, subtract the saved value from the current time to work out how long ago you saw LOW. If that interval exceeds your threshold, you know the input has remained HIGH for the corresponding duration.

hmm, and there isn't some command i can use for getting the time on that?
I can't use PulseIn for it?

uruloke:
hmm, and there isn't some command i can use for getting the time on that?

It's like... 4 lines of code!

const unsigned long SOME_TIME_INTERVAL = 3000; // 3 seconds
static unsigned long lastTimeMySignalWasLow = millis();

if (digitalRead(mySignalPin) == LOW))
{
   lastTimeMySignalWasLow = millis();
}

if (millis() - lastTimeMySignalWasLow >= SOME_TIME_INTERVAL)
{
   // perform some action only after the signal has been HIGH for at least SOME_TIME_INTERVAL
}

Ah thanks a lot!
Did not really think that i could just create it like that :slight_smile: