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
Yuri_D:
Sorry, my mistake... It will not work in your case, because ADC has only 10 bit values, not 8 or 16.
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.