One-Shot timer with UNO

Hello all,
I’m having trouble coding using TimerOne. Is there an easier way to step out of my loop without altering the timing to execute a One-Shot style timer?

Here is the concept:

Run a routine in the main loop to read a sensor. when an external button is pressed it turns on an LED for 4 seconds, then turns off. It seems simple but Im having issues. Any help would be appreciated.

Not My Code below, Im altering it to work for my purposes

#include <TimerOne.h>
 
void setup() 
{
  // Initialize the digital pin as an output.
  // Pin 13 has an LED connected on most Arduino boards
  pinMode(13, OUTPUT);    
  
  Timer1.initialize(100000); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
}
 
void loop()
{
  // Main code loop
  // TODO: Put your regular (non-ISR) logic here
}
 
/// --------------------------
/// Custom ISR Timer Routine
/// --------------------------
void timerIsr()
{
    // Toggle LED
    digitalWrite( 13, digitalRead( 13 ) ^ 1 );
}

the code attached has functions such as Timer1.stop, Timer1.start… but not all work, I tried different versions of the TimerOne library with the same problem.

There may be an easier way to accomplish and the accuracy needed is low so that is not an issue. I have attached the library for reference.

Thanks,

TimerOne-r11.zip (26 KB)

Hi Frank,

Explain a bit more clearly what you want to do. What is this sensor and how does it affect the sketch? What's the relationship, if any, between the sensor and the button?

If you simply want to read a sensor on a regular basis, meanwhile checking for a button press and lighting a led for 4 secs, I don't think you need any fancy libraries. Just use millis()!

Paul

I agree. (I've never used the timer interrupt.)

Just check the time every time through the loop to see if 4 seconds has passed. (See the Blink Without Delay Example.)

I've got some projects where I have a handful of multiple-simultaneous timers running (from milliseconds to several seconds) and they are all simply checking their start-times and intervals to the current time.

Hey guys, thanks for the quick response.

So what I'm doing is checking a sensor, and displaying the data via Serial (later LED display) every second using the delay function.

Meanwhile if a user presses a button it will bring high an LED for 4 seconds, while not interrupting the loop delay.

Does that make sense? FYI there is more complexity, but this is the basic concept.

I thought so!

Loose the delay(), time reading your sensor using millis() and you can check for button presses at the same time. No need for interrupts.

Fantastic, worked great. Learn something new everyday!!

PaulRB:
I thought so!

Loose the delay(), time reading your sensor using millis() and you can check for button presses at the same time. No need for interrupts.