看门狗! 听起来就足够“高大上”的。
曾一度以为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里面每次循环开始的时候“喂狗”。
主循环loop里有按键检测,检测到pin#7上的按键按下就切换pin#13上的LED状态,启动时默认LED熄灭。
如果检测到串口有数据输入则进入死循环,watchdog定时器1s到时间后会自动重启。
实验,烧入程序后,按按键使得LED亮起,然后在电脑上打开串口终端,发送任何字符,1秒后LED会熄灭(重启后的LED初始状态),表示arduino重启了。
C语言: 高亮代码由发芽网提供
#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;
}
}