Reversing input from light sensor

Hi there,

I Just started with Arduino, and have been struggling with this one for a week now. Just a simple starter setup, A light sensor and a LED, the LED has a brightness depending on the available light. What should I do if I wanted the LED brighter when there is less light?

// Example 06B: Set the brightness of LED to
// a brightness specified by the
// value of the analogue input
#define LED 9 // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup() {
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop() {
val = analogRead(0); // read the value from
// the sensor
analogWrite(LED, val/4); // turn the LED on at
// the brightness set
// by the sensor
delay(10); // stop the program for
// some time
}

There is couple ways of doing this but I would do this :

void loop() {
val = 1023 - analogRead(0);      // read the value  

// rest of your code 

}

At full light, analogRead(0) give you now value of 1023 , so 1023 - 1023 = 0 and your LED will be Off. When no light, result will be 1023 - 0 = 1023 and your LED will go to full brightness. You can play with this value but do not use higher than 1023 .

PS - allways use code tags when posting code on this forum :slight_smile:

Great, thanks! Sounds logic.

I Was fidgeting with

analogWrite(LED, 255- val/4); // turn the LED on at

or

val = analogRead(1024); // read the value from

or something in that order.

Or you can define VAL as an unsigned integer (for a case...) and make a NOT on it

uint16_t val;
........
val = ~val;

Hi Yuri,

Please explain, what's the logic for that? How would that work?

It just inverts the value bitwise... f.e.:
255 = 1111 1111, NOT(255) = 0000 0000 = 0
240 = 1111 0000, NOT(240) = 0000 1111 = 15 = 255 - 240

Sorry, my mistake... It will not work in your case, because ADC has only 10 bit values, not 8 or 16. :roll_eyes:
You need to use XOR with 1023 instead...

val = val ^ 1023;

Yuri_D:
Sorry, my mistake... It will not work in your case, because ADC has only 10 bit values, not 8 or 16. :roll_eyes:
You need to use XOR with 1023 instead...
val = val ^ 1023;

Mhm, seeing the logic of it, I have no doubt that would work. I'll try both tonight. :smiley:

val = analogRead(1024); // read the value from

The 1024'th analog pin on which Arduino?