Connect the LDR to a resistor as show below. As the resistance of the LDR will vary with the amount of light the voltage at point X will vary. To gain better understanding I suggest to try different values for the resistor R, to get a feeling how this sketch works. E.g. try the following 5 values for R : 1K 10K 100K 1M 10M. You will see that depending on the value of R the range of voltages (no light, max light) will change.
5V >-- [ LDR ] ---+--- [ R ] ---< GND
Arduino pin A0
Now to the software: The Arduino globally works as follows, when started it first will call the Setup
() routine. In my example code it initializes the speed of the serial port to match the default value of the PC. Then a string is printed to see it works.
After calling Setup the arduino will call the Loop
() routine over and over again. In my example a value from the LDR is read by calling ReadLDR(with some parameters), then this value which is a floating point var is printed to the serial port with 2 decimal places, and because it represents a voltage the code prints that too . Notice the difference between print en println. The latter adds a newline. Then the loop waits for 200 milliseconds and starts over again.
Then there is float ReadLDR
(unsigned int cnt, int pin).
The signature states this function needs two variables, a counter and a pinnumber (abbreviated by lazy programmer) The pinnumber refers to the Analog0 pin where the hardware is connected to. The count is added to stabilize the reading by averaging multiple readings.
if (cnt > 1000) cnt = 1000;
else if (cnt == 0) cnt = 1;
takes care that count will allways stay between 1 and 1000 as we must have at least 1 reading and not to much.
for (int i=0; i<cnt; i++) v += analogRead(pin);
we must declare a float for the value to return, here named v. Then we enter a for loop in which the analogRead(pin) reads a binary representation of the voltage at pin . This is a 0 for 0 volt and 1023 for 5.0 volt, 2Volt will return ~410 etc.
The construction v+= analogRead(pin) is equal to v = v + analogRead(pin). So in short the for loop adds up multiple readings.
v = (v * 5.0) / 1023 / cnt;
does several things. The / cnt takes care that the reading is averaged, the *5.0 / 1023 maps the value 0..1023 to a floating point value of 0..5.0 volt. This value is returned.
So this is about how the posted code works.