So... I'm obviously doing something wrong here.
I'm trying to produce sound from this buzzer that I bought from Radio Shack (part number 273-0053; it's a mini buzzer, 1.5-3.0VDC, 15mA. It's resonant frequency is 300 - 500Hz) using my LilyPad Arduino as a driver. The LEDs light up just fine; it's the buzzer that isn't working. I'm getting nada sound out of it. ![]()
I'm powering the circuit with 3.0V (two AA batteries). The buzzer's positive lead is attached to the #3 pin of the Lilypad, and the negative lead is attached to a ground bus. As for the code, I've written the following set of functions, but the ones in particular that seem to be at fault are the beep() and scale() functions, as near as I can tell. Can anyone tell me what I'm doing wrong?
/*
Blink 7
Turns on 7 LEDs on for one second, then off for one second, repeatedly.
Modified to include a Buzzer sequence at the beginning of the LED blinks.
*/
int LED1[] = {0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0};
int speakerPin = 3;
void setup() {
// initialize the digital pins as output/input.
int i;
for (i = 0; i < 20; i++){
if (LED1[i] == 1){
pinMode(LED1[i], OUTPUT);
}
else{
pinMode(LED1[i], INPUT);
}
}
}
void loop() {
int i;
for (i = 0; i < 20; i++){
if (LED1[i] == 1){
digitalWrite(i + 1, HIGH);
}
}
delay(1000);
for (i = 0; i < 20; i++){
if (LED1[i] == 1){
digitalWrite(i + 1, LOW);
}
}
scale();
delay(1000);
}
void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds) // the sound producing function
{
int x;
long delayAmount = (long)(1000000/frequencyInHertz);
long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
for (x=0;x<loopTime;x++)
{
digitalWrite(speakerPin,HIGH);
delayMicroseconds(delayAmount);
digitalWrite(speakerPin,LOW);
delayMicroseconds(delayAmount);
}
}
void scale ()
{ // My buzzer has a resonant frequency of 300 - 500 Hz, so I am limiting my sequence to these notes.
beep(speakerPin,330,500); //E3
beep(speakerPin,349,500); //F3
beep(speakerPin,392,500); //G3
beep(speakerPin,440,500); //A3
beep(speakerPin,494,500); //B3
}
Is it a problem with my code, or am I simply using the wrong type of component for this? Since I didn't buy the special Lilypad buzzer from SparkFun, am I facing divine retribution from the Arduino gods? xD