Saturday, November 12, 2011

Arduino - Light Dependent Resistor used to control brightness of LED

A light dependent Resistor (LDR) changes it's resistance based on how much light hitting it.

I know this can be done without the Arduino, I am dong this to get the bits together for a more complex project.
Making sure the individual pieces work before putting them together.

I read the LDR on analog pin 1 and then used PWM on pin 6 to set the LED.

// Background Light (the brightest it will be)
int LDRMax;

// When LDR is value returned (depends on the resistor in line with the LDR (I used a 1.5K)
int LDRMin = 50;

// Ratio of range to 255 (max analog out reading)
float LDRRatio;

// Analog Pin for reading LDR
int LDRPin = 1;

// The Value read for the LDR
int LDRValue;

// PWM Pin for the LED
int ledPin = 6;

void setup() {               
  // Initalize LED Pin
  pinMode(ledPin, OUTPUT);    

  // Enable Serial Communication - useful for debugging
  // Get the maximum LDR Reading
  LDRMax = analogRead(LDRPin);

  // Print to serial
  Serial.print("LDRMax: ");

  // Calculate the ratio (note the use of float - since the calculation is being done on integers you have to state this is a float calculation
  LDRRatio = (float)255/(LDRMax-LDRMin);

  // Print to serial
  Serial.print("LDRRatio: ");


void loop() {
  // Read the LDR
  LDRValue = analogRead(LDRPin) - LDRMin;

  // Print the value to the monitor so I can see it

  // Modify reading to match analogWrite range using Ration calculation
  LDRValue = (LDRValue
  ) * LDRRatio;
  // Sometimes the number is over 255 or under 0 - rounding errors !!!!!
  if (LDRValue < 0){LDRValue = 0;}
  if (LDRValue > 255){LDRValue = 255;}
  // Print to Monitor 
  Serial.print("LDRValue after calculation: ");

  // Set the value for the LED
  analogWrite(ledPin, LDRValue);

Still figuring out the Arduino coding and also auto calibrate the LDR so I have the full range.
In the video the range of readings was from 30 to 155.  The scale is 0 to 1023 so I'm only getting a small portion of the range which means I have to get this right to go from full brightness to off.