/* * NeoPixelUltrasonic_8LED.ino * XIAO ESP32-C3 + HC-SR04 + WS2812B (8 LEDs) * * Trig -> D1, Echo -> D2, NeoPixel DIN -> D3 * * Closer distance -> more LEDs lit (bar graph) * LED 0 = closest (red) -> LED 7 = farthest (white) * Out of range -> all off */ #include // --- Pins --- const int trigPin = D1; const int echoPin = D2; const int neoPixelPin = D3; // --- LED count --- #define NUM_PIXELS 8 // --- Distance range --- const float MIN_CM = 5.0; const float MAX_CM = 40.0; // --- NeoPixel --- Adafruit_NeoPixel strip(NUM_PIXELS, neoPixelPin, NEO_GRB + NEO_KHZ800); // One color per LED — index 0 = closest (red), index 7 = farthest (white) const uint32_t palette[NUM_PIXELS] = { strip.Color(255, 0, 0), // 0 — red strip.Color(255, 128, 0), // 1 — orange strip.Color(255, 255, 0), // 2 — yellow strip.Color( 0, 255, 0), // 3 — green strip.Color( 0, 255, 255), // 4 — cyan strip.Color( 0, 0, 255), // 5 — blue strip.Color(255, 0, 255), // 6 — magenta strip.Color(255, 255, 255) // 7 — white }; int lastLitCount = -1; float readAverageDistanceCm() { float total = 0; int valid = 0; for (int i = 0; i < 5; i++) { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); long duration = pulseIn(echoPin, HIGH, 30000); if (duration > 0) { total += duration * 0.0343 / 2.0; valid++; } delay(10); } if (valid == 0) return -1.0; return total / valid; } int distanceToLitCount(float cm) { if (cm < 0 || cm > MAX_CM) return 0; if (cm <= MIN_CM) return NUM_PIXELS; int count = map( (long)(cm * 10), (long)(MIN_CM * 10), (long)(MAX_CM * 10), NUM_PIXELS, 1 ); return constrain(count, 0, NUM_PIXELS); } void setup() { Serial.begin(115200); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); strip.begin(); strip.setBrightness(50); strip.clear(); strip.show(); Serial.println("8-LED NeoPixel + Ultrasonic ready!"); } void loop() { float distance = readAverageDistanceCm(); int litCount = distanceToLitCount(distance); if (litCount != lastLitCount) { strip.clear(); for (int i = 0; i < litCount; i++) { strip.setPixelColor(i, palette[i]); } strip.show(); lastLitCount = litCount; Serial.print("Distance: "); Serial.print(distance, 1); Serial.print(" cm -> LEDs lit: "); Serial.println(litCount); } delay(200); }