0

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?

Shpigford
  • 474
  • 1
  • 8
  • 22
  • 3
    What circuit? What code? output=constrain(map(sensor,100,700,0,255),0,255)); per http://arduino.stackexchange.com/q/9219/6628 ? – Dave X Mar 03 '16 at 03:06

1 Answers1

2

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

e.g.:

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.

Kingsley
  • 773
  • 5
  • 12
  • 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 03 '16 at 05: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 04 '16 at 06:20