Input/Output Coincidence Lab: Alarmed box
Description:
I used a small candy tin as the object that would receive input and give output. The input was through light which was sensed by the photocell, and output was given by sound from the piezo speaker. The box would set off an alarm sound when opened.
You can see the video here.
Materials Used:
- Piezo speaker
- Photocell
- 10kohm resistor
- Tin box
Code:
int sensorPin = 2; // select the input pin for the sensor
int ledPin = 11; // select the output pin for the LED
int val = 0; // variable to store the value coming from the sensor
int speakerOut = 7;
byte names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'};
int tones[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
byte melody[] = "4a4g";
int count = 0;
int count2 = 0;
int count3 = 0;
int MAX_COUNT = 24;
int statePin = LOW;
void setup() {
Serial.begin(9600);
pinMode(speakerOut, OUTPUT);
}
void loop() {
val = analogRead(sensorPin); // read the value from the sensor, 0-1023
//analogWrite(ledPin, val/4); // analogWrite (dimming the LED) can be between 0-255
if (val > 100) {
digitalWrite(speakerOut, LOW);
for (count = 0; count < MAX_COUNT; count++) {
statePin = !statePin;
for (count3 = 0; count3 <= (melody[count*2] - 48) * 30; count3++) {
for (count2=0;count2<8;count2++) {
if (names[count2] == melody[count*2 + 1]) {
digitalWrite(speakerOut,HIGH);
delayMicroseconds(tones[count2]);
digitalWrite(speakerOut, LOW);
delayMicroseconds(tones[count2]);
}
if (melody[count*2 + 1] == 'p') {
// make a pause of a certain size
digitalWrite(speakerOut, 0);
}
}
}
}
}
Serial.println(val); // writing the value to the PC via serial connection
}