看門狗! 聽起來就足夠“高大上”的。
曾一度以為Arduino有bootloader就不會有watchdog了,但是事實上是有的。
我參考了如下兩個鏈接:
http://tushev.org/articles/arduino/item/46-arduino-and-watchdog-timer
http://blog.csdn.net/chn89/article/details/17199171
然后寫了如下代碼實驗。
該代碼正常情況下啟動watchdog,并設定watchdog定時器為1s。 loop里面每次循環(huán)開始的時候“喂狗”。
主循環(huán)loop里有按鍵檢測,檢測到pin#7上的按鍵按下就切換pin#13上的LED狀態(tài),啟動時默認LED熄滅。
如果檢測到串口有數(shù)據(jù)輸入則進入死循環(huán),watchdog定時器1s到時間后會自動重啟。
實驗,燒入程序后,按按鍵使得LED亮起,然后在電腦上打開串口終端,發(fā)送任何字符,1秒后LED會熄滅(重啟后的LED初始狀態(tài)),表示arduino重啟了。
C語言: 高亮代碼由發(fā)芽網(wǎng)提供
#include
#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);
wdt_enable(WDTO_1S); // enable the watchdog timer : 1 second timer
}
void loop()
{
wdt_reset(); // feed the dog
check_button();
digitalWrite(LED_PIN, led_state);
if (Serial.available()>0)
{
while(1) ;
}
}
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;
}
}