Single-chip microcomputer: interrupt system control diode on and off

Example 6-2: As shown in Figure 6-2 , 8 light-emitting diodes are connected to the P0 port, and a button is connected to the pin. It is required that each button can change the light-emitting diodes on and off.
#include <reg51.h>
#define LED P0	
sbit KEY = P3^3;
bit flag=0;
void delay(unsigned char n)     //延时子函数;
{
  	unsigned char a;
  	for(a=0;a<n;a++);
}
 
main(void)
{       
    IT1=1;	//设置边沿触发方式
    EA=1;
   EX1=1;
    LED=0xff;	//发光二极管灭
while(1)
    {
    	if( flag==1 )   		//有外部中断的按键
        {
        	delay(100);  		//延迟一段时间,判断是否为抖动
            if( KEY==0 ) 		//还有按键,说明不是抖动
            {
            	 while( !KEY );	//等待按键松开
                LED=~LED;		//改变发光二级管的亮灭
           	}
              flag=0; 		//上次外部中断已经处理完毕,所以清除该变量
		EX1=1;  			//再次开放外部中断
        }	
 	}
}
void  int1(void) interrupt 2	//中断服务程序
{
    flag=1;			//设置中断标志变量为真,表明有按键闭合
    EX1=0;		                //暂时不允许再次产生外部中断
}
An example picture is:
When writing the interrupt service program, the operation that makes the interrupt time too long should be avoided. If the interrupt service program in this example is compiled as follows:

void int1(void) interrupt 2// interrupt service routine

{

    delay(100); // Delay for a period of time to determine whether it is jitter

    if( KEY==0 ) // There are still keys, indicating that it is not shaking

    {

      while( !KEY ); // wait for the key to be released

        LED=~LED; // Change the light-emitting diode on and off

     }

}

     Since the interrupt function has the processing of removing the button vibration and waiting for the button to be released, when the button is pressed for too long, the program will fall into the execution statement while ( !KEY ) and cannot exit, which may cause program logic errors. If the serial port interrupt is used to send and receive data in the system at the same time, the serial port interrupt request will not be responded to by the CPU in time, resulting in serial port data sending and receiving errors.


 Can you give me a free like! !  

Guess you like

Origin blog.csdn.net/weixin_59798969/article/details/123796630