单片机原理与应用实验——中断嵌套(C语言),定时器0和外部中断0的嵌套,分别实现流水灯和按键

(基于51核的STC12C5A60S2,keil uvision5 mdk 5.25 编译)

 

 

#include 

typedef unsigned char u8;

typedef enum
{
	Tim0_L_Int0_H = 1,
	Tim0_L_Int0_L,
	Tim0_H_Int0_L,
}EnumCase;


sbit LED1 = P2 ^ 4;
sbit LED2 = P2 ^ 5;
sbit LED3 = P2 ^ 6;
sbit LED4 = P2 ^ 7;

sbit BEEP = P1 ^ 0;     

sbit KEY1 = P3 ^ 2;
sbit KEY2 = P3 ^ 4;

//---------------------------------------------------------------------
static u8 i_1sCnt = 0;
static u8 LEDStatus = 0;
//---------------------------------------------------------------------

void delay_2ms(unsigned long int time) //2ms�Ļ�
{
	unsigned long int i;
	for (i = 0; i < time * 100; i++);
}


void SetPriorty(EnumCase chose)
{
	switch (chose)
	{
	case Tim0_L_Int0_H:
		IP = 0x01;
		break;
	case Tim0_L_Int0_L:
		IP = 0x00;
		break;
	case Tim0_H_Int0_L:
		IP = 0x02;
		break;
	default:
		break;
	}
}


void Timer0_Init()
{				
	TH0 = 0;			 //最大延时,约为130ms
	TL0 = 0;
	TMOD = 0x01;			    
	TR0 = 1;		
		     
	ET0 = 1;
  EA = 1;	
}

void Timer0() interrupt 1
{
	TH0 = 0;			 
	TL0 = 0;

	i_1sCnt++;
	if (i_1sCnt==15)
	{
		i_1sCnt = 0;

		LEDStatus++;
		switch (LEDStatus)
		{
			case 1:
				LED1 = 0; LED2 = 1; LED3 = 1; LED4 = 1;
				break;
			case 2:
				LED1 = 1; LED2 = 0; LED3 = 1; LED4 = 1;
				break;
			case 3:
				LED1 = 1; LED2 = 1; LED3 = 0; LED4 = 1;
				break;
			case 4:
				LED1 = 1; LED2 = 1; LED3 = 1; LED4 = 0;
				LEDStatus = 0;
				break;
			default:
				break;
		}

	}
	
}


void ISR_Init()
{
	IT0 = 0;   

	EX0 = 1;   
  EA = 1;    
}

void INT0_ISR() interrupt 0
{
	EX0 = 0;  

	BEEP = 1;
	delay_2ms(125);
	BEEP = 0;
	delay_2ms(125);
	BEEP = 1;
	delay_2ms(125);
	BEEP = 0;
	delay_2ms(125);

	EX0 = 1; 
}

//-------------------------------------------------------------------------

//想查看的设为1,不想查看的设为0,仅有一个为1
#define TEST1  1
#define TEST2  0
#define TEST3  0

void main()
{
	BEEP = 0;

#if TEST1
SetPriorty(Tim0_L_Int0_H);
#endif
	
#if TEST2
SetPriorty(Tim0_L_Int0_L);
#endif

#if TEST3
SetPriorty(Tim0_H_Int0_L);
#endif

	Timer0_Init();		//
	ISR_Init();

	while (1);
}

 

你可能感兴趣的:(单片机原理与应用)