RSS Daily tech news
  • Quantum crystals could spark the next tech revolution
    Auburn scientists have designed new materials that manipulate free electrons to unlock groundbreaking applications. These “Surface Immobilized Electrides” could power future quantum computers or transform chemical manufacturing. Stable, tunable, and scalable, they represent a leap beyond traditional electrides. The work bridges theory and potential real-world use.
  • Decades-old photosynthesis mystery finally solved
    Scientists from the Indian Institute of Science (IISc) and Caltech have finally solved a decades-old mystery about how photosynthesis really begins. They discovered why energy inside plants flows down only one of two possible routes — a design that lets nature move sunlight with astonishing precision. Using advanced computer simulations, the researchers showed that one […]
  • A century-old piano mystery has just been solved
    Scientists confirmed that pianists can alter timbre through touch, using advanced sensors to capture micro-movements that shape sound perception. The discovery bridges art and science, promising applications in music education, neuroscience, and beyond.
  • Princeton’s AI reveals what fusion sensors can’t see
    A powerful new AI tool called Diag2Diag is revolutionizing fusion research by filling in missing plasma data with synthetic yet highly detailed information. Developed by Princeton scientists and international collaborators, this system uses sensor input to predict readings other diagnostics can’t capture, especially in the crucial plasma edge region where stability determines performance. By reducing […]
  • Heisenberg said it was impossible. Scientists just proved otherwise
    Researchers have reimagined Heisenberg’s uncertainty principle, engineering a trade-off that allows precise measurement of both position and momentum. Using quantum computing tools like grid states and trapped ions, they demonstrated sensing precision beyond classical limits. Such advances could revolutionize navigation, medicine, and physics, while underscoring the global collaboration driving quantum research.
  • This new camera sees the invisible in 3D without lenses
    Scientists have developed a lens-free mid-infrared camera using a modern twist on pinhole imaging. The system uses nonlinear crystals to convert infrared light into visible, allowing standard sensors to capture sharp, wide-range images without distortion. It can also create precise 3D reconstructions even in extremely low light. Though still experimental, the technology promises affordable, portable […]

PIC16F877A Timer2 tutorial

by Florius
Educational slide introducing Timer2 of the PIC16F877A microcontroller. It includes a stopwatch icon with the phrase “Alarm, Timers, how does it work?” on the left, and an image of the PIC microcontroller with MPLAB X IDE branding on the right. The tutorial focuses on Timer2's use in generating precise delays and pulse-width modulation (PWM).

The Timer2 module is an 8-bit timer/counter within most PIC MCU devices. Timer2 can increment up to a value of 255 before it overflows back to zero. Timer2 has other built-in features that make it very useful for many different applications, such as the following:

  • 8-bit Timer and Period registers (TMR2 and PR2)
  • Readable and writable (both registers)
  • Software programmable prescaler (1:1, 1:4, 1:16, and 1:64)
  • Software programmable postscaler (1:1 to 1:16)
  • Interrupt on TMR2 match with PR2
  • Optional use as the shift clock for the MSSP module

In one aspect, Timer2 module is different from the other two timers, as they required you to calculate a start value and store it in TMR0 or TMR1H & TMR1L for Timer0 and Timer1 respectively. For Timer2 you need to calculate the end value, which is set in the Period Register (PR2).

On the other hand, it still resembles the other two timers, as a clock pulse with a prescaler is used to create a timer. This incrementing value (the counter) is stored in TMR2 register. Its value is compared with the Period Register (PR2) on every clock cycle. When the two values match, the comparator generates a match signal as the timer output for other peripherals to use as a time base. That match signal can also feed a postscaler to delay the number of matches required to initiate a Timer2 interrupt. For example, if the interrupt without a postscaler normally happens every 1 ms, then with the postscaler set to 1:4, the interrupt will happen every 4 ms.

The microcontroller series also have other timers, which can be used differently and separately from Timer2. I refer to the overview of Timers, Timer0 and Timer1 for their respective information.

Fig 1. block diagram of the timer 2 module in the PIC16F877A

1. Timer Mode

To make the Timer2 module work, we first need to look at the 3 important registers to enable the timer and configure it correctly:

