The program below, from "Getting Started With Arduino", changes the rate an LED blinks based on the analog output of a light-dependent resistor. As it is written, the LED blinks slower as the light level increases. I would like to make it blink faster as the light level increases and tried doing so by taking the absolute value of the reading on pin 0, minus 1023 as shown below:
val = abs(analogRead(0)-1023);
It seems like this should return a low value for a high reading of pin 0 and vice versa. The problem is when I run it, the LED blinks at a rate of about one second on and one second off regardless of the amount of light falling on the sensor.
What am I doing wrong?
Thanks,
Tom
#define LED 13 // Define 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 used as an OUTPUT
}
void loop() {
val = analogRead(0); // read the value from the sensor
digitalWrite(13, HIGH); // turn the LED on
delay(val); // wait
digitalWrite(13, LOW); // turn the LED off
delay(val); // wait
}
Ok, so it was actually a light level issue not a coding issue. The LDR is apparently not very sensitive and it takes a strong light to make any change in the flashing rate of the LED.
Thanks to Coding Badly for a more elegant alternative to using the abs function.
No need to thank me. I thought I was helping solve the problem you were having. Now that I've had a pick-me-up (cinnamon toast; yum) I can see the two lines of code return the same values.
The LDR is apparently not very sensitive and it takes a strong light to make any change in the flashing rate of the LED.
The LDR may be more sensitive than you give it credit for. It needs to be part of a voltage divider, and you haven't said anything about how you have it wired up.
If the other part of the voltage divider has too much or too little resistance, the range of values measured will be smaller than it could be,
Right, it's probably more of a narrow range issue than sensitivity. Room light has no effect, but the concentrated light from a flashlight or laser pointer drives it to the limit.
If this had turned out to be a coding issue, how does one go about debugging an Arduino program? It would have been nice to be able to read the value of the variable val in the program. That would have solved the problem much quicker.
how does one go about debugging an Arduino program?
Serial.begin() in setup(), and Serial.print() or Serial.println() in loop().
But, you didn't answer my question. An LDR SHOULD be sensitive enough to react to normal room light. Measure the resistance of the LDR, when not connected to anything, in bright light, and in the dark. What resistance values do you read? What value is the other resistor in your voltage divider?