Jump to content
 
  • 0

How to use TMR1 on a PIC16F1


Orunmila

Question

  • Member

Saw this question today on the MCHP forum so I thought I would post a short example.

My first advice to anybody who has this kind of problem is to generate the code with MCC and study what it is doing in terms of order of initialization and also what it is setting in the configuration bits for the device. Even if you are planning on using ASM, do that first with your settings so you can have a working example to start with!

Here is a minimal example on the PIC16F18344 for TMR1

 

#pragma config WDTE = OFF       // Watchdog Timer Enable bits (WDT disabled; SWDTEN is ignored)

#include <xc.h>

void main(void) {
    INTCONbits.PEIE = 1;  // Enable peripheral interrupts

    TMR1IE = 1;   // Enable TMR1 peripheral interrupt
    
    T1CON = 0x01; // Set the timer to prescaler 1:1 (fastest), clock source instruction clock
                  //    and pick timer2 clock in as source (not Secondary Oscillator)
                  //    we also select synchronization, no effect as we run of FOSC here.
    
    TMR1H = 0x00;
    TMR1L = 0x00;
    
    INTCONbits.GIE = 1;  // Enable GIE last, or interrupts can happen while we are setting up!
   
    while(1); // Wait forever for interrupts
    
    return;
}

void __interrupt() myISR(void)
{
    NOP();
    TMR1IF = 0;  // Remember to clear the IF here or we will just end up in the ISR all of the time!
}

 

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • Member

Remember, this timer counts up.and you get the interrupt when it rolls over.  To interrupt at a precise interval, you must compute the number of "counts" required for that interval and then subtract from 65535 to determine the timer load value.

 

void setTimer(unsigned int intervalCounts)
{
	TMR1ON = 0;
	TMR1 = 65535 - intervalCounts;
	TMR1ON = 1;
}

By turning the timer off and then setting the counts and restoring the timer, you can be sure that you will not get unexpected behavior if the timer value is written in an unexpected order.  I will cover this topic in the next blog post on timers.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

 


×
×
  • Create New...