/* * PIR controlled LED strip */ enum LightStates { Off, TurningOn, On, TurningOff }; int ledPin = 3; // choose the pin for the LED int inputPin = 2; // choose the input pin (for PIR sensor) LightStates lightState = Off; // we start, assuming lights are off int val = 0; // variable for reading the pin status const int Delay = 50; // milliseconds const int SleepDelay = 1000; // Loop delay when lights are off. const int IntensityStep = 4; // Intensity change per loop iteration when switching on/off const long LightTimeout = 300000;// Time between last motion detection and lights out, in milliseconds. long lastMotion = 0; int lightIntensity = 0; int nextDelay = 50; void setup() { pinMode(ledPin, OUTPUT); // declare LED as output pinMode(inputPin, INPUT); // declare sensor as input //Serial.begin(9600); } void loop() { val = digitalRead(inputPin); // read input value if (val == HIGH) { //Serial.println("reset timer"); // Reset the timeout. lastMotion = 0; // If the lights were off, start lighting up. if( lightState == LightStates::Off || lightState == LightStates::TurningOff ) { lightState = LightStates::TurningOn; } } else { if( lightState == LightStates::On ) { // Check if we reached the timeout. lastMotion += nextDelay; if( lastMotion >= LightTimeout ) { //Serial.print("Turning off, "); //Serial.println(lastMotion); lightState = LightStates::TurningOff; } } } switch( lightState ) { case LightStates::TurningOn: lightIntensity += IntensityStep; if( lightIntensity > 255 ) { lightIntensity = 255; lightState = LightStates::On; } break; case LightStates::TurningOff: lightIntensity -= IntensityStep; if( lightIntensity < 0 ) { lightIntensity = 0; lightState = LightStates::Off; } break; default: break; } analogWrite(ledPin, lightIntensity); //Serial.print("State "); //Serial.print(lightState); //Serial.print(", Light "); //Serial.print(lightIntensity); //Serial.print(", timeout "); //Serial.println(lastMotion); if( lightState == LightStates::Off || lightState == LightStates::On ) { nextDelay = SleepDelay; } else { nextDelay = Delay; } delay(nextDelay); }