We used switches to control when the sound is played or not. If the switch is pressed, the lines are connected. Since lines are only connected when the switch is pressed, we made the code play continuous sounds (or what sounds like continuous), this will allow the user to press the switch at anytime and hear the sound, therefore the user controls how long the notes last for. The user is always able to control if the sound will be playing or not. The instrument can play 4 notes (C5, D5, E5, F5), the notes are limited because we had limited material: only 4 switches.
The code we used:
/*Khai Tran and Will 6/15/2017 Musical Instrument */ #define NOTE_C5 523 #define NOTE_D5 587 #define NOTE_E5 659 #define NOTE_F5 698 int noteC = 1; //note C in port 1 int noteD = 2; //note D in port 2 int noteE = 3; //note E in port 3 int noteF = 4; //note F in port 4 int speakerPin = 13; //speaker connect to pin 13 with a resistor void setup() { //code for seting up each button pinMode (noteC, OUTPUT); pinMode (noteD, OUTPUT); pinMode (noteE, OUTPUT); pinMode (noteF, OUTPUT); pinMode (speakerPin, OUTPUT); } void c () { //code for playing the 'C' note // play the tone using pin 13 with frequency 523 Hz for 500 ms = 0.3 seconds tone(13, 523, 30); } void d () { //code for playing the 'D' note // play the tone using pin 13 with frequency 587 Hz for 500 ms = 0.3 seconds tone(13, 587, 30); } void e () { //code for playing the 'E' note // play the tone using pin 13 with frequency 659 Hz for 500 ms = 0.3 seconds tone(13, 659, 30); } void f () { //code for playing the 'F' note // play the tone using pin 13 with frequency 698 Hz for 500 ms = 0.3 seconds tone(13, 698, 30); } void loop() { if (digitalRead(noteC)==HIGH) { //play note C(5) if note F is pressed c (); } if (digitalRead(noteD)==HIGH) { //play note D(5) if note F is pressed d (); } if (digitalRead(noteE)==HIGH) { //play note E(5) if note F is pressed e (); } if (digitalRead(noteF)==HIGH) { //play note F(5) if note F is pressed f (); } }