For this assignment, we wanted to make a hovering keyboard. We used the ultrasonic distance measuring sensor to set specific distance ranges to specific notes. As the user would move their hand through different ranges, different notes would play. We also added a button to turn off the instrument completely in addition to implementing a maximum range beyond which the instrument doesn’t produce any sound.
Video:
#include "pitches.h"
// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
const int speakerPin = 8;
const int pushButton = A2;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode()
Serial.begin(9600); // Starts the serial communication
}
void loop() {
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Playing outside distance range or the instrument is turned off
if (distance >= 40 || buttonState == 1) {
noTone(speakerPin);
}
// Play C4 in first 10cm
else if (distance >= 0 && distance <= 10) {
tone(speakerPin, NOTE_C4, 1000 / 4);
}
// Play G4 in next 10cm
else if (distance >= 11 && distance <= 20) {
tone(speakerPin, NOTE_G4, 1000 / 4);
}
// Play A4 in next 10cm
else if (distance >= 21 && distance <= 30) {
tone(speakerPin, NOTE_A4, 1000 / 4);
}
// Play F4 in next 10cm
else if (distance >= 31 && distance <= 40) {
tone(speakerPin, NOTE_F4, 1000 / 4);
}
}
Future Applications:
I think for future applications, the number of keys could be expanded to have 12 keys, and buttons to move up or down an octave so it could be a complete hovering piano with all possible keys present on a keyboard.