I'm making a basic "door open" detector that, when a door is opened, it turns on an LED and then sounds an alarm via a piezo.
This is controlled via a 5v Adafruit Trinket.
Is a 9v battery the correct thing to power this with, if the goal is to change batteries as infrequently as possible?
Here's the code, incase that's relevant.
#include <elapsedMillis.h>
elapsedMillis timeElapsed;
const int switchPin = 2;
const int ledPin = 1;
const int piezoPin = 0;
const uint32_t openLength = 5 * 1000L; // X seconds
int notes[] = {862,294,730};
void setup() {
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(piezoPin, OUTPUT);
digitalWrite(switchPin, HIGH);
}
void loop() {
if(digitalRead(switchPin) == LOW){
digitalWrite(ledPin, LOW);
timeElapsed = 0;
} else {
digitalWrite(ledPin, HIGH);
if (timeElapsed > openLength){
for (int n = 0; n < 200 ; n++){
beep(notes[random(0,2)]);
if(digitalRead(switchPin) == LOW){ break; }
}
}
}
}
void beep(int delayAmount)
{
for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
{
digitalWrite(piezoPin,HIGH);
delayMicroseconds(delayAmount);
digitalWrite(piezoPin,LOW);
delayMicroseconds(delayAmount);
}
}
UPDATE: I had a 9V plugged in to this for about 3 days before it used all the power in 9V. Is that an issue w/ voltage on the battery (i.e. I should be using AA's instead of a 9V)? Or does that point largely to some other inefficiency w/ the code or hardware?
notes[random(0,2)]
will only be 0 or 1 (2 is never reached). But you have 3 values in your array.