7 Using TMR1 Gate to Measure Short vs. Long Button Press
This example describes how to initialize and use the TMR1 in Gate Single-Pulse mode. The timer will start counting on an falling edge. If the leading edge appears, a gate interrupt will be generated, denoting that the button was short pressed. If the timer overflows before the leading edge appears, an overflow interrupt will be generated, denoting that the button was long pressed. A GPIO pin will be configured as input and connected to a button.
In this example, the microcontroller was configured with a clock system of 1 MHz and the timer was configured with a clock source frequency of 31,250 MHz = 32 µs and is able to measure the following range of values:
- The smallest pressed time: This is based on the clock frequency of the timer, resulting in a minimum time of 1 / 31,250 Hz = 32 µs.
- The biggest pressed time: This is based on the maximum value the timer can count. It is a 16-bit timer so it can count up to 65,535. Thus, resulting in a minimum time of 32 µs * 65,535 ~ = 2.1 s. A longer press will result in a timer overflow.
- System clock initialization
- Port initialization
- Timer1 initialization
- Interrupts initialization
- Timer1 interrupt handling
- Timer1 gate interrupt handling