Photoresistors: a resistor that changes with light

A photoresistor (also called an LDR, light-dependent resistor) is a small disk with a zigzag line of cadmium sulfide (CdS). When more light falls on it, its resistance decreases. A common part, the GL5528, has about 1 MΩ in the dark and about 10–20 kΩ at 10 lux (a dim room). In bright light, it goes down to some hundred ohms. The ESP32 cannot measure resistance directly, so you put the LDR in a voltage divider with a fixed resistor. Then you read the voltage with analogRead() on an ADC1 pin. LDRs are cheap and easy to use for “dark or bright” decisions. They are not calibrated light meters.

Nine GL5528 photoresistors on a breadboard, each a small round disk with an orange zigzag track between two metal contacts
GL5528 photoresistors on a breadboard. The orange zigzag is the light-sensitive CdS track.
Photo: Retired electrician, CC0 1.0

Voltage divider and ADC

The bold curve is the selected fixed resistor. The thin curves are the other resistors. A good resistor gives a steep curve in the light range that you care about. A flat part of the curve means that the ADC cannot see light changes there.

“Raw reading” is the analogRead() value. “Calibrated mV” is the analogReadMilliVolts() value. The simulator adds a small amount of ADC noise, as a real ESP32 has.

How it works

Resistance against light

The relation is not linear. It is approximately a power law: R ≈ R10 × (lux / 10)−γ. For the GL5528, R10 is 8–20 kΩ and γ is about 0.6–0.7. On a log–log graph, this is a straight line. Each part is different, so two LDRs from the same bag can give different readings in the same light.

The voltage divider

Connect the LDR from 3.3 V to the GPIO, and the fixed resistor from the GPIO to GND. Then
V = 3.3 V × Rfixed / (Rfixed + RLDR).
More light gives a lower RLDR, so V increases. If you swap the two parts, more light gives a lower voltage.

Choose the fixed resistor

Find the LDR resistance at the darkest level (Rdark) and the brightest level (Rbright) that you care about. Use Rfixed ≈ √(Rdark × Rbright). This gives the largest voltage change in that range. For indoor light with a GL5528, 10 kΩ is a good start. For very dark scenes, use 47–100 kΩ. For sunlight, use 1 kΩ.

The ESP32 ADC

analogRead() gives 12-bit values from 0 to 4095. With the default attenuation, full scale is about 3.1 V. The ADC is not linear near 0 V and near the top, and each chip is a little different. analogReadMilliVolts() uses the factory calibration and returns millivolts. Refer to Quantization and Analog inputs.

Use ADC1 pins

ADC2 (GPIO 0, 2, 4, 12–15, 25–27) does not operate while Wi-Fi is on. Use an ADC1 pin: GPIO 32, 33, 34, 35, 36 (VP) or 39 (VN). The input-only pins 34–39 are good for analog inputs.

Slow response

A CdS cell needs tens of milliseconds to follow a change. The GL5528 datasheet gives about 20 ms (to light) and 30 ms (to dark). After a long time in bright light, the dark resistance can need some seconds to come back. Do not use an LDR for fast signals, for example data from an IR remote. For that, refer to IR remote.

For real lux values, use a light sensor. An LDR is good for “darker or brighter”. It cannot give accurate lux, because each part, the temperature and the color of the light change the reading. For calibrated measurements, use a digital light sensor such as the BH1750.

Wiring

ESP32 3V3 GPIO 34 GND GPIO 4 LDR GL5528 10 kΩ 100 nF (optional) 220 Ω LED 0–3.3 V
The LDR goes from 3V3 to GPIO 34. The 10 kΩ resistor goes from GPIO 34 to GND. More light gives a higher reading. The 100 nF capacitor is optional. It decreases noise on long wires. The LED on GPIO 4 is for the night-light sketch.

Connections

PartFromTo
LDR3V3GPIO 34
10 kΩ resistorGPIO 34GND
100 nF capacitor (optional)GPIO 34GND
220 Ω + LEDGPIO 4GND (LED cathode)

An LDR has no polarity. You can connect it in either direction. Connect the LDR to the 3V3 pin. The voltage at the GPIO must not be more than 3.3 V. Refer to GPIO.

Breakout modules

Small “LDR modules” have the LDR, a resistor and sometimes a comparator with a blue trim potentiometer. Use the AO pin for an analog value. The DO pin gives only HIGH/LOW at the knob setting. Supply the module from 3V3, so its outputs stay at 3.3 V or less.

Build steps

  1. Put the parts on the breadboardConnect the LDR and the 10 kΩ resistor as shown in the diagram.
  2. Upload sketch 1Open the Serial Plotter (Tools → Serial Plotter) at 115200 baud. Cover the LDR and look at the lines change.
  3. Record the rangeCover the LDR with your hand. Then point a phone flashlight at it. Write down the lowest and highest values.
  4. Change the resistor if necessaryIf most values are near 0 or near 4095, use a different fixed resistor. Use the simulator above to find one.
  5. Set the thresholdPut the threshold between the “dark” and “bright” values. Add hysteresis (sketch 2).

