Use Arduino timers like PLC timers

Using a On-delay timer in a PLC is straight forward, and with this clever function is easy on an Arduino too.

On delay timer in a PLC

A typical On-delay timer of a PLC (often referred as “TON” timer) has one input (“in”, or “en”), one output (“q”, or “out”), and a preset timing value (“pt”). When the input goes high, the timer count the time up to the preset timing value, and once reached it activates the output bit (q). If we want, we can read the value of the timer (ep), which tells how much time has elapsed since when it started counting. When the input goes low, the output goes low and the elapsed time (ep) is set to zero again. Timing diagram:

On delay timer in arduino

On the arduino the same can be achieved defining a data type structure called “timer” that contains two bits (in, q), the preset (pt) and the counting value (et) which keeps track of time.

Once we have the “timer” data type created, we must create the timers, which we call “t[i]”, where i is the number of the timer. MAXT is the total number of timers we use in the program (or more). To access the input enable of timer 3 for example, we write t[3].in. The output of the timer is t[3].q. Don’t forget to tell the timer how much time is the preset, in hundreds of seconds t[3].pt=500 (5 seconds). The preset timing (pt) must be specified in hundreds of seconds, either in the “setup” or in the “loop”.

The only difference with the PLC, is that on the arduino it is more practical to “count down” rather than “up”. The On-delay has elapsed when “et” is equal to zero.

This program will turn on a led (pin D13 on arduino nano) after 1 s from the button press. Two second after, a second led (pin D2) will go on.

The smart thing of this program (inspired by this and this), is that we can create new timers simply calling them t[whatever], and set the delay time with t[whatever].pt , and access the bits with .in and .q. The smart thing is that we have one single function that manage all the timers we have in our program with a “for” loop, taking cares of increments and bits.


Leave a Reply

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