專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機教程網(wǎng) >> Arduino >> 瀏覽文章

Arduino的輕觸按鍵檢測

作者:y8686   來源:轉(zhuǎn)自y8686   點擊數(shù):  更新時間:2014年07月05日   【字體:

在Arduino上做單純按鍵檢測,其實是很簡單的。 但是我這里做的方法考慮了一下防抖和抗干擾。

 
大概的原理是:
 
每一次主循環(huán)檢測一次按鍵,發(fā)現(xiàn)低電平(可能為按鍵按下),就在計數(shù)器變量(o_prell)加一, 直到計數(shù)器變量(o_prell)達(dá)到 BUTTONS_SAMPLES 定義的值,則判定按鍵按下。 而在此過程中如果檢測到高電平,則計數(shù)器變量(o_prell)減一,這樣起到防抖和抗干擾的作用。
 
按鍵釋放時,則相反,計數(shù)器變量(o_prell)減一,直到 0。
 
BUTTONS_SAMPLES 我設(shè)置的比較大, 是6000, 主要因為程序里沒什么代碼,主循環(huán)比較快。如果程序代碼較多,主循環(huán)沒有這么快,這個值要調(diào)低的。
這個值改低一點,按鍵靈敏度會提高,但是防抖和抗干擾的作用會變差。
 
如下程序?qū)崿F(xiàn)的功能是,每按一次按鍵,Arduino板上的LED會切換亮滅。  按鍵接在pin#7和GND之間,pin#7需要上拉電阻到5V。
 
 
C++語言: 高亮代碼由發(fā)芽網(wǎng)提供


#define BUTTON_PIN          7       // Button pin
#define LED_PIN             13      // Led pin
#define BUTTONS_SAMPLES     6000   // Affect the sensitivity of the button
#define BUTTON_PRESSED      LOW     // The state of the pin when button pressed

unsigned int o_prell          = 0;      // counter for button pressing detection
boolean button_state          = false;  
unsigned int led_state        = LOW;    // Led off at the beginning

void setup()
{
   //Serial.begin(9600);

   pinMode(BUTTON_PIN, INPUT);
   pinMode(LED_PIN, OUTPUT);
   
   // set initial LED state
   digitalWrite(LED_PIN, led_state);
}

void loop()
{
   check_button();
   digitalWrite(LED_PIN, led_state);
}

void check_button()
{
   int button_input    =   digitalRead(BUTTON_PIN);

   if ((button_input == BUTTON_PRESSED) && (o_prell <</SPAN> BUTTONS_SAMPLES))
   {
       o_prell++;      // counting for button pressing
   }
   else if ((button_input == BUTTON_PRESSED) && (o_prell == BUTTONS_SAMPLES) && !button_state)
   {
       button_state = true;    // button pressed
       //led_state = HIGH;
       led_state = !led_state;
   }
   else if ((button_input != BUTTON_PRESSED) && (o_prell > 0))
   {
       o_prell--;      // counting for button releasing,  or debouncing / immunity
   }
   else if ((button_input != BUTTON_PRESSED) && (o_prell == 0) && button_state)
   {
       button_state = false;
       //led_state = LOW;
   }
}
關(guān)閉窗口

相關(guān)文章