/**
Mini piano for Arduino.
You can control the colorful buttons with your keyboard:
After starting the simulation, click anywhere in the diagram to focus it.
Then press any key between 1 and 8 to play the piano (1 is the lowest note,
8 is the highest).
Copyright (C) 2021, Uri Shaked. Released under the MIT License.
*/
const int trigPin = 9; // Trigger pin of ultrasonic sensor
const int echoPin = 10; // Echo pin of ultrasonic sensor
const int numLeds = 5; // Number of LEDs to control
const int ledPins[numLeds] = {2, 3, 4, 5, 6}; // Pins connected to the LEDs
const int distanceThresholds[numLeds + 1] = {200, 250, 300, 350, 410}; // Distance thresholds for each LED
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.0343) / 2; // Convert the time into distance
Serial.print("Distance: ");
Serial.println(distance);
// Turn off all LEDs
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], LOW);
}
// Turn on the appropriate LED based on distance
for (int i = 0; i < numLeds; i++) {
if (distance >= distanceThresholds[i] && distance < distanceThresholds[i + 1]) {
digitalWrite(ledPins[i], HIGH);
break; // Exit loop once LED is turned on
}
}
delay(500); // Delay for stability
}