Final – Update

I have admittedly fallen behind in terms of progress (in comparison to the current date), but I fortunately do have some updates to share! I have been able to commit to my chosen concept and start working on the primary components of the project.

The Concept, Revisited and Given Life

The base concept for my project involves an Arduino-based musical instrument of sorts that 1) the user can interact with to play notes and 2) is able to trigger a certain change in the p5js sketch when a correct tune—so a correct combination of notes—is played. As the general idea and its essential components were set in stone, I set out to first make the instrument itself. The plan was to have a device with five buttons that each play a different note through a speaker when pressed (D4, F4, A4, B4, D5). After some tinkering, I settled on a circuit that worked, the diagram of which looks like:

The actual circuit:

And now, the most prominent milestone so far: I was able to construct the code that I needed to achieve the desired effect from Arduino! Using arrays, I was able to simplify much of the repetitive code and condition checks, with the final result being:

#include "pitches.h"

int buttonPins[] = {
  2, 3, 4, 5, 6
};
int pinCount = 5;
int buttonStates[5];
int notes[] = {
  NOTE_D4, NOTE_F4, NOTE_A4, NOTE_B4, NOTE_D5
};
const int BUZZER_PIN = 8;
bool counter = false;

void setup() {
  Serial.begin(9600); // Initialize Serial
  for (int buttonPin = 0; buttonPin < pinCount; buttonPin++){
    pinMode(buttonPins[buttonPin], INPUT_PULLUP);
  }

  pinMode(BUZZER_PIN, OUTPUT); // Set Arduino Pin to Output Mode
  pinMode(13, OUTPUT);
}

void loop() {
  for (int buttonPin = 0; buttonPin < pinCount; buttonPin++){
    buttonStates[buttonPin] = digitalRead(buttonPins[buttonPin]);
  }
  for (int buttonPin = 0; buttonPin < pinCount; buttonPin++){
    if (buttonStates[buttonPin] == LOW) {
      if (counter == false) {
      Serial.println(buttonPin); //Sends Number of Button Being Pressed to p5js
      counter = true;
    }
    digitalWrite(13, HIGH);
    tone(BUZZER_PIN, notes[buttonPin], 500);
    delay(500);
    noTone(BUZZER_PIN); // Stop the tone playing:
  }
  else if (buttonStates[0] == HIGH) {
    digitalWrite(BUZZER_PIN, LOW);  // Turn off
    counter = false;
  }
  }
}

The use of for() loops in tandem with the buttonPins[] and notes[] arrays facilitates much of the input and output management here, with a notable line of code being Serial.println(buttonPin), which is used to send the “number” of the button being pressed to p5js. As I continue working on my project, I will be able to gather these outputs and run condition checks on p5js that determine whether the “correct” string of buttons (notes) has been played. Again, this will then trigger certain effects depending on the song. With the base Arduino-instrument completed, I can now move onto the next stages of the project—I look forward to what I can make of this vision!

Leave a Reply