Project 8.02 Mapping Light

In this project we will use the Min and Max brightness values from the last sketch to vary the brightness of an LED based on the light on the LDR. The darker the room, the brighter LED1 will be.

Project Code:

//////////////////////////////////////////
// 8.02 Mapping Light

byte lightSensorPin = A2;
int maxValue = 909;
byte minValue = 23;

byte LED1 = 13;

void setup() {
  pinMode(lightSensorPin, INPUT);
  pinMode(LED1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int currentValue = analogRead(lightSensorPin);
  
  int LED1Brightness = map(currentValue, minValue, maxValue, 0, 255);
  
  LED1Brightness = constrain(LED1Brightness, 0, 255);
  
  analogWrite(LED1, LED1Brightness);
}
//////////////////////////////////////////

*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.

In my case, my maxValue is 909 and my minValue is 23. Yours will probably be slightly different. You’ll need to update the variables below for your specific values.

int maxValue = 909;
byte minValue = 23;

In the loop() function, we first have to analogRead the voltage on the LDR. The analogRead function reads from 0 – 1023 (10-bit) but the analogWrite function write values of 0 – 255 (8-bit). The map function will take care of this issue. Remember, the map function takes five parameters. It takes the value to map, the min value of that range, the max value of that range, the min value of the range to be mapped to, and the max value of the range to be mapped to.

int LED1Brightness = map(currentValue, minValue, maxValue, 0, 255);

Sometimes the LDR will register values higher or lower than the range we defined in our code. For this reason, we want to “Constrain” our readings. This just keeps our readings from going above or below the range we’ve defined.

To keep this from happening, what we need to do is use the constrain function. The constrain function allows us to keep a variable in between certain numbers. For example, if we were to get a value of 300 and our constrain range is 0 – 255, the function would return 255. The same is true for the lower range, but it returns the low constrained value. If the value is instead within the range, it just returns that value.

LED1Brightness = constrain(LED1Brightness, 0, 255);

Lastly, the LED1Brightness analog value is written to LED1.

analogWrite(LED1, LED1Brightness);
Previous
Previous

Project 9.00 Using the Temp Sensor

Next
Next

Project 8.01 Max and Min Brightness