LEDs and Light Dependent Resistors

I have a led that turns on and off. I have an LDR that should register the on and off - but it doesn't. When you turn the lights off it drops to near 0 even tho the light is flashing next to it??? Code as follows.

*/

// pin assignments
int LDR = 0;

// initialize the serial port
// and declare inputs and outputs
void setup() {
pinMode(LDR, INPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}

// read from the analog input connected to the LDR
// and print the value to the serial port.
// the delay is only to avoid sending so much data
// as to make it unreadable.
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000);
int v = analogRead(LDR);
Serial.println(v);
delay(10);

}

You only sample the LDR when the LED is off. :slight_smile:

If you use millis for the timing it is easy to decouple sampling and blinking.

const byte LDR = A0;
unsigned long lastSecond, lastPrint;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
}

// read from the analog input connected to the LDR
// and print the value to the serial port.

void loop() {
  unsigned long topLoop = millis();
  if (topLoop - lastPrint >= 330) {
    lastPrint = topLoop;
    int v = analogRead(LDR);
    Serial.println(v);
  }
  if (topLoop - lastSecond >= 1000) {
    lastSecond = topLoop;
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
}

While you can use 0 as a name of an analog port in analogRead, pinMode needs A0 to manage the mode of an analog pin. So this

int LDR = 0;
 
   pinMode(LDR, INPUT);

does not work as expected.