#include FASTLED_USING_NAMESPACE #define DATA_PIN 5 #define LED_TYPE WS2812 #define COLOR_ORDER GRB #define NUM_LEDS 24 CRGB leds[NUM_LEDS]; #define BRIGHTNESS 96 #define NOTE_C4 262 #define NOTE_C5 523 #define NOTE_C6 1047 #define END -1 int melody[] = { NOTE_C4, NOTE_C5, NOTE_C6, END }; // note durations: 8 = quarter note, 4 = 8th note, etc. int noteDurations[] = { //duration of the notes 12, 8, 4, 0 }; const int trigPin = 4; const int echoPin = 2; const int distance_threshold = 155; //cm int speed = 90; //higher value, slower notes float duration_us, distance_cm; void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); delay(3000); // 3 second delay for recovery FastLED.addLeds(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); FastLED.setBrightness(BRIGHTNESS); } void loop() { digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration_us = pulseIn(echoPin, HIGH); distance_cm = 0.017 * duration_us; if (distance_cm > distance_threshold) { ShowLight(95); int noteDuration = speed * noteDurations[3]; tone(3, melody[3], noteDuration); delay(noteDuration); noTone(3); } if (distance_cm > 100 && distance_cm <= distance_threshold) { ShowLight(60); int noteDuration = speed * noteDurations[0]; tone(3, melody[0], noteDuration); delay(noteDuration); noTone(3); } if (distance_cm > 50 && distance_cm <= 100) { ShowLight(22); int noteDuration = speed * noteDurations[1]; tone(3, melody[1], noteDuration); delay(noteDuration); noTone(3); } if (distance_cm <= 50) { ShowLight(0); int noteDuration = speed * noteDurations[2]; tone(3, melody[2], noteDuration); delay(noteDuration); noTone(3); } } void ShowLight(uint8_t hue) { for (int i = 0; i < NUM_LEDS - 1; i++) { leds[i] = CHSV(hue, 255, 255); } FastLED.show(); FastLED.delay(9); }