Precise Timer1 & Input Capture Techniques for Real-time PIC

Real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. applications often require precise timing and event measurement capabilities. Timer1 is a fundamental resource on many PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. and is perfectly suited for tasks that demand accurate timing intervals, periodic interrupts, and event capture through Input Capture modules. In this tutorial, we will explore how to configure Timer1 for real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. requirements, how to use the Input Capture feature to measure external signals, and how to combine them to build robust and time-critical projects.

Introduction🔗

Many embedded systems rely on real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. processing, where specific tasks must be executed or measured at precise intervals. Examples include:

By leveraging Timer1 and Input Capture, you can build applications that accurately handle these real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. constraints.

Overview of Timer1 on PIC🔗

Timer1 is a 16-bit timer/counter commonly found in PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization.. Its key characteristics include:

1. 16-bit resolution – It can count from 0 up to 65535 (0xFFFF).

2. Flexible clock source – Timer1 can often use an internal clock (Fosc/4), external clock on a T1CKI pin, or a secondary low-power crystal for real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. clock applications.

3. Prescaler options – Multiple prescaler settings allow you to adjust the timer’s clock rateLow-Power Strategies: Maximizing PIC Battery LifeLow-Power Strategies: Maximizing PIC Battery LifeDiscover proven low-power strategies for PIC microcontrollers that maximize battery life through smart oscillator use, sleep modes, and efficient coding., achieving the right balance between resolution and timing range.

4. InterruptImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. support – When the timer overflows (from 0xFFFF to 0x0000), an interruptImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. can be generated, enabling precise periodic tasks.

5. Integration with Input Capture – Input Capture can measure the exact value of Timer1 upon detecting a rising or falling edge on the capture pin.

Below is a simplified table showing possible prescaler settings (actual values may differ depending on PIC model):

PrescalerDescription
1:1Timer1 increments on every clock cycle (depending on clock source).
1:2Timer1 increments on every 2 clock cycles.
1:4Timer1 increments on every 4 clock cycles.
1:8Timer1 increments on every 8 clock cycles.

Choosing the right prescaler is essential for your application’s timing requirements.

Configuring Timer1 for Real-Time Applications🔗

Configuring Timer1 for your real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. application involves:

1. Selecting the clock source: Decide whether Timer1 is driven by the internal instruction clock (Fosc/4) or an external clock input.

2. Adjusting the prescaler: A larger prescaler allows longer timing intervals but reduces resolution. A smaller prescaler increases resolution but shortens the maximum interval.

3. Enabling interruptsImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. (if needed): The Timer1 overflow interruptImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. can be enabled to initiate periodic tasks.

4. Loading initial values (optional): You can preload Timer1 with an initial count to control the overflow period precisely.

Below is an example C snippet for configuring Timer1 using the Microchip XC8 compilerGetting Started with MPLAB X and the XC8 CompilerGetting Started with MPLAB X and the XC8 CompilerSet up MPLAB X IDE and XC8 compiler for PIC programming with our comprehensive guide detailing installation, configuration, and debugging techniques.. This snippet assumes a generic PIC16 or PIC18 device with typical Timer1 registers:

#include <xc.h>
// Configure Timer1 for internal clock (Fosc/4), prescaler 1:8, and enable overflow interrupt
void Timer1_Init(void) {
    TMR1H = 0;              // Clear high byte
    TMR1L = 0;              // Clear low byte
    T1CONbits.TMR1CS = 0;   // Timer1 clock source = internal (Fosc/4)
    T1CONbits.T1CKPS = 0b11;// Prescaler = 1:8
    T1CONbits.TMR1ON = 1;   // Enable Timer1
    // Enable Timer1 overflow interrupt
    PIR1bits.TMR1IF = 0;    // Clear interrupt flag
    PIE1bits.TMR1IE = 1;    // Enable interrupt
}
// Timer1 interrupt service routine
void __interrupt() Timer1_ISR(void) {
    if(PIR1bits.TMR1IF) {
        // Handle Timer1 overflow event
        // Perform periodic tasks here
        PIR1bits.TMR1IF = 0;    // Clear the interrupt flag
    }
}
Tip: Configure the Global Interrupt Enable (GIE) and Peripheral Interrupt Enable (PEIE) bits in your main code to ensure this ISR is properly called.

Understanding the Input Capture Module🔗

The Input Capture module allows you to capture the current value of Timer1 during events (rising or falling edges) on a specific input pin. This feature is very useful for:

In many PIC devices, you can configure Input Capture with the following main steps:

1. Select capture sources: Assign the correct pin to the input capture module (if the device has Peripheral Pin SelectAdvanced Peripheral Pin Selections (PPS) on PIC MCUsAdvanced Peripheral Pin Selections (PPS) on PIC MCUsUnlock flexible design with advanced PPS on PIC MCUs. Our guide details how to remap pins, optimize layouts, and improve peripheral functionality. (PPS), configure it accordingly).

2. Select capture mode: Rising edge, falling edge, every 4th rising edge, etc.

3. Enable Timer1: Because Input Capture usually uses Timer1 for timestamping.

4. Read the captured value: Store it in a variable inside the capture interrupt service routineImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices..

Combining Timer1 and Input Capture for Real-Time Analysis🔗

By intelligently configuring both Timer1 and the Input Capture module, you can implement:

