One simple solution could be:
Start by noticing the first time you get the HIGH
input whit a simple if statement:
if (digitalRead(sensor) == HIGH) {
}
where sensor
is the pin of the sensor according to your code.
When this statement is True
, you are interested in remain here until one of two things happens:
- either you interrupt some kind of loop with another
HIGH
input,
- or the time you have set is passed.
One way of knowing elapsed times will be with the millis()
function, that returns the milliseconds since the board began running.
We should get the elapsed time the first time we enter the loop:
if (digitalRead(sensor) == HIGH) {
long startTime = millis();
}
Then, as I have said, we need to remain here for a specific amount of time. We could use the while
loop, but, which condition needs to be true
?
So we have a start time, lets said x
and you need to stay in the loop for, let's say, y
milliseconds. This is the same as saying that you want to stay in the loop until the time we enter the loop and a specific amount of milliseconds, x+y
. When the millis()
function gives us a greater number, we should exit the loop:
if (digitalRead(sensor) == HIGH) {
long startTime = millis();
while (millis() <= (startTime+1000))
// ^ The second you are interested, 1000 milliseconds.
}
Now, we have to check if there is another interrupt during this time, by using the same statement of the beginning:
if (digitalRead(sensor) == HIGH) {
long startTime = millis();
while (millis() <= (startTime+1000)) {
if (digitalRead(sensor) == HIGH) {
// 2 interrupts in less than 1000 millis!
}
}
}
Summarizing is nicer to declare a global with the specific time we want, instead of the 1000
value we are using now:
const long maxTimeInterval = 1000;
And changing it in our code (that is inside the loop()
)
if (digitalRead(sensor) == HIGH) {
long startTime = millis();
while (millis() <= (startTime+maxTimeInterval)) {
if (digitalRead(sensor) == HIGH) {
// 2 interrupts in less than 1000 millis!
digitalWrite(LED, HIGH);
}
}
}
Hope this helps!