Arduino – Photoresistor and LED PWM

Description:

This project uses a photoresistor to detect the ambient light level, and then as the light level goes up or down it changes the brightness of the LED. For this project the LED becomes brighter as the light level goes down.

We use PWM (Pulse Width Modulation) to change the brightness of the LED instead of simply turning the LED fully on or off.

We use basic math and if statements to create a value for the brightness derived from the value of the photoresistor sensor.

Parts:

  • Arduino Uno
  • Photoresisitor
  • LED
  • 10K Ohm resistor
  • 220 Ohm resistor
  • Breadboard
  • Wires

Code:

#define sensor A0 #define led 3 float fade; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); } void loop() { int value = analogRead(sensor); Serial.print("Analog value : "); Serial.print(value); fade = value - 550; if(fade > 255){ fade = 255;} if(fade < 0){fade = 0;} fade = fade/255; fade = 1 - fade; fade = fade * 255; Serial.print(" Fade Value: "); Serial.println(fade); analogWrite(led, fade); }
Code language: PHP (php)