如何切换LED

时间:2017-10-17 02:01:22

标签: embedded

如何使用按钮切换LED。我写了程序。程序中存在问题。如果我连续按下按钮然后LED连续打开/关闭,此程序将失败。如何解决问题?

  #include<REGX51.h>

  #define led_off         0
  #define switch_pressed  0

  sbit  Switch = P1^2;                    /*set bit P1^2 to Switch*/

  sbit led = P1^0;                       /*set bit P1^0 to LED*/


  void debounce (unsigned long wait)     /* Debounce function */
  {
       unsigned int i;
       for (i = 0; i < wait;  i++);
  }

  void main (void)
  {
     led = led_off;

  while (1)
  {
      if (Switch ==  switch_pressed)

        {
            led = ~led;
            debounce (40000);
        }

  }
}

1 个答案:

答案 0 :(得分:1)

只要按下按钮,您就会切换按钮。当按钮从未按下变为按下时需要切换 时:

#include<REGX51.h>

#define BTN_UP  1
#define BTN_DN  0
#define DEBOUNCE_DELAY 40000

sbit Switch = P1^2 ;  
sbit led = P1^0 ;

void delay( unsigned long wait ) 
{
     for( volatile unsigned long i = 0 ; 
          i < wait;  
          i++ )
     { /* do nothing */ } 
}

int main( void )
{
    int prev_button_state = Switch ;
    led = 0 ;

    for(;;)
    {
        // Read current Switch state
        int button_state = Switch ;

        // If BTN_DN event...
        if( button_state != prev_button_state && 
            button_state == BTN_DN )
        {
            led = ~led;
            delay( DEBOUNCE_DELAY ) ;
        }

        prev_button_state = button_state ;
    }

    return 0 ;
}