您想检测 2 次闪光之间恰好 1 秒发出的 3 次不同闪光吗?
所以 2 秒内闪烁 3 次(不是 4 次)...?
(flash1 是开始,flash2 1 秒后,flash2 2 秒后。所以 2 秒内闪 3 次)。
这是一个简单的代码,没有计时器,也没有执行此检测的数组:
light_1=sample(1);
for(::){
// the while loop waits for the first flash, ie : wait for sample(2) > light_1
while(sample(2) <= (light_1))
{
// if you know that a flash lasts n ms, you can add "sleep(n);" in this loop, so you will use less cpu.
}
// now the first flash is emitted, we will wait for 1 second before looking for the second flash
delay(1);
if(sample(3) <= light_1)
continue;
// if after 1 second, there is no flash, ther will not be 3 flashes in 2 seconds.
// so we restart from the first flash (the "continue;" instruction do that)
delay(1); // the second flash was catched, then we wait for 1 second before looking for the third flash.
if(sample(4) <= light_1)
continue;
//so if sample(4 > light_1), we have 3 flashes, each 2 are separated by 1 second then you can do the function you want.
do function...
// once finish the function, we loop back to the beginning to start looking for the first flash again.
}
您必须确保在发出闪光灯时未拍摄 light_1 = sample(1)。
我想到了两种方法:
1 - 如果你知道闪光灯的长度(例如:20 毫秒),取 3 或 4 个与闪光灯的长度分开的值,以获得好的 light_1 值:
int i;
light_1 = sample(1);
for(i=0 ; i<4 ; i++)
{
light_1 = sample(1) < light_1 ? sample(1) : light_1;
sleep(20); // 20 = 20 ms. you can replace 20 by lenght_of_flash
}
2 - 通过校准。然后你可以使用没有闪光灯获得的值来初始化light_1;
如果你想在不知道周期的情况下在 4 秒内获得 3 次闪烁,我认为有必要使用计时器:
这里是伪代码:
light_1 = sample();
int nb_flashes = 0;
bool fail = false;
clock_t start; to contain the time
for(::)
{
fail = false;
nb_flashes = 0;
start = clock(); //get the time to count 4 seconds.
while(nb_flashes <3)
{
while(sample() <= (light_1))
{
sleep(1);
}
nb_flashes ++;
if( (clock() - start)/CLOCKS_PER_SEC >=4)
{
fail = true; //more than 4 seconds where elapsed... so we restart from the beginning of the for loop.
break; //going outside the while loop
}
while(sample() > light_1 )
sleep(1); //waiting the end of the irst flash.
}
if (fail)
continue; // there was no 3 flashes whithin 4 seconds, so we restart from the beginning of the for loop
else
do function // do the function you want...
}