blinking a LED with the timer interrupt, PIC 16F

Blinking a LED on a PIC 16F microcontroller using C language.
You should use latest MPLABX, and XC8.

Create a new project using MPLABX templates- it generates all necessary files for you. Then modify interrupts.c


/******************************************************************************/
/*Files to Include                                                            */
/******************************************************************************/
#if defined(__XC)
    #include          /* XC8 General Include File */
#elif defined(HI_TECH_C)
    #include         /* HiTech General Include File */
#endif
#include          /* For uint8_t definition */
#include         /* For true/false definition */
extern unsigned char v_sys_flags;
/******************************************************************************/
/* Interrupt Routines                                                         */
/******************************************************************************/
/* Baseline devices don’t have interrupts. Note that some PIC16’s
 * are baseline devices.  Unfortunately the baseline detection macro is
 * _PIC12 */
#ifndef _PIC12
void interrupt isr(void)
{
    /* This code stub shows general interrupt handling.  Note that these
    conditional statements are not handled within 3 seperate if blocks.
    Do not use a seperate if block for each interrupt flag to avoid run
    time errors. */
    if(TMR0IF)
    {
	TMR0IF=0;
	v_sys_flags|=1;
    }
}
#endif
<

br>
Don’t spend too much time inside the interrupt, so, set a flag and leave it immediately.

The main.c file, toggling a port bit with a LED. The sysclock here is 8 MHz internal OSC, and the prescaler is set to 100 (binary).

There is also a software extension so indeed you get a 16bit timer! Simply for the reason the LED should blink slowly.


/******************************************************************************/
/* Main Program                                                               */
/******************************************************************************/
void main(void)
{
    /* Configure the oscillator for the device */
//    ConfigureOscillator();
    /* Initialize I/O and Peripherals for application */
//    InitApp();
//    configure_tris();
    /* Enable interrupts */
    TMR0IE=1; // timer int on
    GIE=1; // interrupts on
    OPTION_REG=0x04; // prescaler bits = 100
    TRISB=0b10111111; // LED IO bit set to output
    ANSEL=0; // AD set to off
    ANSELH=0;
    v_sys_flags=0;
    v_led_ctr=0;
    while(1)
    {
	if(v_sys_flags&1)
	{
	    v_sys_flags&=0xfe;
	    v_led_ctr++;if(v_led_ctr==0x50)
	    {
		v_led_ctr=0;
		if(v_sys_flags&0x2)
		{
		    v_sys_flags&=0xfd;
		    PORTBbits.RB6=1;
		}else
		{
		    v_sys_flags|=0x02;
		    PORTBbits.RB6=0;
		}
	    }
	}
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*