1.3.1 Timer1 Gate
Modules | Limit High | Resolution |
---|---|---|
Timer1 Gate | 4.1 ms | 62.5 ns |
Timer1 |
Timer1 Gate is the classical method when measuring the pulse width of a periodic and non-periodic signal. It is recommended that this method be given preference, since it is very accurate and simple to configure. The entire capture is performed in hardware that is widely available on most PIC devices.
OVERVIEW
Timer1 Gate controls when Timer1 increments based on external triggers. The trigger can either be a rising or falling edge on the Timer1 gate input.
Assuming that the pulse being measured is active-high and a rising edge has just occurred, the gate will connect the clock source to its counter (Figure 1). Timer1 will now increment as long as the pulse is kept high. When the waveform goes low, the gate will disconnect, and an interrupt flag will be set. The pulse width can now be determined by reading out the 16-bit value in the Timer1 count registers.
SETUP
- Set up Timer1 Gate for Single-Pulse mode on rising/falling edge
- Choose an appropriate Timer1 clock source and prescale for the pulse
- Clear TMR1H and TMR1L
- Enable the module and set T1GGO bit
- Wait for the pulse to occur
- TMR1GIF is set
- Read pulse width out of TMR1H:L
- Clear TMR1GIF
- Repeat steps 2-8
Timer1 Gate Pulse Setup and Operation Code (Steps 3-8)
Timer1 Setup T1GCON = 0x10; // Enable Single-Pulse Mode (Step 1) T1CLK = 0x2; // Timer1 Clock is Fosc with 1:1 prescale (Step 2) Operation Code TMR1H = TMR1L = 0; // Clear TMR1H and TMR1H (Step 3) Timer1_StartSinglePulseAcquisition(); // (Step 4) while(!TMR1GIF); // Wait for TMR1GIF to set (Step 5 and Step 6) uint8_t pulse_width_low = TMR1L; // Save pulse low byte data (Step 7) uint16_t pulse_width_high = TMR1H; // Save pulse high byte data (Step 7) TMR1GIF = 0; // Clear Gate Flag (Step 8)
FOSC should be selected as the Timer1 clock source with a 1:1 prescale value for the best resolution.
For 16 MHz clock source, the uncertainty can be as much as +/- 62.5 ns.
LIMITATIONS
There is an uncertainty of plus or minus one clock period. The worst case will be when the pulse goes low just before the rising edge of the clock, or when the pulse goes high just after the clock. Timer1 has a maximum count of 65535. On the 65536th period the timer count overflows to 0. You can accommodate pulses longer than 65535 Timer1 periods by counting the number of Timer1 overflows. The TMR1IF bit is set at each overflow event. Count the number of overflow events and add 65536 times that number to the Timer1 count.