This photoresistor has a min/max of 0-1023.

I'm trying to scale the brightness of a cathode RGB LED based on the sensor's value, but based on my current lighting, the min/max readings I generally am getting are 100-700.

So how can I scale the sensor reading so that 100 = no light on the LED and 700 = max brightness?


1 Answer 1


You can easily scale in Arduino code with the map() function.


const int MIN_LIGHT 100;
const int MAX_LIGHT 700;

int light_reading = analogRead(A0);

// Convert MIN reading (100) -> MAX reading (700) to a range 0->100.
int percentage_bright = map(light_reading, MIN_LIGHT, MAX_LIGHT, 0, 100);

But you may need some calibration of your system to handle different ambient light situations. What reading do you get in direct sunlight for example?

So then I assume you're using PWM (Pulse Width Modulation) to drive the LED. This requires a value between 0 & 255. Once again we can use the map() function.

// Convert light-value % (0-100) to PWM speed (0-255)
int led_brightness = map(percentage_bright, 0, 100, 0, 255);
analogWrite(LED_PIN_RED, led_brightness);

Obviously these bits of code can be reduced down to a single line - mapping directly from the reading to the desired result.

  • A light_reading of 90 would give a negative percentage_bright, which could in turn produce negative led_brightness, which would behave badly. You need a light_reading = constrain(light_reading,MIN_LIGHT,MAX_LIGHT) or percentage_bright=constrain(percentage_bright,0,100)
    – Dave X
    Mar 3, 2016 at 5:08
  • @Dave X - Yep, that's why I had the note about calibration. But I didn't want to confuse the explanation of the map() function.
    – Kingsley
    Mar 4, 2016 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.