/*
Arduino | coding-help
Hiran - March 6, 2026 11:56 AM
Can anyone make a code for an air piano?
There are two 5 pin sensors on each end of the piano.
The piano has 8 notes and on each note an led light.
I want to have it so that an led lights up and if you move
your hand in front of the led/onto the note that the next
led will light and it'll form a song for example
twinkle twinkle little star.
Ive gone through a lot of trial and error but i cant see to get it to work
*/
// pin constants
const int LEFT_TRIG_PIN = 13;
const int LEFT_ECHO_PIN = 12;
const int RIGHT_TRIG_PIN = 3;
const int RIGHT_ECHO_PIN = 2;
const int LEFT_LED_PINS[4] = {11, 10, 9, 8};
const int RIGHT_LED_PINS[4] = {7, 6, 5, 4};
const int BUZZ_PIN = A0;
// note constants
const int NOTES_LEFT[4] = {131, 147, 165, 175}; // C3 D3 E3 F3
const int NOTES_RIGHT[4] = {392, 440, 494, 523}; // G4 A4 B4 C5
// zone distance constants
const int ZONES[4] = {10, 20, 30, 40};
// funtion returns distance as a long
long measureDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 20000);
long distance = duration * 0.0343 / 2;
return distance;
}
void setup() {
Serial.begin(9600);
pinMode(LEFT_TRIG_PIN, OUTPUT);
pinMode(LEFT_ECHO_PIN, INPUT);
pinMode(RIGHT_TRIG_PIN, OUTPUT);
pinMode(RIGHT_ECHO_PIN, INPUT);
for (int i = 0; i < 4; i++) {
pinMode(LEFT_LED_PINS[i], OUTPUT);
pinMode(RIGHT_LED_PINS[i], OUTPUT);
}
}
void loop() {
// Measure distance
long distanceLeft = measureDistance(LEFT_TRIG_PIN, LEFT_ECHO_PIN);
long distanceRight = measureDistance(RIGHT_TRIG_PIN, RIGHT_ECHO_PIN);
// Turn LEDs off
for (int i = 0; i < 4; i++) {
digitalWrite(LEFT_LED_PINS[i], LOW);
digitalWrite(RIGHT_LED_PINS[i], LOW);
}
// -------- LEFT HAND --------
for (int i = 0; i < 4; i++) {
if (distanceLeft > ZONES[i] - 5 && distanceLeft < ZONES[i] + 5) {
Serial.print("Left: ");
Serial.print(distanceLeft);
Serial.println(" cm");
digitalWrite(LEFT_LED_PINS[i], HIGH);
tone(BUZZ_PIN, NOTES_LEFT[i], 500);
}
}
// -------- RIGHT HAND --------
for (int i = 0; i < 4; i++) {
if (distanceRight > ZONES[3 - i] - 5 && distanceRight < ZONES[3 - i] + 5) {
Serial.print("Right: ");
Serial.print(distanceRight);
Serial.println(" cm");
digitalWrite(RIGHT_LED_PINS[i], HIGH);
tone(BUZZ_PIN, NOTES_RIGHT[i], 500);
}
}
delay(50);
}