How to use timer for counting interrupted beam of IR LED?

Dear all;
I have a circuit with arduino connected to Photo diode and IR LED. I want to count number of interrupted beam and also duration of interrupted beam of IR. How to count the duration of interrupted beam ? The program is as follows:

int pd=7; //photodiode
int LED=12; // indicator of the interrupted beam
int senRead=0;
int limit=850; //Threshold range of an obstacle
int count=0;
int val;

void setup()
{
pinMode(pd,OUTPUT);
pinMode(LED,OUTPUT);
digitalWrite(pd,HIGH); //supply 5 volts to photodiode
digitalWrite(LED,LOW); //set the LED in off mode (initial condition)
Serial.begin(9600); //setting serial monitor at a default baund rate of 9600
attachInterrupt(0, test,RISING);

}

void test()
{
count++;
Serial.println(count);

}

void loop()
{

int val=analogRead(senRead);

if(val <= limit) //If obstacle is nearer than the Threshold range

{
digitalWrite(LED,HIGH); // LED will be in ON state

}
else if(val > limit) //If obstacle is not in Threshold range
{
digitalWrite(LED,LOW); //LED will be in OFF state

}

}

How to count the duration of interrupted beam ?

Save the time from millis() when the beam [u]becomes[/u] interrupted and increment a counter variable. Save the time from millis() when the beam [u]becomes[/u] uninterrupted. Subtract one from the other to derive the duration.

Note the need to detect when the beam [u]becomes[/u] interrupted not when it [u]is[/u] interrupted. See the StateChangeDetection example in the IDE for the way to do it. The example uses a digital input but the principle is the same for an analogue input.

Hello,

why reinvent the wheel?

https://www.arduino.cc/en/Reference/PulseIn

The Arduino language has a built in function to detect such things. At least, if I understand your Project correctly.

Also, you’re throwing a lot more code at the Problem than necessary.

If val is not less than or equal to limit, what else could it be but greater than limit? The if following the else is unnecessary.

For that matter, you could accomplish the same Task without a single if/else:

digitalWrite(LED, val <= limit);

The Compiler is smart enough that your code is only marginally larger in compiled Bytes than the single line, but personally, I think the single line is sufficient and easier to read, but that is only my opinion.

The Arduino language has a built in function to detect such things.

The pulseIn() function blocks program execution. Saving millis() at the start and end of activation does not.