Hello all, I am trying to write a code that uses two IR sensors to detect fan motion and lighting up an LED when motion is detected. I am using a black fan with a white strip for detection. Whenever the white strip passes the sensor it activates, lighting the LED. In order to prevent false readings, I am trying to get the LED to turn off after three seconds in case it lands on the white strip. However, my code instead is turning the LED off briefly every three seconds regardless of the sensor input. How can I fix my code so that the LED will turn off only after three seconds and with no change in the sensor? Right now this code is only using one sensor but I would like to use multiple eventually. Any help would be appreciated.
int IRSensor1 = 2; // connect ir sensor 1 to arduino pin 2
int LED1 = 13; // connect led1 to arduino pin 13
#define LED1_OFF LOW // digitalWrite value to turn LED off
#define LED1_ON HIGH // digitalWrite value to turn LED on
// state machine state names
#define ST_OFF 0
#define ST_TIMING 1
#define ST_NO_MOTION 2
// LED on-time constant
const unsigned long TIME_LED1_ON = 3000ul; // 3000mS == 3-seconds
void setup()
{
Serial.begin(9600);
pinMode (IRSensor1, INPUT); // sensor1 pin INPUT
pinMode (LED1, OUTPUT); // LED1 pin OUTPUT
}
void loop()
{
static byte
stateLED1 = ST_OFF;
static unsigned long
timeLED1;
unsigned long
timeNow;
timeNow = millis();
delay(1);
int statusSensor1 = digitalRead (IRSensor1);
switch( stateLED1 )
{
case ST_OFF:
if ( statusSensor1 == LOW )
{ digitalWrite( LED1, HIGH ); // motion seen; turn on the LED
timeLED1 = timeNow; // set the timeLED1 variable to the "current" time
stateLED1 = ST_TIMING;
}
break;
case ST_TIMING:
if ( timeNow - timeLED1 >= TIME_LED1_ON )
{ digitalWrite( LED1, LOW );
stateLED1 = ST_NO_MOTION;
}
break;
case ST_NO_MOTION:
if ( statusSensor1 == HIGH )
{ digitalWrite( LED1, LOW );
stateLED1 = ST_OFF;
}
break;
}
}