Motion sensing alarm

 avatar
unknown
plain_text
2 years ago
1.4 kB
11
Indexable
const int TRIG_PIN = 6; // connect to ultrasonic sensor's TRIG pin
const int ECHO_PIN = 7; // connect to ultrasonic sensor's ECHO pin
const int BUZZER_PIN = 3; // connect to piezo buzzer's pin
const int DISTANCE_THRESHOLD = 50; // set the distance threshold

float duration_us, distance_cm;

// notes in the melody:
int melody[] = {
  659, 659, 659,
};

// note durations: 4 = quarter note, 8 = eighth note, etc, also called tempo:
int noteDurations[] = {
  8, 8, 4,
};

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  duration_us = pulseIn(ECHO_PIN, HIGH);
  distance_cm = 0.017 * duration_us;

  // Uncomment this block of code to play the melody when the distance is below the threshold
  /*
  if(distance_cm < DISTANCE_THRESHOLD)
    buzzer(); // play a song
  */

  delay(500);
}

// Uncomment this block of code to enable the buzzer function
/*
void buzzer() {
  int size = sizeof(noteDurations) / sizeof(int);

  for (int thisNote = 0; thisNote < size; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];

    digitalWrite(BUZZER_PIN, HIGH);
    delay(noteDuration);

    digitalWrite(BUZZER_PIN, LOW);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
  }
  digitalWrite(BUZZER_PIN, LOW);
}
*/