PROJECT: Light Sensor LED Strip Gauge
Step 1 - Build the Project
Using an LED Strip and a light sensor, create a light gauge that lights up more pixels when it's bright and fewer when it's dim.
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
Above the setup, create an integer variable named numPixels. This will stand in for the number of LED pixels on your LED strip. Any time you use the integer numPixels, it will act as if you typed 15 in that place.
When you're using an LED strip, you need to tell the library about that strip. In the line LEDStrip strip = LEDStrip(numPixels, 12, 11), you are telling the library "I'm using an LEDStrip and I want to name it 'strip'. The strip has 'numPixels' number of pixels and its data pin is connected on pin 12. Its clock pin is connected on pin 11. That is called creating an object and it links the hardware to the library.
In the setup() section of the code, set the pinMode of the light sensor to INPUT_PULLUP, so it sends a signal close to 0 for brightness and close to 1000 for darkness.
In the loop of the code, first create a variable called lightValue and set its value to the analogRead(A2). Now any time you use the variable lightValue, you're using the analog reading of pin 2. Keep in mind that the variable only updates its value on this line, not each time you use it. You're using the same single analogRead for an entire loop.
Now, create an integer variable called pixel. This variable will tell your code how high on the LED strip to fill in with color. Your lightValue variable will probably range between 150 and 900. However, you only have 15 light pixels on your strip.
To make the light value map to the pixels, you use the map command. First, you tell map that you're mapping the variable lightValue. Then you tell it you want a 150 lightValue to equal 0 pixels lit and a 900 light value to equal 'numPixels' lit. Whether you have 15 pixels or 4 pixels or 40 pixels, this map command will work with your numPixels variable. After the variable is mapped, it will have a value between 0 and numPixels.
The next step is to clear the strip with the strip.clear() method, wiping away all of the color on the strip.
Now you'll use a for loop to light up the pixels. First, create an integer called 'i' and set the value to 0. This variable exists only inside the for loop. Then, tell the for loop that as long as i is less than pixel; increase i by one with the ++ operator each time the loop runs.
The content of the for loop lights up the pixel corresponding to the value of variable i. The first time through, the strip.setPixel() method will use 0 as the value of i. The next time through, the for loop will use 1 as the value of i. After i is equal to the value of the variable pixel, the for loop is complete and it ends. The strip.draw() method then displays all of the pixels that the for loop has set with the .setPixel method().