Musical instrument with an ultrasonic distance sensor

This week’s assignment was my favorite arduino task thus far. I think it’s because the final outcome seems more reusable for other creative tasks. I used an ultrasonic distance sensor, a push button, and a piezo buzzer to emulate the interactive artwork Aaron once introduced to us in the beginning of the course (tried to find the artwork to show what I was inspired by but was never successful…).

The way it works is very simple. The push button initiates the sound, so only when the button is pressed down, you will be able to hear the notes. You can variate the distance between your hand (or any surface) and the ultrasonic distance sensor to create 3 different notes – middle C (~10 cm), middle D (~15 cm), and middle E (~20 cm). The hand should not move away from the sensor for more than 20 cm for the sound to be activated. Once these conditions are met, the buzzer will emit sound that is corresponding to the notes described above.

While making this instrument, it was important to note the formula for distance that sound travels. This was crucial for me to determine the distance range for each note. Another thing I had to be aware is the fact that echo pin takes in the number for total distance of the sound travel. In other words, I had to be aware that this number represented the round-trip of the sound against the surface and that it had to be halved to obtain the actual distance between the sensor and the object.

Without further ado, here is the video of my working instrument. Please bear in mind that I changed the note after making this video and the notes are now slightly lower and more accurate (Do, Re, Mi).

#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330

int trig = 13;
int echo = 12;
int piezo = 11;
int buttonPin = 3;
int buttonState = 0;

void setup() {
    Serial.begin (9600);
    pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);
    pinMode(buttonPin, INPUT);
}

void loop() {
    int time;
    int distance;
    
    digitalWrite(trig, HIGH);
    delay(0.01);
    digitalWrite(trig, LOW);
    
    time = pulseIn(echo, HIGH);
    
    //speed of sound = 343 m/s = 0.0343 cm/µs
    // distance = time * speed
    distance = time * 0.0343 / 2; // sound wave travels forward and bounces backward.

    Serial.print(distance);
    Serial.println(" cm");

    buttonState = digitalRead(buttonPin);

    if( buttonState == HIGH ) {
      if (distance > 20 || distance < 0){
        noTone(piezo);
        }
      else if (distance < 10){
        tone(piezo, NOTE_C4);
        }
      else if (distance < 15){
        tone(piezo, NOTE_D4);
        }
      else{
        tone(piezo, NOTE_E4);  
        }
    }
    else {
      noTone(piezo);
    }
    delay(100);
}

 

Leave a Reply