I've written code for an Arduino Nano that when a button is pressed, it sends an IR command. It is set so that if no button press has been received for a period of 10 seconds, it will enter sleep mode until a button press is received. The button to send the IR command is the same button being used to send the wake up interrupt (button connected to pin D2). When testing the code the Arduino is able to go to sleep and wake up from the interrupt 1-3 times before it will suddenly receive an interrupt signal just before entering sleep mode. When this happens it gets stuck in sleep mode and will no longer accept the wake up interrupt. I am currently using Serial Monitor outputs and the built-in LED to determine when the Arduino is in sleep mode or not.
#include <IRLib.h>
#include <avr/sleep.h>
#define interruptPin 2
IRsend My_Sender;
const int button = 2;
int buttonState = 0;
int timeSinceCommand = 0;
const unsigned long eventInterval = 1000;
unsigned long previousTime = 0;
void setup() {
Serial.begin(9600);
pinMode(button, INPUT);
pinMode(LED_BUILTIN, OUTPUT); //delete once code finalized and working
pinMode(interruptPin, INPUT_PULLUP);
digitalWrite(LED_BUILTIN, HIGH); //delete once code finalized and working
Serial.println("---------------------------New Run---------------------------");
}
void loop() {
while (timeSinceCommand < 10) {
unsigned long currentTime = millis();
buttonState = digitalRead(button);
if (buttonState == HIGH) {
My_Sender.send(SONY, 0xC90, 12);
timeSinceCommand = 0;
previousTime = currentTime;
}
if (currentTime - previousTime >= eventInterval) {
timeSinceCommand++;
previousTime = currentTime;
}
}
if (timeSinceCommand >= 10) {
Going_To_Sleep();
timeSinceCommand = 0;
}
}
void Going_To_Sleep() {
sleep_enable();
attachInterrupt(0, wakeUp, RISING);
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
digitalWrite(LED_BUILTIN, LOW); //delete once code finalized and working
Serial.println("Arudino going to sleep!"); //delete once code finalized and working
delay(1000); //delete once code finalized and working
sleep_cpu();
Serial.println("Arudino has waken up!"); //delete once code finalized and working
digitalWrite(LED_BUILTIN, HIGH); //delete once code finalized and working
}
void wakeUp() {
Serial.println("Interrupt received!"); //delete once code finalized and working
sleep_disable();
detachInterrupt(0);
}
Here is the Serial Monitor output from a couple of tests:
---------------------------New Run---------------------------
Arudino going to sleep!
Interrupt received!
Arudino has waken up!
Arudino going to sleep!
Interrupt received!
Arudino has waken up!
Interrupt received!
Arudino going to sleep!
---------------------------New Run---------------------------
Arudino going to sleep!
Interrupt received!
Arudino has waken up!
Interrupt received!
Arudino going to sleep!
EIFR = bit (INTF0);