5 Using TMR1 Gate to Measure Frequency

This example describes how to initialize and use the TMR1 in Gate-Single Pulse and Toggle combined mode. The timer will start counting on an incrementing edge, will measure a full-cycle length of a gate signal and will stop when a new incrementing edge appears. An interrupt will be generated when the measurement is completed. A GPIO pin will be configured as input and the periodical signal will be applied on this pin.

In this example, the microcontroller was configured with a clock system of 32 MHz and the timer was configured with a clock source frequency of 1 MHz and is able to measure the following range of values:

  • The smallest frequency value: This is based on the number of values that the timer can count. It is a 16-bit timer so it can count up to 65,535, resulting in a frequency of approximately 15.26 Hz.
  • The biggest frequency value: This is based on the Nyquist frequency theorem. The sampling frequency must be at least two times bigger than the one of the measured signal to obtain a more accurate result. This results in a frequency of approximately 500 kHz.
Note: It is recommended to increase the clock source frequency of the timer to measure frequencies closer or bigger than the Nyquist value from the above example.
To achieve the functionality described by this use case, the following actions will have to be performed:
  • System clock initialization
  • Port initialization
  • Timer1 initialization
  • Interrupts initialization
  • Timer1 gate interrupt handling