Little Bird Curriculum / code littlebird.com.au
_10_Alarm_Basic.ino Arduino (C/C++) 34 lines · 3 views ✦ Open in English IDE Raw Download Embed view

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);
  }
}

Embed this snippet

As an iframe:

Or drop it inline with a script tag (injects the highlighted block where included):

Shared from Little Bird Electronics curriculum.

Copied to clipboard