Week 10: Musical Instrument

Concept

We wanted to make a device that allows artists to simulate high-hats in drill beats according how they bob their heads. We realized that sound engineers move their body in a unique way. We used an ultrasonic sensor and novel equation to track this movement and produce a drill beat with a correlated frequency.

Code & Schematic

We used an ultrasonic sensor to obtain distance measurements, a switch to implement a function to introduce delay and slow the sound down.  Also the inspiration for the code to produce a melody was inspired by Prof. Michael Shiloh’s implementation.

We used these inputs to make a device that produces a sound continuously sampled and responds to the distance of the user from the sensor.

Here are the schematics for the circuit implementation:

#include "pitches.h"
#define echoPin 2 
#define trigPin 3 

int pushButton = 7;
const int sPin = 1;
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] = {
  4,4,5,4,5,4,5
};

unsigned long currentNoteStartedAt = 0;

int thisNote = 0;

int millisToNextNote = 0;

int currentLedState = LOW;
unsigned long currentLedStateStartedAt = 0;
long ledDelay = 100;


long duration;
int distance; 

void setup() {
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 
  Serial.begin(9600); 
  
  pinMode(pushButton, INPUT);
}
void loop() {
  
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
 
  distance = duration * 0.034 / 2; 
    unsigned long currentMillis = millis();

  if (currentMillis - currentNoteStartedAt >= millisToNextNote) {

    int noteDuration = 1000 / noteDurations[thisNote];

    tone(3, melody[thisNote], noteDuration);
    millisToNextNote = log10(distance) * 1300;
    currentNoteStartedAt = currentMillis;
    thisNote++;

   
    if ( thisNote >= 8 ) {
      thisNote = 0;
    }
  }

  
  if (currentMillis - currentLedStateStartedAt >= ledDelay) {

   
    if (currentLedState == LOW) {
      currentLedState = HIGH;
    } else {
      currentLedState = LOW;
    }
    currentLedStateStartedAt = currentMillis;
  }

  int buttonState = digitalRead(pushButton);
  if (buttonState==true){
    Serial.println(buttonState);
    delay(100);}

}

Result / Future improvements

We wanted to implement a loudness altering function to the piezo speaker and tested the schematic on tinker cad as well, however during the implementation it did not seem to work out. Some improvements that could made are the ability to give the user more flexibility with what sounds to choose.

Leave a Reply