
I created an Arduino universal timer function for the Purix project some years ago. I could not get a clear picture of how the various timers you find on the web will function in all different scenarios… so I made my own. Basically it is a four-state-machine, as shown in the picture above. From time to time I have put in more functional modes, and with it I can now implement all possible timing related tasks. Some of the more special features are:
- The timer accepts a Boolean input, and outputs an integer with a magnitude defined by an input to the function. This enables the function to parse timed and scaled outputs directly to Arduino PWM-pins.
- A mode control input enables 15 different ways for the timer to operate; including features for the function to produce n-times output pause/pulse. The pauses and pulses can be defined in two ways:
- two milli- or microsecond values, one for pause and one for pulse,
- one milli- or microsecond value for the total period-length and another %-value defining the duty cycle.
- The Boolean input can trigger the n-pulse feature in two modes:
- In one mode the pulses will continue as long as the input is true, and finish with N * n-pulses when the input goes to false.
- In the other mode the function will only send one series of n-pulses for an input transition from false to true.
- If the n-value is set to 0 or 1, the function will act as a monostable with a leading pause of minimum 1 milli/micro second.
Here below you can see all the inputs to the function, all the 15 different operational modes and a few application examples:
Some times it is easier to understand what a timer is doing from looking at a timing chart. The numbers in circles refers to numbers on the State Diagram above:
You can see my code hereĀ Universal Timer Code