Using two input sensors time delay to generate output


I am from biology background and new to arduino.
I am using this code for a behavioral experiment for my research.
I have 2 sensors as input. sensor-1 and sensor-2
I have 2 LEDs as output - LED1 and LED2.

When sensor-1 is triggered and in 10 seconds sensor-2 is also triggered, LED1 is lighted up for 500 ms.
But when sensor-2 is only triggered, both LED1 and LED2 is lighted up for 2 seconds.
sensor-1 can get triggered and sensor-2 may not get triggered in 20 ms.
It keeps repeating.

Here is the code I have written but its not working as I thought.
It will be of great help if anyone can solve the problem.


Here is the code

int sensor_1=6; //sensor1
int sensor_2=2;
int LED1=5;
int LED2=3;

unsigned long interval, start_time;
void setup() {
// put your setup code here, to run once:

void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(sensor_1)==HIGH)
interval=start_time+10000; //defining my interval as 20 seconds.

if (digitalRead(sensor_2)==HIGH && millis()<interval)

else if (digitalRead(sensor_2)==HIGH && millis()>interval)

sketch_apr04a.ino (853 Bytes)

If you want to detect a second sensor within a period of time you can't use delay() because nothing happens during a delay()

Have a look at how millis() is used to manage timing without blocking in Several things at a time

I think you need to save the value of millis() when the first sensor is detected and then keep checking the elapsed time. If the second sensor is detected before the 10 second interval elapses do one thing, otherwise do something else.

Dealing with the "when sensor-2 is only triggered" is a little more complex - you need some means to identify the fact that the detection sequence has been restarted so the program can ignore any earlier detection of sensor-1.

Your program really needs to work through a series of states - for example it starts in the waitingState. If sensor1 is triggered it goes to the sensor1detectedState in which it is wondering if sensor2 will be detected. etc etc. Eventually something need to return it to the waitingState. You could have a variable to keep track of the state using characters 'W' for waiting, '1' for sensor-1-detected etc.