For this week’s assignment, we were tasked with using Arduino to create a musical instrument. Working in pairs, Kashish and I decided to create a piano based on the tone() function we had explored earlier in class. In our project, we wanted each button switch to correspond to a different note from a piano, so that it could be “played”.
We were asked to use both an analogue and digital component for the assignment; while the digital component was simple enough with the buttons, we decided to use a pontentiometer as our analogue component, and used it to control the pitch of the notes being produced by each button.
The components we used were:
- Arduino Uno
- Breadboards
- Jumper cables
- 10k Ohm resistors
- Push buttons
- 5V speaker
Here is an image of our project, and the schematic:
Our code:
#include "pitches.h" const int potPin = A0; // Potentiometer on A0 const int buzzerPin = 8; // Speaker on D8 const int buttonPins[] = {2, 3, 4, 5, 6, 7, 9, 10}; // C4-C5 buttons const int baseNotes[] = {NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5}; void setup() { // Keep external 10k resistors for (int i = 0; i < 8; i++) { pinMode(buttonPins[i], INPUT); } pinMode(buzzerPin, OUTPUT); } void loop() { // potentiometer value int potValues[5] = {0}; int potIndex = 0; potValues[potIndex] = analogRead(potPin); potIndex = (potIndex + 1) % 5; int octaveShift = map( // mapping potentiometer values as a shift in octave (potValues[0] + potValues[1] + potValues[2] + potValues[3] + potValues[4]) / 5, 0, 1023, -2, 2 ); // Check buttons to play notes bool notePlaying = false; for (int i = 0; i < 8; i++) { if (digitalRead(buttonPins[i]) == HIGH) { int shiftedNote = baseNotes[i] * pow(2, octaveShift); tone(buzzerPin, constrain(shiftedNote, 31, 4000)); notePlaying = true; break; } } if (!notePlaying) { noTone(buzzerPin); } delay(10); }
Videos of our project:
A challenge we faced was definitely our lack of musical knowledge. Neither Kashish or I are musicians, and as such, we had to do a lot of research to understand the terminology and theory, such as the notes, and how to adjust the octave using the potentiometer. We then also had to figure how to reflect these findings within our code.
Overall though, we had a great time making this project, and then executing our idea.