Hi guys, I'm an Arduino noob and am working on a project that requires the use of one button to put the Arduino to sleep when clicked once and then wake it up the next time it is clicked. After doing some research and looking at code that other people wrote, I was able to get my Arduino to go to sleep but can't get it to wake up.
It seems like the culprit has to do with sleep_mode() in the goToSleep() function, because when I remove it, I can clearly see that both the goToSleep and wakeUp functions work, and I can't exactly take it out because it seems like that method call is essentially to what I want to end up doing.
It seems really simple, and I'm sure there is a simple solution that I'm missing, but if anyone could help, that would be greatly appreciated!
#include <avr/sleep.h>
int buttonPin = 2;
boolean isSleeping = false;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
delay(100);
Serial.println("I'm up...");
Serial.println(digitalRead(2));
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleSleepState, LOW); //attaching wakeup to interrupt 0 on pin 2
delay(1000);
}
void loop() {
// int buttonState = digitalRead(buttonPin);
// Serial.println(buttonState);
// delay(1000); // wait 1 sec
}
void toggleSleepState() {
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// If interrupts come faster than 20ms, assume it's a bounce and ignore
if (interrupt_time - last_interrupt_time > 200)
{
// toggle state of sleep
isSleeping = !isSleeping;
if (isSleeping == true) {
Serial.println("goToSleep");
goToSleep();
}
else {
Serial.println("wakeUp");
wakeUp();
}
}
last_interrupt_time = interrupt_time;
}
void goToSleep() {
Serial.println("Power Button pressed...");
Serial.flush();
sleep_enable(); // only enabling sleep mode, nothing more
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // setting sleep mode to max pwr saving
sleep_mode();
Serial.println("Checkpoint!"); // gets executed after interrupt
Serial.flush();
}
void wakeUp () {
sleep_disable();
Serial.println("Wakeup Interrupt Fired");
}
For reference, I am using an Arduino Uno and the button I'm using is a large arcade button bought from Adafruit.
button.ino (1.55 KB)