Assignment: Input / Output Coincidence Lab Assignment
Collaborators:
Assignment: Input / Output Coincidence Lab Assignment
Description:
I created a "music box". I modifed the melody from the melody program in the lab. I added a photocell and an LED to the circuit. When the box lid is removed a song plays and the LED flashes. When the lid is replaced, both the music and the image shut off.
Materials:
- breadboard
- Piezo Speaker
- LED
- Photocell
- resistor
Arduino Code:
/* Play Melody
* -----------
*
* Program to play melodies stored in an array, it requires to know
* about timing issues and about how to play tones.
*
* The calculation of the tones is made following the mathematical
* operation:
*
* timeHigh = 1/(2 * toneFrequency) = period / 2
*
* where the different tones are described as in the table:
*
* note frequency period PW (timeHigh)
* c 261 Hz 3830 1915
* d 294 Hz 3400 1700
* e 329 Hz 3038 1519
* f 349 Hz 2864 1432
* g 392 Hz 2550 1275
* a 440 Hz 2272 1136
* b 493 Hz 2028 1014
* C 523 Hz 1912 956
*
* (cleft) 2005 D. Cuartielles for K3
* modified by Heather Dolan - based on play melody and theramin code from lab, melody has been modified
* October 7, 2009
*/
int ledPin = 3;
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[] = "2d2a1f2c2d2a2d2c2f2d2a2c2d2a1f2c2d2a2a2g2p8p8p8p";
byte melody[] = "2c2c2g2g2a2a2g2f2f2e2e2d2d2c2g2g2f2f2e2e2d2c2c2g2g2a2a2g2f2f2e2e2d2d4c"; //melody
// count length: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
// 10 20 30
int count = 0;
int count2 = 0;
int count3 = 0;
int MAX_COUNT = 24;
int statePin = LOW;
int potPin = 2;
int currentVal = 0;
int val = 0;
void setup() {
//pinMode(speakerPin, OUTPUT);
Serial.begin(9600);
Serial.println("ready");
pinMode(ledPin, OUTPUT);
pinMode(speakerOut, OUTPUT);
val=analogRead(potPin);
}
void loop() {
val=analogRead(potPin);
Serial.println(val);
if (val!=currentVal){
// val=analogRead(potPin);
currentVal=val;
Serial.println(val);
}
if(val<300) {
digitalWrite(speakerOut, LOW);
}
else{
if(val >= 300){ //if the photocell is detecting light, play the melody and flash the light
for (count = 0; count < MAX_COUNT; count++) {
statePin = !statePin;
digitalWrite(ledPin, statePin);
digitalWrite(speakerOut, LOW);
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);
delayMicroseconds(50);
}
}
}
}
}
else{}
}
}