I'm working on a lighting project for the front of my garage. I have a string of addressable LEDs, hooked up to an Uno, being controlled by an HC-SR04 sensor, and am trying to make it so the lights will "follow" you as you walk in front of the garage. For example when you're 40 inches from the sensor the lights 40 inches away will come on, and as you move the light will "move" with you. I have it technically working, except that the lights don't always turn off as you move. I'm also wondering if there is cleaner way to code it. I've included the sketch below.
Thanks!
#include <FastLED.h>
const int trigPin = 8; //trigger for sensor
const int echoPin = 7; //return from sensor
//----------LIGHT STRIP INFO----------------------------------
#include <FastLED.h>
#define NUM_LEDS 150 //number of LEDs
#define DATA_PIN 6 //data pin
CRGB leds[NUM_LEDS]; //light array
//**********************************************************
void setup() {
Serial.begin(9600); //starts serial monitor
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
}
void loop()
{
long duration, inches; //variables for distance
//---------------------CODE TO TRIGGER SENSOR-----------------------
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//******************************************************************
// -------------CODE TO READ,& CONVERT INPUT FROM SENSOR------------
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.println();
//*******************************************************************
//-------CODE TO TURN ON SECTIONS OF THE LIGHTS BASED ON DISTANCE FROM SENSOR-------------
if (inches <150) {
leds[inches-6] = CRGB(0,0,0);
leds[inches-5] = CRGB(70,70,70);
leds[inches-4] = CRGB(105,105,105);
leds[inches-3] = CRGB(140,140,140);
leds[inches-2] = CRGB(175,175,175);
leds[inches-1] = CRGB(210,210,210);
leds[inches] = CRGB(240,240,240);
leds[inches+1] = CRGB(210,210,210);
leds[inches+2] = CRGB(175,175,175);
leds[inches+3] = CRGB(140,140,140);
leds[inches+4] = CRGB(105,105,105);
leds[inches+5] = CRGB(70,70,70);
leds[inches+6] = CRGB(0,0,0);
FastLED.show();
}
else if (inches > 150) {fill_solid( &(leds[0]), NUM_LEDS, CRGB::Black);
FastLED.show();
}
delay(300);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}