A worked model for the design brief: a switch on the box arms the alarm after a short exit delay; opening the box flashes an LED and sounds the buzzer.
From the unit Crack the Code
· activity PRP 4: Digital output — Buzzer
int sensorPin = 7; // the sensor (a switch on the box) connects to pin 7
int flashPin = 13; // an LED that lights up when the alarm sounds
int buzzerPin = 3; // the buzzer connects to pin 3
int Status = 0; // 0 = exit delay, 1 = armed, 2 = triggered
int sensor = 0; // the current sensor reading
void setup() {
pinMode(sensorPin, INPUT);
pinMode(flashPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
if (Status == 0) { // first time through the loop — arm the alarm
delay(3000); // gives you 3 seconds to close the box
tone(buzzerPin, 725, 40); // a short beep...
delay(200);
tone(buzzerPin, 725, 40); // ...and another, so it double-beeps when armed
Status = 1; // armed — don't run this block again
}
if (Status == 1) {
sensor = digitalRead(sensorPin); // read the switch
}
if (sensor == 0) { // the box has been opened
Status = 2;
}
if (Status == 2) { // triggered — flash the LED and sound the alarm
digitalWrite(flashPin, HIGH);
tone(buzzerPin, 725, 1000);
delay(1000);
tone(buzzerPin, 330, 1000);
delay(1000);
}
}
Shared from Little Bird Electronics curriculum.