Is a 9v battery appropriate for a piezo and 1 LED? 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 &lt;elapsedMillis.h&gt;
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 &gt; openLength){
      for (int n = 0; n &lt; 200 ; n++){
        beep(notes[random(0,2)]);

        if(digitalRead(switchPin) == LOW){ break; }
      }
    }
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t &lt; 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?
A couple things to note:


Get rid of the PWR LED on the Trinket so it's not always drawing current.
Sleep the MCU whenever possible, only waking on interrupts.
Converting 9V to 5V with an LDO (in this case, the MIC5225) implies a 55% efficiency, max, which isn't great. But at least the LDO has a low ground current.


Also, ask yourself if you really need a micro for this task.

If you want a ballpark for runtime, find the capacity of your battery, estimate your current draw, and see what your upper bound on runtime is.