Saturday, January 29, 2011

PIC16F877A Interrupt Code

During my attempt to program my tachometer, I decided to make things simpler by creating code for an external interrupt, timer 0 interrupt (TMR0), and timer 1 (TMR1) interrupt.  I figured this might be useful to someone in the future, so here it is!

NOTE: I program my code using Sourceboost C complier.

External Interrupt Code on the PIC16F877A
//External Interrupt Test,  
//RoboSlave.Blogspot.com, 1/2011
//Includes
#include <system.h>
//PIC16F877A
#pragma DATA _CONFIG, _PWRTE_OFF & _BODEN_OFF & _WDT_OFF & _LVP_ON & _CPD_OFF & _DEBUG_OFF & _XT_OSC & _CP_OFF
#pragma CLOCK_FREQ 4000000 //Set clock frequency
//Define
#define button1 portb.0
#define led1 portd.0
//Interrupts
void interrupt( void )
{
if( intcon & (1<<INTF) ) //Handle external interrupt
{
clear_bit( intcon, INTF );
led1 = !led1;
}
}
//Main Code
void main( void )
{
trisb = 0x00; //Configure port B
trisd = 0x00; //Configure port D
portb = 0x00; //Initialize port B
portd = 0x00; //Initialize port D
intcon = 0xB0; //Enable interrupts (External, Timer0)
while( 1 ) //Endless loop
{}
}

 Timer0 Interrupt Code on the PIC16F877A
//Timer0 Interrupt Test 
//RoboSlave.Blogspot.com, 1/2011
//Includes
#include <system.h>
//PIC16F877A
#pragma DATA _CONFIG, _PWRTE_OFF & _BODEN_OFF & _WDT_OFF & _LVP_ON & _CPD_OFF & _DEBUG_OFF & _XT_OSC & _CP_OFF
#pragma CLOCK_FREQ 4000000 //Set clock frequency
//Define
#define led1 portd.0
//Interrupts
void interrupt( void )
{
if( intcon & (1<<T0IF) ) //Handle timer0 interrupt
{
clear_bit( intcon, T0IF ); //clear timer 0 interrupt bit
led1 = !led1;
}
}
//Main Code
void main( void )
{
trisd = 0x00; //Configure port D
portd = 0x00; //Initialize port D
intcon = 0xB0; //Enable interrupts (External, Timer0)
//Set Timer0 mode
clear_bit( option_reg, T0CS ); //configure timer0 as a timer
//Set prescaler assignment
clear_bit( option_reg, PSA ); //prescaler is assigned to timer0
//Set prescaler rate
set_bit( option_reg, PS2 ); //prescaler rate 1:128
set_bit( option_reg, PS1 );
set_bit( option_reg, PS0 );
//Set timer0 source edge selection
set_bit( option_reg, T0SE ); //increment on high-to-low transition on RA4/T0CKI pin
while( 1 ) //Endless loop
{}
}

  Timer1 Interrupt Code on the PIC16F877A
//Timer1 Interrupt Test, 
//RoboSlave.Blogspot.com, 1/20111
//Includes
#include <system.h>
//PIC16F877A
#pragma DATA _CONFIG, _PWRTE_OFF & _BODEN_OFF & _WDT_OFF & _LVP_ON & _CPD_OFF & _DEBUG_OFF & _XT_OSC & _CP_OFF
#pragma CLOCK_FREQ 4000000 //Set clock frequency
//Define
#define led1 portd.0
//Interrupts
void interrupt( void )
{
//if( pir1 & (1<<TMR1IF) ) //Handle timer1 interrupt
if (pir1.TMR1IF == 1)
{
clear_bit( pir1, TMR1IF ); //clear timer 1 interrupt bit
led1 = !led1;
}
}
//Main Code
void main( void )
{
trisd = 0x00; //Configure port D
portd = 0x00; //Initialize port D
intcon.GIE = 1;
intcon.PEIE = 1;
pie1.TMR1IE = 1;
t1con= 0b00000001; //set timer1 configs and start
while( 1 ) //Endless loop
{}
}

No comments:

Post a Comment