Motion Alarm

Here is a motion alarm I made using an infrared sensor, a speaker, and an RGB LED. When motion is detected, the light turns yellow and the alarm plays. The light turns blue when the sensor stops detecting motion.

CODE

//This code creates a motion alarm using an ir sensor.
//When motion is detected the light changes color and a song plays.
//The speaker code is borrowed from
//http://www.arduino.cc/en/Tutorial/melody#.UxTNY16O1xk

int red = 3;
int green = 5;
int blue = 6;
int ir = 7;
int irValue = 0;
int speakerPin = 8;

int length = 15; // the number of notes
char notes[] = “ccggaagffeeddc “; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;

void setup(){
Serial.begin(9600);
pinMode(ir, INPUT);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(speakerPin, OUTPUT);
digitalWrite(3, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);

}

void loop(){
irValue = digitalRead(ir);
Serial.print(irValue);

if(irValue == 1){
digitalWrite(red, HIGH);
digitalWrite(green, LOW);
digitalWrite(blue, LOW);
} else {
digitalWrite(red, LOW);
digitalWrite(green, HIGH);
digitalWrite(blue, LOW);
}
while(irValue == 1){
for (int i = 0; i < length; i++) {
if (notes[i] == ‘ ‘) {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}

// pause between notes
delay(tempo / 2);
irValue = 0;
}

}

delay(20);

}

void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}

void playNote(char note, int duration) {
char names[] = { ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘a’, ‘b’, ‘C’ };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}

Advertisements

One thought on “Motion Alarm

  1. Pingback: Physical Computing Experiments | conteximus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s