Skip to content

Technik Blog

Programmieren | Arduino | ESP32 | MicroPython | Python | Raspberry Pi | Raspberry Pi Pico

Menu
  • About me
  • Contact
  • Deutsch
  • English
Menu

Interval execution made easy: Timer for Arduino

Posted on 9. August 20233. August 2023 by Stefan Draeger

This post is all about efficient timer programming for Arduino. Timer controlled functions play an important role in many Arduino projects, be it for precise timing or recurring tasks. I’ll show you how to use the external “timer” library to elegantly overcome these challenges. Discover an improved solution compared to traditional approaches and learn how to enrich your Arduino projects with the right time intervals. For additional support, you’ll also find a step-by-step tutorial video to help you get started.

In the German contribution Arduino: Ein Sketch ohne delay(ms) schreiben I had already shown you a solution how you can execute a program section without the function call “delay”. Here I would like to pick up these ideas and show you another solution.

Arduino Programmierung - Timer Bibliothek für asynchrones Blinken zweier LEDs
Watch this video on YouTube.

Table of Contents

  • Taking a break with board resources
    • delay
    • millis()
    • Modulo
  • Lean with the timer library from Arduino
  • Download
  • Conclusion

Taking a break with board resources

First I would like to show you again how you can insert a small break in your program with the board means of the Arduino IDE and/or the language.

delay

Probably the simplest form is the call of the function delay. Here the entire microcontroller takes a pause. When the pause has expired, the program continues to be executed. However, no further action can be executed during this pause.

void setup() {
  //start serial communication from 9600 baud
  Serial.begin(9600);
}

void loop() {
  //output the milliseconds that have passed so far
  Serial.println(millis());
  //insert a pause of 500 milliseconds
  delay(500);
}

If we run this little program once, we see that the pause is usually a bit longer than the targeted 500 milliseconds.

Inserting a pause in the program with the delay function
Inserting a pause in the program with the delay function

millis()

Another possibility is to take the past milliseconds (function millis()) and use them for a small calculation. Here it is checked whether the past milliseconds + a pause continuously, whether this is smaller than the current milliseconds. If so, then the function is to be executed.

//Constant with the integer value of the pause
const int PAUSE = 500;
//Field to store the timestamp of the last execution
long lastAction = 0;

void setup() {
  //start serial communication from 9600 baud
  Serial.begin(9600);
}

void loop() {
  //If the time of the last execution + the pause
  //is smaller than the current return value of the function
  //millis(), then...
  if ((lastAction + PAUSE) < millis()) {
    //save the current value of the function millis()
    lastAction = millis();
    //output the milliseconds that have passed so far
    Serial.println(millis());
  }
}

The values in the serial monitor are now much more accurate than with the function call of delay:

Output text with the calculation of milliseconds
Output text with the calculation of milliseconds

Modulo

I found a third approach on the page https://starthardware.org/timer-mit-arduino-alternative-zu-delays/. There a third equally very interesting approach is shown, namely with the calculation with modulo.

Modulo is a mathematical operation similar to addition or multiplication. This operation plays a significant role in various encryption procedures as well as key exchange procedures. The result of modulo, often abbreviated as “mod”, denotes the remainder of an integer division.

//Constant with the integer value of the pause
const int PAUSE = 500;

void setup() {
  //start serial communication from 9600 baud
  Serial.begin(9600);
}

void loop() {
  //divide the current value of the past milliseconds, since which
  //the microcontroller started by 1000 and take from that
  //take the integer remainder
  long calcMod = millis() % 1000;
  //If this value is greater than the desired pause, then....
  if (calcMod > PAUSE) {
    //output the milliseconds that have passed so far
    Serial.print(millis());
    //output the calculated value
    Serial.print(" [");
    Serial.print(calcMod);
    Serial.println("]");
  }
}

If we look closely at the output, whenever the remainder is greater than 500, the output is executed on the serial port.

Output with the calculation via modulo
Output with the calculation via modulo

So we have a pause of 500 milliseconds, this is sufficient for LEDs etc., but if we run a serial output like here, then we get too many values.

Lean with the timer library from Arduino

But it is also possible to do it more slim and precise, here the timer library of Arduino is used. You can download it in version 3.0.0 from https://www.arduino.cc/reference/en/libraries/arduino-timer/ as a ZIP file.

