Michael Dornisch
Michael Dornisch

Reputation: 187

Start a timer with a function in arduino

I have a project to control my projector via RS-232 commands, and the projector sends feedback to the arduino. Therefore I have a LCD screen with buttons. To make it nicer, I have an ultrasonic rangefinder that I want to use so that when you approach the device, the LCD backlight turns on for 30 seconds, then turns back off. I can't use a delay because I need to continue polling for buttons and serial information from the projector.

There are community libraries like Timer.h and SimpleTimer.h, but these only do oscillations, etc.

What I would like to do is this:

distance = measureUltrasonicDistance(ultrasonicPin); //returns in cm
if (distance <= 10) {
    //digitalWrite(baclkightPin,HIGH);
    //have this turn off 30 seconds later
}

Upvotes: 0

Views: 1162

Answers (2)

Udo Klein
Udo Klein

Reputation: 6882

This seems like a typical application for the event fuse library.

Upvotes: 1

JackCColeman
JackCColeman

Reputation: 3807

First thing to realize is that loop() is continuously invoked, and that you can use a "watchdog" pattern to keep the light on without using a timer.

unsigned long timeoff;

void setup() {

   timeoff = millis();

}

void loop() {

   distance = measureUltrasonicDistance(ultrasonicPin); //returns in cm
   if (distance <= 10) {
       digitalWrite(baclkightPin,HIGH);

       // compute boundary of when light should be off
       timeoff = millis() + 30L*1000L;   
   }

   if (timeoff < millis()) {

      digitalWrite(backlightPin, LOW);

   }

}

Hope this helps, let me know if there are any problems.

Upvotes: 1

Related Questions