PORTB的功能基本就是普通IO,但它在其他方面有其他引脚不具备的特点,PORTB的每一个引脚在作为输入时,内部都有一个弱上拉可用。
PORTB的RB0可以作为一个外部中断信号输入,可以对输入信号的上升沿或下降沿跳变产生一个中断响应。
要实现RB0/INT中断源,软件初始化设定步骤如下:
1,RB0/INT引脚为输入模式,TRISB0 = 1;
2,INTEDG = 1,RB0上输入信号上升沿产生中断;INTEDG = 0,下降沿中断
3,清除INTF = 0,确识有效中断发生前中断标志为0;
4,INTE = 1,允许RB0/INT中断响应。
5,GIE = 1,打开总中断使能
6,中断发生后,查询INTF位;
7,若INTF = 1,有中断,处理完毕后,软件必须清除INTF中断标志位。
#include
#define uchar unsigned char
#define uint unsigned int
// CONFIG
#pragma config FOSC = HS //
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = ON // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3/PGM pin has PGM function; low-voltage programming enabled)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
#define DELAY 500
uchar count;
void delay(uint x) //1ms
{
uint y,z;
for(y=x;y>0;y--)
for(z=25;z>0;z--);
}
void init(void)
{
TRISB0=0;
RB0=1; //为下降沿创造高电平的初始条件
TRISB0=1; //输入模式
INTEDG=0; //0下降沿触发,1为上升沿触发
INTF=0; //清零标志位
INTE=1; //开中断允许
GIE=1; //开全局中断
}
void interrupt INT() //查询式中断
{
if(INTE&&INTF)
{
INTF=0;
count++;
TRISB0=0; //RB0设为输出
RB0=1; //输出高电平,以便检测中断条件(下降沿)
TRISB0=1; //设为输入,等待中断
}
}
void main(void)
{
uchar i,temp;
TRISA=0x00;
PORTA=0xff;
temp=0x01;
init();
while(1)
{
if((count%2)==1)
{
PORTA=temp;
delay(DELAY);
temp^=1;
}
}
}