How to integrate a library as a ZIP file into the Arduino IDE, I have already explained in detail in the german article Arduino IDE, Einbinden einer Bibliothek.

//Arduino Timer Library
#include <arduino-timer.h>

//Timer object initialize
Timer timer = timer_create_default();

//Function to output the milliseconds
//Parameter is undefined
bool printMillis(void *){
  Serial.println(millis());
  //Returns true if the timer is to be continued,
  //otherwise false.
  return true;
}

void setup() {
  //start serial communication with 9600 baud
  Serial.begin(9600);
  //configure the timer,
  //the function "printMillis" should be executed every 500 milliseconds
  //be executed.
  timer.every(500, printMillis);
}

void loop() {
  //Makes the timer run forward
  timer.tick();
}

If we now look at the output, we see that the pause here is exactly 500 milliseconds.

Output to serial port using Time library from Arduino
Output to serial port using Time library from Arduino

So if you need an explicit pause, I would recommend you to use the Time library.

Download

Here you can find all of these examples as zip-file:

Examples for Arduino TimerHerunterladen

Conclusion

In conclusion, there are significant advantages to using the “Timer” library for Arduino. The precise interval of execution allows for more accurate timing while maintaining code efficiency. With this streamlined solution, we can say goodbye to the traditional approaches, such as using delay, and take our projects to a new level. Discover the fascination of Arduino timer programming and experience the accuracy your projects deserve.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Fragen oder Feedback?

Du hast eine Idee, brauchst Hilfe oder möchtest Feedback loswerden?
Support-Ticket erstellen

Newsletter abonnieren

Bleib auf dem Laufenden: Erhalte regelmäßig Updates zu neuen Projekten, Tutorials und Tipps rund um Arduino, ESP32 und mehr – direkt in dein Postfach.

Jetzt Newsletter abonnieren

Unterstütze meinen Blog

Wenn dir meine Inhalte gefallen, freue ich mich über deine Unterstützung auf Tipeee.
So hilfst du mit, den Blog am Leben zu halten und neue Beiträge zu ermöglichen.

draeger-it.blog auf Tipeee unterstützen

Vielen Dank für deinen Support!
– Stefan Draeger

Categories

Links

Blogverzeichnis Bloggerei.de TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste Blogverzeichnis trusted-blogs.com

Stefan Draeger
Königsberger Str. 13
38364 Schöningen

Tel.: 01778501273
E-Mail: info@draeger-it.blog

Folge mir auf

  • Impressum
  • Datenschutzerklärung
  • Disclaimer
  • Cookie-Richtlinie (EU)
©2025 Technik Blog | Built using WordPress and Responsive Blogily theme by Superb
Cookie-Zustimmung verwalten
Wir verwenden Cookies, um unsere Website und unseren Service zu optimieren.
Funktional Always active
Die technische Speicherung oder der Zugang ist unbedingt erforderlich für den rechtmäßigen Zweck, die Nutzung eines bestimmten Dienstes zu ermöglichen, der vom Teilnehmer oder Nutzer ausdrücklich gewünscht wird, oder für den alleinigen Zweck, die Übertragung einer Nachricht über ein elektronisches Kommunikationsnetz durchzuführen.
Vorlieben
Die technische Speicherung oder der Zugriff ist für den rechtmäßigen Zweck der Speicherung von Präferenzen erforderlich, die nicht vom Abonnenten oder Benutzer angefordert wurden.
Statistiken
Die technische Speicherung oder der Zugriff, der ausschließlich zu statistischen Zwecken erfolgt. Die technische Speicherung oder der Zugriff, der ausschließlich zu anonymen statistischen Zwecken verwendet wird. Ohne eine Vorladung, die freiwillige Zustimmung deines Internetdienstanbieters oder zusätzliche Aufzeichnungen von Dritten können die zu diesem Zweck gespeicherten oder abgerufenen Informationen allein in der Regel nicht dazu verwendet werden, dich zu identifizieren.
Marketing
Die technische Speicherung oder der Zugriff ist erforderlich, um Nutzerprofile zu erstellen, um Werbung zu versenden oder um den Nutzer auf einer Website oder über mehrere Websites hinweg zu ähnlichen Marketingzwecken zu verfolgen.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Einstellungen anzeigen
{title} {title} {title}