51单片机外部中断示例

void Usart_INT0_init()
{
  TMOD = 0X21;
  TH1 = 0XFD;
  TL1 = 0XFD;
  SM0 = 0;
  SM1 = 1;
  REN = 1;
  TR1 = 1;

  //ES = 1;//串口中断影响外部中断0 这句话会让程序无法进入外部中断服务

  TH0 = 0;
  TL0 = 0;
  ET0 = 0;//关闭定时器0

  IT0 = 1;//外部中断下降沿触发*/
  EX0 = 1;//打开外部中断

  EA = 1;
  //ES = 1;
}

void Send_data(unsigned char dat)
{
  SBUF = dat;
  while(!TI);
  TI = 0;
}

int j;

void main()
{
  unsigned int i;
  LED = LED_ON;
  //LED = LED_OFF;
  flag_test_high = ON;

 
  IN0 = 1;
  Usart_INT0_init();

  EX0 = 1;
  while(1)
  {  
       /*i=40000;
    while(i--);*/

    /*flag_test_high = ON;

    EX0 = 1;
    while(flag_test_high == ON);
    EX0 = 0;
    //Send_data('a');*/
    Send_data(result|0x30); 
  }
}

void EX_int(void) interrupt 0
{
  EX0 = 0;
  
  ET0 = 1;//打开定时器
  TR0 = 1;
  while(IN0 == 0);
  TR0 = 0;
  
  tem_TH = TH0;
  tem_TL = TL0;
  sum = tem_TH*256 + tem_TL;
  sum = (int)sum/1000;
  result = 9 - sum;
     //result = 9-(int)(10*(TH0*256 + TL0)/10000);//分步计算避免出错

  TH0 = 0;
  TL0 = 0;
  
  LED = LED_OFF;
  //Send_data(result|0x30);
  flag_test_high = OFF;
  ET0 = 0;//关闭定时器
  EX0 = 1;
}

你可能感兴趣的:(it,单片机,ea)