RegistersDescription
T2CONThis register is used to configure Timer 2’s prescaler and postscaler
TMR2This register holds the counter for timer 2.
PR2This register holds the max value of timer 2
Diagram of the T2CON register from the PIC16F877A microcontroller. It shows bit fields for configuring Timer2, including TMR2ON (Timer2 enable), T2CKPS (prescaler select), and TOUTPS (postscaler select). These settings control how Timer2 operates, especially in PWM and timing applications.

TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits
0000 = 1:1 postscale
0001 = 1:2 postscale
0010 = 1:3 postscale



1111 = 1:16 postscale

TMR2ON: Timer2 On bit
1=Timer2 is on
0=Timer2 is off

T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16

In this Register, you will be able to set the Postscaler and Prescaler. Do not that there is not much option for the prescaler, as it can only go to a max of 1:16. Do not forget to turn on the Timer2 module with the TMR2ON = 1 bit.

1.1 TMR2 & PR2 Registers

As explained before, Timer2 requires you to set an end value and store it in the Period Register (PR2). The TMR2 register will start from 0 and starts counting till it matches with the PR2 register, which has a maximum value of 255. At this point, TMR2 register will overflow and repeats the process from 0. In a similar fashion, PR2 can be calculated.

2. Timer Interrupt

To enable the interrupt, we need to enable the global and peripheral interrupts in the INTCON register. This is done by setting both GIE = 1 and PEIE = 1.

Diagram of the INTCON register from the PIC16F877A microcontroller, showing updated bit fields for managing interrupts. Includes global (GIE), peripheral (PEIE), timer (T0IE, T0IF), and external interrupt controls (INTE, INTF), providing fine-grained control over interrupt behavior in embedded applications.

Lastly, the TMR2 overflow flag enabler is situated in the PIE1 register and needs to be set to TMR2IE = 1; The TMR2 overflow flag itself is situated in the PIR1 register, and has to be cleared every time an interrupt happened. This can be done by setting TMR2IF = 0;

3. Programming code in MPLAB

Assume we have a PIC16F877A microcontroller with a 20 MHz crystal oscillator. We want to create a timer of 10 ms (10×10-3 s), using timer 2.

We will use a prescaler of 16 and a postscaler of 16; this will give us an multiplication of 16×16 = 256. A single instruction will take 0.2×10-6 s, hence a single instruction with a multiplication of 256 will take 51.2 ×10-6 s.

We need to count 195 instructions (195 × 51.2 ×10-6 s = 9.984×10-3 s), which is close to 10 ms. For this example, the PR2 register is set to 195, which is 0xC3 in hexadecimal.

				
					#include <pic16f877a.h>
#include <xc.h>
    
#define XTAL_FREQ 20000000  // 20MHz external crystal oscillator frequency

// Configuration bits 
#pragma config FOSC = HS    // High-Speed Crystal oscillator
#pragma config WDTE = OFF   // Watchdog Timer disabled
#pragma config PWRTE = OFF  // Power-up Timer disabled
#pragma config BOREN = OFF  // Brown-out Reset disabled
#pragma config LVP = OFF    // Low-Voltage Programming disabled
#pragma config CPD = OFF    // Data memory code protection off
#pragma config WRT = OFF    // Flash Program Memory Write protection off
#pragma config CP = OFF     // Flash Program Memory Code protection off

void main()
{
    TRISD = 0x00; // Configure PORTD as output to control LED

    // Timer1 - T1CON Register Configuration
    T2CON = 0b01111110; // Timer2 enabled, 1:16 prescaler, 1:16 postscale

    // TimerCounter register
    PR2 = 0xC3; // Set period register for Timer2

    //INTCON Register & PIE1 Register configuration
    TMR2IE = 1; // Enable Timer2 interrupt
    GIE = 1;    // Enable Global Interrupt
    PEIE=1;     //Enable the Peripheral Interrupt

    while (1)
    {
        // No need to toggle PORTD here; the ISR will handle the blinking
    }
}

// Timer2 interrupt service routine
void interrupt timer_isr()
{
    if (TMR2IF == 1)
    {
        RD0 = !RD0; // Toggle RD0 (LED) state
        TMR2IF = 0; // Clear Timer2 interrupt flag
    }
}
				
			
Florius

Hi, welcome to my website. I am writing about my previous studies, work & research related topics and other interests. I hope you enjoy reading it and that you learned something new.

More Posts

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.