I am working on making an electric piano that can play two notes at once.
I am using this tone library GitHub - bhagman/Tone: A Wiring Library to produce square wave tones on arbitrary pins. because it is designed to allow the playing of more than one tone at a time by a single arduino board, on separate speakers. I have already figured out how to get two tones playing on separate speakers at the same time, but my difficulty is in making this responsive to buttons (keys).
Right now I am trying to code two buttons, where when a button is pressed, it plays a tone on the first speaker that is free. For example, button 1 is pressed and both speakers are free, so a note is played on speaker 1, then button 2 is pressed with button 1 still held down, so button 2 plays a note on speaker 2.
Or vice versa; button 2 is pressed while both speakers are free, so it plays a note on speaker 1, and then button 1 is pressed while button 2 is still held down, so it plays a note on speaker 2. (Sorry if this is confusing!)
I attached my code for this.
From troubleshooting I have learned that:
- Right now when either button is individually pressed after the code is compiled, it simply plays its note on both speakers, and then both speakers continue playing that note.
-Having the sound start & stop with the pressing of the button does work when only using 1 tone on 1 speaker with 1 button.
- My logic for checking when a button is pressed vs not pressed is working correctly; the if statements correctly execute according to the state of the button
- The code to check the state of each speaker is working correctly as well; when tested in isolation the tone.isPlaying() is correct
- If the state of the button and the state of the speaker are correct, could this issue be caused by something related to a race condition in the code? Or any other ideas?
Also, if anyone has ideas for a better way to implement this functionality I am open to them! Thank you so much for reading this & for your help!
Piano_Buttons.ino (2.49 KB)