简体   繁体   中英

How to enable Timer 2 on PIC18?

I want to enable timer2 to be able to use pulse width modulation. I am using PIC18F87J11 with internal 8MHz oscillator. I have minimum knowledge about PIC programming, so I want to know what else is missing in my code to enable the timer.

#define TMR2_IF          PIR1bits.TMR2IF 
#define TMR2_IE          PIE1bits.TMR2IE
#define TMR2_IP          IPR1bits.TMR2IP
#define TMR2_CON         T2CON

Let's say this is my main code for now

void main()
{
     TMR2_CON = 0b00000100 | CLOCK_DIVIDER_SETTING; // CLOCK_DIVIDER_SETTING = 4

     TMR2_IF = 0;
     TMR2_IE = 1;
     TMR2_IP = 1;

 while(1);

}

The rest of the code that I don't yet know where to place it.

if(TMR2_IF)
    {

        printf("\r\nHello");

        if(TMR2_IE)

         {
            TMR2_IF = 0;
         }

   }

Do I need an Interrupt Service Routine? If Yes, how do I add it? Remember my goal is to use the PWM which I still did not get there yet, but for now I want to make sure the settings for timer2 are correct.

What else is missing?

Thanks in advance!

change the while(1);

to

while(1)
{

if(TMR2_IF)
    {

        printf("\r\nHello");

        if(TMR2_IE)

         {
            TMR2_IF = 0;
         }

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM