Query on Arduino based timer

Greetings to forum members,

I have recently made a project which have multiple sensors performing different function.I want to call all these functions at a frequency of 1HZ.So how reliable is it use a timer interrupt to perform this task.How can I generate this 1Hz delay with timer2 as timer1 is used in servo which I am using again.Would there be any conditions of deadlock?are there any better alternative ways to this. Example I found a non blocking delay library as given in link.Are there any other best choices

using interruption has consequences if what you need to do requires interruption.

1 Hz is pretty slow, you should handle that with millis()

unsigned long chrono;

void setup() {
  ...
  chrono = millis();
}

void loop() {
  if (millis() - chrono >= 1000) {
    // do your stuff
    ...
    chrono = millis(); // or chrono += 1000; depending on how you want to manage the time it took to execute the actions
  }
}

What if millis() or timer wraps around?

that's in 50 days and by doing a subtraction in the compare, all will be fine as it's unsigned maths

Why cant i use timer 2?and call the ISR related to the timer

You can. But by default interrupts are disabled in an interrupt. So millis() won't be maintained, other ISR dependant stuff (I2C, SoftwareSerial, ...) won't work unless you take special care of it etc... In a nutshell you don't want to run the main part of your code within an interrupt context.

Got your point.one last thing can we use the non blocking delay timer Imentioned in link ?How reliable is it ?

I don't know if it's buggy or not, never used it - but this is just a wrapper to do exactly what I did with millis()... I'm not sure it brings lots of value but if you feel this makes your code looks better...

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.