For our assignment, Nafiha and I drew inspiration from a synthesizer and a sampler to create our own musical instrument. Our instrument incorporates three buttons, a piezo buzzer, a potentiometer, and a bunch of wires and resistors. It is designed such that each button triggers a distinct melody, and by adjusting the potentiometer, the pitch is modified, consequently altering the played melodies.
Video:
link:https://drive.google.com/file/d/1zvd5qZeavfn0oTLdWGMqWOIxTLay6gbp/view?usp=sharing
Code:
const int switch1Pin = 12; const int switch2Pin = 8; const int switch3Pin = 7; const int potentiometerPin = A0; const int buzzerPin = 3; int currentMelody[8];//array to store the current melody int melodyIndex = 0;// keep track of the current note in the melody int isPlaying = 0;//to indicate whether a melody is currently playing //melodies for each button int melody1[] = {262, 330, 392, 523, 392, 330, 262, 196};//melody for switch 1 int melody2[] = {330, 392, 523, 392, 330, 262, 196, 262};//melody for switch 2 int melody3[] = {392, 523, 659, 523, 392, 330, 262, 330};//melody for switch 3 void setup() { pinMode(switch1Pin, INPUT_PULLUP); pinMode(switch2Pin, INPUT_PULLUP); pinMode(switch3Pin, INPUT_PULLUP); pinMode(potentiometerPin, INPUT); pinMode(buzzerPin, OUTPUT); } void loop() { //potentiometer value for pitch control int pitch = analogRead(potentiometerPin); //if switch 1 is pressed if (digitalRead(switch1Pin) == HIGH && !isPlaying) { playMelody(melody1, pitch); } //if switch 2 is pressed if (digitalRead(switch2Pin) == HIGH && !isPlaying) { playMelody(melody2, pitch); } //if switch 3 is pressed if (digitalRead(switch3Pin) == HIGH && !isPlaying) { playMelody(melody3, pitch); } //check if any switch is pressed and a melody is currently playing if ((digitalRead(switch1Pin) == HIGH || digitalRead(switch2Pin) == HIGH || digitalRead(switch3Pin) == HIGH) && isPlaying) { noTone(buzzerPin);//stop playing the melody isPlaying = 0;//set the flag to indicate no melody is playing } } void playMelody(int melody[], int pitch) { //map the potentiometer reading to adjust the pitch int adjustedPitch = map(pitch, 0, 1023, 50, 255); //copy the melody to the currentMelody array memcpy(currentMelody, melody, sizeof(currentMelody)); //play each note in the melody for (int i = 0; i < sizeof(currentMelody) / sizeof(currentMelody[0]); i++) { tone(buzzerPin, currentMelody[i], adjustedPitch); delay(250); noTone(buzzerPin); } //set the flag to indicate a melody is currently playing isPlaying = 1; }
In terms of improving our instrument, one potential feature could be incorporating additional sound effects through the use of the potentiometer. However, overall, working on this assignment was really fun, and we’re pretty pleased with the outcome.