Connect as shown in the following figure:
The resistor size of the photosensitive resistor is inversely proportional to the brightness. By measuring the voltage of the resistor, you can know the resistor size of the photosensitive resistor to know the brightness.
Code:
# Define led_green 9 // define the Pin Connecting to the green light
# Define led_red 10 // define the Pin connected to the red light
Int brightness = 0; // how bright the LED is
Int fadeamount = 5; // how to specify points to fade the led
Void setup ()
{
Pinmode (led_green, output );
Pinmode (led_red, output );
Serial. Begin (9600); // open the serial port and set the baud rate to 9600 bps.
}
Void loop ()
{
Int I;
While (1)
{
I = analogread (5); // read simulation Port 5
Serial. println (I, DEC); // send the string from the serial port and wrap the line
If (I> 400) // when there is light, modify this value according to the actual situation
{
// Set the brightness of Pin 9:
Analogwrite (led_green, brightness );
Analogwrite (led_red, 0 );
// Change the brightness for next time through the loop:
Brightness = brightness + fadeamount;
// Reverse the direction of the fading at the ends of the fade:
If (brightness = 0 | brightness = 255 ){
Fadeamount =-fadeamount;
}
// Digitalwrite (led_green, high); // green light
// Digitalwrite (led_red, low); // disable the red light
// Delay (1000); // set the delay time, 1000 = 1 second
// Digitalwrite (led_green, low); // green light
// Delay (1000); // set the delay time, 1000 = 1 second
} Else
{
// Set the brightness of Pin 9:
Analogwrite (led_red, brightness );
Analogwrite (led_green, 0 );
// Change the brightness for next time through the loop:
Brightness = brightness + fadeamount;
// Reverse the direction of the fading at the ends of the fade:
If (brightness = 0 | brightness = 255 ){
Fadeamount =-fadeamount;
}
// Digitalwrite (led_red, high); // red light
// Digitalwrite (led_green, high); // green light
// Delay (1000); // set the delay time, 1000 = 1 second
// Digitalwrite (led_red, low); // red light
// Digitalwrite (led_green, low); // green light
// Delay (1000); // set the delay time, 1000 = 1 second
}
Delay (30 );
}
}
After compilation and upload, when the photosensitive resistance is not blocked, the green LEDs are switched from dark to bright, and then from Bright to dark. When the photosensitive resistance is blocked, the red LED starts the same action. View the serial port data to see the analog value of the resistance voltage (0-1024, maximum 1024)
There is another point in the code that needs to be modified, for example, to block the photosensitive resistance. The brightness of the red LED is the brightness of the last moment before the green LED goes off.
The resistance value in series with the photosensitive resistance is better than the resistance value when the photosensitive resistance is light-free, or a little smaller, so the effect is better.