timer programming

Hello everyone,

I am facing a problem with a program of controlling lights. My project is to use IR sensor with arduino for controlling lights that means whenever the IR sensor triggered the lights switched on for 10 seconds as an example. The problem is while the lights switched on and the IR sensor get triggered, I need the time become more 10 seconds plus the remaining time from the previous trigger.

Here is my code without any incresing. :frowning:

const int ProxSensor=2;
int x;
void setup() {                
  pinMode(3, OUTPUT);     
void loop() {
    digitalWrite(3, HIGH);
    digitalWrite(3, LOW);    

sincerely. :slight_smile:

Your problem is in the use of delay. That's a blocking function. The code is stuck at the delay line until the delay is finished. So it cannot respond to anything during that time. You've made the board blind, deaf, and dumb during that delay.

See the Blink Without Delay example sketch and any of the many many great tutorials all over the web about it for some inspiration on how to handle timing without using delay so that you can still respond to inputs during the 10 seconds.

Here's on such tutorial: https://www.gammon.com.au/blink


Use StateChangeDetection example so you only act on the sensor once each time it activates.
Use a timer to filter out button contact bounce.
Use the BlinkWithoutDelay example to schedule something to happen in the future.

const byte ProxSensorPin = 2;
const byte OutputLEDPin = 3;
const unsigned long IntervalIncrease = 10000UL;

unsigned long Interval = 0;  // How many milliseconds the LED should stay on
unsigned long LEDStartTime = 0;  // The time that the LED first turned on

void setup() {
  pinMode(OutputLEDPin, OUTPUT);
  pinMode(ProxSensorPin, INPUT);

void loop() {
  static boolean prevProx = HIGH;  // Looking for state changes
  boolean prox = digitalRead(ProxSensorPin);
  static unsigned long proxChangeTime = 0;

  if (prox != prevProx && millis() - proxChangeTime > 100) {
    proxChangeTime = millis();
    // State changed (protected from contact bounce)
    if (prox == LOW) {  // Input just went LOW
      if (Interval == 0) {  // timer isn't already running
        LEDStartTime = millis();  // Start the timer
        digitalWrite(OutputLEDPin, HIGH);  // Turn on the LED
      Interval += IntervalIncrease;  // Add ten seconds to the interval

  if (Interval != 0 && millis() - LEDStartTime >= Interval) {
    // Time's Up
    Interval = 0;  // Stop the timer
    digitalWrite(OutputLEDPin, LOW);  // and turn out the light