Friday, November 20, 2009

Playing Sound With the Arduino

One of the great things about going to an awesome school is the teachers, especially those who will let you borrow microprocessors.

I've been wondering for several months now if I should buy an Arduino, the relatively low cost microcontroller that has hobby engineers going wild (seriously, wild. You would not believe how much someone can love a computer chip until you've seen the die hard Arduino fans). Fortunately, my school's ASR (Applied Science Research) teacher let me borrow an Arduino for the weekend. I've only had a couple hours to tinker with it, but so far I've been very impressed by both the Atmega 328 (the chip) and the design of the board. I've had the chance to sift through some of the documentation on the Arduino site, and my favorite tutorial so far has been the Melody tutorial.

Setup was quick and easy, once you get the hang on which pins do what, and yielded a pretty annoying little song (but still pretty cool).

I've gotten a lot of feedback that there should be more videos on BW Science Labs, so here's one I shot of my borrowed Arduino playing "Marry Had a Little Lamb".


I only recorded this once, even though it plays in a loop. After about two or three times of playing "Marry Had a Little Lamb" you start to lose your mind.

And for those of you too lazy to click on the link above, here's the code I used to make this happen:

int speakerPin = 9;

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

0 comments:

blogger templates 3 columns | Make Money Online