Jump to content
  • 0

How to use TMR1 on a PIC16F1



  • 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

void __interrupt() myISR(void)
    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

  • 0
  • 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.

  • Like 1
  • Helpful 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Create New...