Hi, I'm having trouble starting my piezo buzzer when the LED is low, and having no tone while the LED is high. I'm new to Arduino and coding, so any help would be greatly appreciated. Here is my code so far:
const int sensorPin = 0;
const int ledPin = 9;
const int buzzerPin = 10;
// We'll also set up some global variables for the light level:
int lightLevel, high = 0, low = 1023;
const int songLength = 18;
char notes[] = "cdfda ag cdfdg gf ";
int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};
int tempo = 300;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop()
{
lightLevel = analogRead(sensorPin);
autoTune();
analogWrite(ledPin, 255-lightLevel);
if (lightLevel==high)
noTone(songLength);
else
tone();
int i, duration;
for (i = 0; i < songLength; i++)
{duration = beats[i] * tempo;
if (notes[i] == ' ')
{delay(duration);}
else
{tone(buzzerPin, frequency(notes[i]), duration); delay(duration);}
delay(tempo/10);}
}
void autoTune()
{
if (lightLevel < low)
{
low = lightLevel;
}
if (lightLevel > high)
{
high = lightLevel;
}
lightLevel = map(lightLevel, low+30, high-30, 0, 255);
lightLevel = constrain(lightLevel, 0, 255);
}
int frequency(char note)
int i;
const int numNotes = 8;
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};
for (i = 0; i < numNotes; i++)
{
if (names[i] == note)
{
return(frequencies[i]);
}
}
return(0);
Moderator edit:
</mark> <mark>[code]</mark> <mark>
</mark> <mark>[/code]</mark> <mark>
tags added.