在Arduino上做單純按鍵檢測(cè),其實(shí)是很簡(jiǎn)單的。 但是我這里做的方法考慮了一下防抖和抗干擾。
大概的原理是:
每一次主循環(huán)檢測(cè)一次按鍵,發(fā)現(xiàn)低電平(可能為按鍵按下),就在計(jì)數(shù)器變量(o_prell)加一, 直到計(jì)數(shù)器變量(o_prell)達(dá)到 BUTTONS_SAMPLES 定義的值,則判定按鍵按下。 而在此過(guò)程中如果檢測(cè)到高電平,則計(jì)數(shù)器變量(o_prell)減一,這樣起到防抖和抗干擾的作用。
按鍵釋放時(shí),則相反,計(jì)數(shù)器變量(o_prell)減一,直到 0。
BUTTONS_SAMPLES 我設(shè)置的比較大, 是6000, 主要因?yàn)槌绦蚶餂](méi)什么代碼,主循環(huán)比較快。如果程序代碼較多,主循環(huán)沒(méi)有這么快,這個(gè)值要調(diào)低的。
這個(gè)值改低一點(diǎn),按鍵靈敏度會(huì)提高,但是防抖和抗干擾的作用會(huì)變差。
如下程序?qū)崿F(xiàn)的功能是,每按一次按鍵,Arduino板上的LED會(huì)切換亮滅。 按鍵接在pin#7和GND之間,pin#7需要上拉電阻到5V。
C++語(yǔ)言: 高亮代碼由發(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;
}
}