1. Configure Timer1 as a free-running counter.

2. Enable Input Capture on the rising edge of the external signal.

3. Read the difference in captured Timer1 values between consecutive edges to determine the signal period.

  • Pulse width measurement:

1. Use separate Input Capture channels or edges (if supported).

2. Capture the Timer1 value on a rising edge and again on a falling edge.

3. Subtract the two capture readings to find the pulse width in Timer1 ticks.

  • Event time stamping: Capture the exact Timer1 value at the moment an external event (pulse) occurs to synchronize external signals with internal processes.

Example Project: Measuring an External Signal’s Pulse Width🔗

Below is an illustrative example of using Timer1 (16-bit, prescaler = 1:8) alongside Input Capture to measure the width (high time) of a pulse. This is a generalized C example using the XC8 compilerGetting Started with MPLAB X and the XC8 CompilerGetting Started with MPLAB X and the XC8 CompilerSet up MPLAB X IDE and XC8 compiler for PIC programming with our comprehensive guide detailing installation, configuration, and debugging techniques..

#include <xc.h>
volatile unsigned int risingEdgeTime = 0;
volatile unsigned int fallingEdgeTime = 0;
volatile unsigned int pulseWidth = 0;
void Timer1_InputCapture_Init(void) {
    // Initialize Timer1
    TMR1H = 0;
    TMR1L = 0;
    T1CONbits.TMR1CS = 0;           // Internal clock (Fosc/4)
    T1CONbits.T1CKPS = 0b11;        // Prescaler 1:8
    T1CONbits.TMR1ON = 1;           // Enable Timer1
    // Configure Input Capture module
    // Exact registers differ depending on PIC model, shown here as generic bits
    // Assuming capture on rising edge for the first event:
    CCP1CONbits.CCP1M = 0b0101;     // Capture mode: Rising edge
    PIR1bits.CCP1IF = 0;           // Clear capture flag
    PIE1bits.CCP1IE = 1;           // Enable capture interrupt
    // Global Interrupts
    INTCONbits.PEIE = 1;           // Enable peripheral interrupts
    INTCONbits.GIE = 1;            // Enable global interrupts
}
// Generic interrupt for Timer1 and CCP1
void __interrupt() ISR(void) {
    // Timer1 overflow interrupt (handle if needed)
    if(PIR1bits.TMR1IF) {
        // Timer1 overflow tasks
        PIR1bits.TMR1IF = 0;
    }
    // Capture interrupt
    if(PIR1bits.CCP1IF) {
        // If we captured a rising edge, store the Timer1 value
        if(CCP1CONbits.CCP1M == 0b0101) {
            risingEdgeTime = ((unsigned int)(CCPR1H << 8)) | CCPR1L;
            // Switch capture mode to falling edge
            CCP1CONbits.CCP1M = 0b0100;  // Capture on falling edge
        }
        // If we captured a falling edge, store the Timer1 value
        else if(CCP1CONbits.CCP1M == 0b0100) {
            fallingEdgeTime = ((unsigned int)(CCPR1H << 8)) | CCPR1L;
            // Calculate pulse width
            if(fallingEdgeTime >= risingEdgeTime) {
                pulseWidth = fallingEdgeTime - risingEdgeTime;
            } else {
                // Handle Timer1 wrap-around
                pulseWidth = (65536 - risingEdgeTime) + fallingEdgeTime;
            }
            // Reset capture mode to rising edge to measure the next pulse
            CCP1CONbits.CCP1M = 0b0101;
        }
        PIR1bits.CCP1IF = 0;  // Clear capture interrupt flag
    }
}

In this example:

  • risingEdgeTime holds the Timer1 count on the rising edge of the input signal.
  • fallingEdgeTime holds the Timer1 count on the falling edge.
  • pulseWidth stores the difference in Timer1 counts between the edges.

To translate pulseWidth into real timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices., you can calculate:

Pulse Duration (s)=pulseWidth×PrescalerFosc/4 \text{Pulse Duration (s)} = \frac{\text{pulseWidth} \times \text{Prescaler}}{\text{Fosc}/4}
(Adjust for your clock frequency and prescaler settings accordingly.)

Conclusion🔗

Real-timeImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. engineering tasks often hinge on precise timing and signal measurement. By harnessing the flexibility of Timer1 to create periodic interruptsImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. or serve as a free-running counter, and combining it with the Input Capture module, you can develop applications that accurately synchronize with or measure external events. Whether you are creating a simple frequencyGenerating Audio with PIC Timers and PWMGenerating Audio with PIC Timers and PWMExplore how to configure PIC timers and PWM for audio signal generation, including hardware setup, duty cycle adjustments and simple tone creation. meter or implementing a complex control loop for real-time systems, mastering these peripherals is a powerful step toward designing reliable, responsive, and professional PIC-based solutions.

Key Takeaways:

With these foundations in place, you are equipped to build real-time projects using Timer1 and Input Capture on PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization.. This approach will help you confidently manage timing-critical tasksIntegrating Real-Time Operating Systems (RTOS) on PIC32Integrating Real-Time Operating Systems (RTOS) on PIC32Learn how to effectively integrate an RTOS into your PIC32 project to manage tasks, optimize timing, and maintain real-time, scalable performance., a hallmark of high-quality embedded system design.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles