Tuesday, December 15, 2009

Afterthoughts

Piezo Code:

int speakerPin = 9;

int length = 12; // the number of notes
char notes[] = "efgaaaabCagf "; // a space represents a rest
int beats[] = { 1, 1, 1, 4, 4, 4, 1, 1, 1, 4, 4, 4, 1, 1, 1, 4, 4,
4, 2, 4, 5, 1, 3};
int tempo = 150;

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

void setup() {
pinMode(speakerPin, OUTPUT);
}

void loop() {
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);
}
}

In case anyone wasn't certain, these tones represent the hymn "Lift Ev'ry Voice And Sing".

Basically, the thing is an Arduino Board with a miniature circuitboard on top. I soldered a piezo speaker (connected to pin 9) and a tilt sensor to the board. The way the tilt sensor works is like this: it's basically a little metal ball in a plastic(?) cube. Depending on which end of the cube the ball is in, it completes one of two circuits. I didn't connect anything to the other curcuit so when the ball isn't on the side that activates the speaker it's just 'off'. The arduino board is connected to a 9 volt battery so it doesn't need a cumbersome laptop setup to operate. I attached the whole thing to the inside of my hat and... well, voila. When I lean forward it plays music.




Uhm... sorry about my camera quality, but I think you get the idea.

Thanks to Mike for lending me the circuitboard, to Allyse for getting me/explaining how to use the battery connection device, Sarah S. for random code/building assistance, and Adam for recording video footage.

No comments:

Post a Comment