I am making a project in which I am using 4 Infrared sensors to take an input. The way I want it to work is such that when one of the sensors is triggered, the code listens for input from the other sensors for a fixed amount of time (say 2 seconds). Based on this data, further functions are executed.

I am assigning a number to each of the sensors, and the sequence in which they are triggered is stored in an array like:

// All relevant pins of the IR sensors are set to input with names ir1,ir2,ir3,ir4
int sequence[] = {0,0,0,0}
int s1 = digitalRead(ir1); //and similarly for all other pins
int counter = 0; 

  sequence[counter] = 1; //similarly 2 for s2 and so on
  counter ++;

What I am attempting to do is something like this:

if(s1 == 1 || s2==1 || s3 == 1 || s4 == 1){
   if(s1 == 1){
      sequence[counter] = 1;
      counter ++;

   //Start listening for other sensors
   } // similarly check which sensor is triggered first

   //Allow 2 seconds for input from all sensors (no input from either one of them is also allowed)
   // After 2 seconds execute some code based on the sequence array which got updated from inputs by different sensors

How do I accomplish this?

  • 2
    Definitely look at the timing principle shown in the BlinkWithoutDelay example, that comes with the Arduino IDE – chrisl Jul 31 '19 at 17:04

Here's some pseudocode that might help:

   if millis() - start time >= 2000
         time is up, do what you want with the sequence so far
         maybe a boolean flag here so you only do it once
   if any button is pressed
      if counter == 0
          set start time = millis() // start the timer
          set first in sequence
          add the button to the sequence
  • Thanks this worked. I put the code to check inputs from the sensors inside a while loop and used the millis() function as the while condition. Something like int a = millis(); int b= millis(); while(a-b <=200){... a=millis() // updates a at the end of every loop} – RishiC Aug 2 '19 at 3:08

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.