How to avoid delay() – create a custom Arduino class – Part 2

In the previous blog post we learned how to avoid delay() if necessary. It would be very convenient when we are able to add a layer of abstraction to this code so when can easily reuse it if we need it.

Before we can begin creating a custom Arduino class, we need to create these files:

  • SCAsyncTimer.cpp ( = the implementation, this is where the most of the code goes)
  • SCAsyncTimer.h ( = the header, this is some kind of a “table of contents” for our class)
  • keywords.txt ( = optional the keywords, here we can specify the keywords which then get colored in the IDE)

Create these files either in your sketch directory (so its only available in this sketch – restart the IDE so the compiler recognizes it) or follow this documentation how to install custom classes/libraries: Libraries

Please note that if the class goes into the global Arduino libraries folder (so its accessible for all sketches) needs to be named exactly as the class itself. In our case SCAsyncTimer.

 

The Header – SCAsyncTimer.h

Below you can find the Arduino SCAsyncTimer header-file:

 

The Implementation – SCAsyncTimer.cpp

Here is the implementation of the class itself:

 

The Keywords – keywords.txt

The basic keywords file looks like this:

 

Usage

Then we can just use the class like this:

The cool thing is that is does some math for use if we do not want to calculate with milliseconds all the time. There is an enum (TimeUnit) that takes care of the calculations to minutes, seconds, hours etc.

You can download the full class here: SCAsyncTimer

Have fun!

15. November 2016 by Marius
Categories: Arduino, Programming, Tutorials | Tags: , , , | 1 comment