我试图通过按钮打开和关闭Arduino。我使用了教程https://www.instructables.com/id/A-Guide-to-Putting-Your-Arduino-to-Sleep/,以了解如何做到这一点。但不幸的是,这种情况并不适合100%。我希望通过同一开关(而不是通过计时器)打开和关闭两者。 因此,我已经按照下面所示的方式实现了它,只是通过attachInterrupt()将不同的函数重新分配给事件。 就像您一旦分配给事件便无法重新分配该功能。是这样吗有人可以解决这个问题吗?
在再次使用attachInterrupt之前,我已经添加了detachInterrupt。另外,我已经在两者之间添加了延迟。尝试过的中断事件HIGH,LOW和CHANGE总是相同的结果,它们进入睡眠状态,但再也不会唤醒。
#include <avr/sleep.h>
#define INTERRUPT_PWR_BUTTON_PIN 2 // pin for power button (Power button)
void setup() {
Serial.println("I'm up...");
attachInterrupt (digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN), goToSleep, HIGH); //attaching wakeup to interrup 0 on pin 2
delay(1000);
}
void loop() {
Serial.println("Ping");
delay(1000); // wait 1 sec
}
void goToSleep() {
Serial.println("Power Button pressed...");
Serial.flush();
sleep_enable(); // only enabling sleep mode, nothing more
detachInterrupt(digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN)); //remove interrupt 0 from pin 2
attachInterrupt (digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN), wakeUp, HIGH);
/* 2019-05-02 NN: Does not work, device will not wake up at all, unless pressing reset -> 2 buttons for now */
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // setting sleep mode to max pwr saving
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
sleep_cpu();
Serial.println("Just woke up!"); // gets executed after interrupt
digitalWrite(LED_BUILTIN, HIGH);
}
void wakeUp () {
Serial.println("Wakeup Interrupt Fired");
sleep_disable();
detachInterrupt(digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN)); //remove interrupt 0 from pin 2
attachInterrupt (digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN), goToSleep, HIGH);
}
答案 0 :(得分:0)
由于您只想使用一个按钮,因此可以通过中断触发切换功能,并通过该功能使Arduino睡眠或唤醒。您必须使用一个布尔标志来实现这一点。
...
// use flag to control state of sleep
bool isSleeping = false;
void setup() {
...
attachInterrupt (digitalPinToInterrupt(INTERRUPT_PWR_BUTTON_PIN), toggleSleepState, HIGH); //attaching wakeup to interrup 0 on pin 2
...
}
void loop() {
...
}
void toggleSleepState() {
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// If interrupts come faster than 200ms, assume it's a bounce and ignore
if (interrupt_time - last_interrupt_time > 200)
{
// toggle state of sleep
isSleeping = !isSleeping;
if (isSleeping == true) {
goToSleep();
}
else {
wakeUp()
}
}
last_interrupt_time = interrupt_time;
}
void goToSleep() {
// sleep logic
}
void wakeUp () {
// wake up logic
}