Hi,
I´m trying to setup a Nano-based system that runs on a battery. Trying to maximize the batt life, I want it to go to power down, and wake up by:
a. timer (8 secs, for instance), or
b. input HIGH (using a button or other means)
The system will do different tasks depending on the way it is waken up. In this sample, turn on LED if it´s by timer, or beep if it´s by button. After the task, it´s supposed to go again into the 8 secs power down lapse.
I am combining lowpower with interrupts, and it works a little bit oddly. When I press the button, the buzzer will beep maybe 2 or 3 times. I used a small timer for "debouncing", but I´m not sure it millis() works well when Arduino goes in power down, or if it´s OK to call the LowPower routine from the interrupt handler...
Here´s my code. Any hints on what can be changed/improved?
#include <LowPower.h>
byte VT = 2; // Interrupt
byte Buz = 8; // buzzer
byte Led = 13;
const int timeThreshold = 500;
long startTime = 0;
void setup() {
pinMode(VT, INPUT);
pinMode(Buz, OUTPUT);
pinMode(Led, OUTPUT);
}
void loop() {
attachInterrupt(digitalPinToInterrupt(2), RunInterrupt, RISING); // int on (again)
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); // go to sleep for 8 secs
detachInterrupt(digitalPinToInterrupt(2)); // if it wakes up from powerdown, disable int until loop completes
digitalWrite(Led, HIGH); // enciendo LED para mostrar que arrancó, y ver consumo
delay(150);
digitalWrite(Led, LOW);
}
void RunInterrupt()
{
detachInterrupt(digitalPinToInterrupt(2)); // no interrupts while processing
if (millis() - startTime > timeThreshold) // only once every half second, to avoid input debounces
{
tone(Buz, 880, 300); // do this only when button pressed
startTime = millis();
}
attachInterrupt(digitalPinToInterrupt(2), RunInterrupt, RISING); // reactivates interrupts
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); // ..and go to sleep again for 8 secs
}
Thanks in advance!