Esp8266 Team Hack Light Sensing
by querry43 in Circuits > Microcontrollers
346 Views, 3 Favorites, 0 Comments
Esp8266 Team Hack Light Sensing
This project is part of a series for an instructables team hack. See the series for more information.
A photoresistor is a resistor that changes its resistance value based on how much light touches it. We can combine this with another resistor of known value to make a voltage divider.
The protoresistor in the kit already has a resistor attached on the black leg under the heatshrink tubing. When we connect it to 3.3 volts, the output will read between 0 and 3.3 volts depending on brightness.
Connect the photoresistor following the images and the mapping below. You can leave the LED attached from the previous steps if you want.
Red -> 3V3 Black -> GND Gray -> A0
Reading Light Levels
The sensor is going to output different voltages based on how much light it receives. We will need to configure an analog (ADC) pin to read these values.
from machine import ADC light = ADC(0)
Now we can read the light level. This will give up a number between 0 and 65,536. Higher numbers indicate more light, lower numbers less light.
light.read_u16()
Read the light values in a loop, twice a second.
# read_light.py from machine import ADC from utime import sleep_ms light = ADC(0) while True: print(light.read_u16()) sleep_ms(500)
Setting Led Color Based on Light Level
Let's combine this with the RGB LED to change the color based on how bright it bright it is. This is a lot to type out in the repl, so instead write it to a file and copy copy that file to the esp8266 using the webrepl `Send a file`. If you got your board for the team hack, then it should already be there.
# set_color_based_on_light.py # import some libraries from machine import ADC, Pin from utime import sleep_ms # define the light sensor pin light = ADC(0) # define the rgb led pins red = Pin(5, mode=Pin.OUT,value=0) green = Pin(4, mode=Pin.OUT, value=0) blue = Pin(0, mode=Pin.OUT, value=0) # define a threshold threshold = 40000 # create a function to adjust the led color based on light levels while True: sleep_ms(100) if light.read_u16() > threshold: red.on() blue.off() else: red.off() blue.on()
Load the file.
import set_color_based_on_light
The led should turn red when the light level is high and blue when it is low.
Exit the function with `control-c`.
If the light stays red or blue, try setting the threshold higher or lower.
Next Steps
What can we do with this? There are a number of projects which connect relays to esp8266 dev boards to turn on and off lights. Perhaps this could be used to:
- Detect when a trick-or-treater breaks a light beam and turn on halloween props.
- Turn on your porch light for a few hours when it starts getting dark.
- Detect when your model train reaches the crossing and flash the crossing lights.