Troubleshooting

  • The reading is always 0: the LDR is not connected to 3V3, or you read the wrong pin.
  • The reading is always 4095: the fixed resistor is missing or too large, or the light is too bright for the resistor.
  • The reading does not change with Wi-Fi on: you use an ADC2 pin. Move the wire to GPIO 32–39.
  • The reading jumps by ±20: this is normal ADC noise. Average 16 or more readings. Add the 100 nF capacitor.
  • The light flickers at night: your LED shines on the LDR. Turn the LDR away from the LED, or use hysteresis.

Code

These sketches use only the Arduino-ESP32 core (version 3.x). Install it as shown in IDE setup.

1 · Read the voltage and the LDR resistance

Use the Serial Plotter with this sketch. In the Arduino IDE, select Tools → Serial Plotter and set 115200 baud. Move your hand over the LDR and look at the lines go up and down. Each line has a name (raw, mV, LDR_kohm). Click a name in the plotter to hide or show its line. Close the Serial Monitor first: only one window can use the port.

ldr_read.ino


              const int LDR_PIN = 34;            // ADC1 pin
              const float R_FIXED = 10000.0;     // ohms, from GPIO 34 to GND
              const float VCC_MV = 3300.0;

              void setup() {
                Serial.begin(115200);
                analogReadResolution(12);        // 0..4095 (the default)
              }

              void loop() {
                // Average 16 readings to decrease noise.
                uint32_t sumMv = 0;
                for (int i = 0; i < 16; i++) sumMv += analogReadMilliVolts(LDR_PIN);
                float mv = sumMv / 16.0;

                int raw = analogRead(LDR_PIN);   // 0..4095

                // Divider: V = VCC * R_FIXED / (R_FIXED + R_LDR)
                float rLdr = (mv > 1) ? R_FIXED * (VCC_MV - mv) / mv : 1e7;

                // Serial Plotter format: name:value pairs, a comma between
                // the pairs, one line for each sample. No other text.
                Serial.printf("raw:%d,mV:%.0f,LDR_kohm:%.1f\n",
                              raw, mv, rLdr / 1000.0);
                delay(50);                       // 20 samples each second
              }
            

The resistance is in kΩ, so its line is near the bottom in bright light and goes up quickly in the dark. To see one line at full height, hide the other two. In the Serial Monitor, the same output shows as text, for example raw:1268,mV:1012,LDR_kohm:22.6.

2 · Night light with hysteresis

Two thresholds stop the LED from flickering when the light is near one threshold.

ldr_night_light.ino


              const int LDR_PIN = 34;
              const int LED_PIN = 4;
              const int DARK_ON  = 850;           // LED on below this reading
              const int LIGHT_OFF = 1150;         // LED off above this reading
              bool ledOn = false;

              int readAverage(int pin, int n) {
                long sum = 0;
                for (int i = 0; i < n; i++) sum += analogRead(pin);
                return sum / n;
              }

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

              void loop() {
                int level = readAverage(LDR_PIN, 16);
                if (!ledOn && level < DARK_ON) {
                  ledOn = true;
                  digitalWrite(LED_PIN, HIGH);
                  Serial.println("Dark: LED on");
                } else if (ledOn && level > LIGHT_OFF) {
                  ledOn = false;
                  digitalWrite(LED_PIN, LOW);
                  Serial.println("Bright: LED off");
                }
                delay(100);
              }
            

3 · Automatic brightness with PWM

The LED is bright in the dark and dims in bright light. The sketch uses the LEDC API of core 3.x (ledcAttach, ledcWrite). Refer to PWM & LEDs. A smoothing filter makes the changes slow and soft.

ldr_auto_brightness.ino


            const int LDR_PIN = 34;
            const int LED_PIN = 4;
            const int DARK_MV = 300;     // record these two values with sketch 1
            const int BRIGHT_MV = 2500;
            float smoothMv = 0;

            void setup() {
              ledcAttach(LED_PIN, 5000, 8);        // 5 kHz, 8-bit duty (0..255)
              smoothMv = analogReadMilliVolts(LDR_PIN);
            }

            void loop() {
              int mv = analogReadMilliVolts(LDR_PIN);
              smoothMv += 0.05 * (mv - smoothMv);  // low-pass filter
              int clamped = constrain((int)smoothMv, DARK_MV, BRIGHT_MV);
              int duty = map(clamped, DARK_MV, BRIGHT_MV, 255, 10);  // dark = bright LED
              ledcWrite(LED_PIN, duty);
              delay(20);
            }
          

Resources