Working with Timers


Measuring Events Duration and Time Between Events

This lesson is a continuation of the previous lesson – Counting events . In that lesson we saw how we can the occurrence of events by capturing the  edges of an input pin. We said the microcontroller can detect the occurrence of an event due to the signal changes that happens at the input pin of microcontroller.

To find the duration of an event, all we have to save  the timestamp of the rising-edge capture in  one variable and save the timestamp of falling-edge capture in another variable, and then subtract the timestamp of the rising-edge from the time stamp of the falling-edge.

Finally, to convert  the results to our desired time units, we have to multiply it by an appropriate value based on the running frequency of our CPU.


In our Timer configuration we have select capture both-edges in order to be able to perform this task.

Following the same principle, to measure the time between two events, we have save the timestamp of  the rising-edge capture of event1 i.e input1 and then the timestamp of the rising-edge capture of event2, find the difference between the two timestamps then convert the difference to the appropriate time unit.

See the example code in the link below. In this example we took the timestamp of when  the input pin got HIGH and then the timestamp of when it got back to LOW,converted the difference to an appropriate time unit for our application and finally converted the value to centimeters.  This is a use case example showing how to calculate the distance of an obstacle in front of an ultrasonic sensor.

London, U.K