How can i get my sustain pedal to work?
What i want to happen: If i press my C tone key while holding my sustain button it plays the C tone, then release my C tone key and still hold my sustain button it will continue to play my C note until i release the sustain button.
What happens: The "if statement" does not continue to play the C tone when releasing the C tone key while holding the sustain key. I tried exchanging the "if statement" for a "while statement," which does continue to play the note, but does not stop when i release the sustain button and I can't get it out of the while loop without it doing the same thing as the "if statement".
I've tried multiple ways around this without any success.
does any one have an idea so i can get this to work?
int button_C = 2;
int sustainPedal = 11;
int speaker = 13;
int buttonstate_C = 0;
//NOTES 'c' , 'd', 'e', 'f', 'g', 'a', 'b', 'C'
int tones1[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; //freq
int tones2[] = { 3830, 3400, 3038, 2864, 2550, 2272, 2028, 1912};
int Cur_tone = 0;
void setup()
{
pinMode(10,INPUT);
pinMode(sustainPedal,INPUT);
pinMode(button_C, INPUT);
pinMode(speaker, OUTPUT);
}
void loop()
{
piano2();
}
void piano2()
{
int buttonstate_C= digitalRead(button_C);
int pedalState = digitalRead(sustainPedal);
if((buttonstate_C == LOW) && (pedalState == LOW))
{
while(pedalState == LOW)
{
Cur_tone = tones1[1];
digitalWrite(speaker, HIGH);
delayMicroseconds(Cur_tone);
digitalWrite(speaker, LOW);
delayMicroseconds(Cur_tone);
}
}
else if((buttonstate_C == LOW))
{
if (buttonstate_C == LOW)
{
Cur_tone = tones1[0];
}
digitalWrite(speaker, HIGH);
delayMicroseconds(Cur_tone);
digitalWrite(speaker, LOW);
delayMicroseconds(Cur_tone);
}
else //in case no button is pressed , close the piezo
digitalWrite(speaker, LOW);
}
Project1_Piano.ino (1.18 KB)