Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

Using a Light Dependant Resistor (LDR) with the ESP32

Introduction

The basics of using an ADC are covered in another tutorial available here.

An LDR is an electronics component that has variable resistance dependant upon the intensity of light, this component's resistance will change with the level of illumination and can be used to sense light levels in an IOT project. An LDR is usually combined with a high value resistor to form a potential divider circuit (as shown in figure 1).

image

The potential divider

A potential divider circuit can comprise of two resistors in series, a voltage is applied at Vi and the circuit outputs a voltage that is a fraction of the input voltage at Vo. The amount the voltage is divided by is set by the values of R1 and R2. This can be calculated using the following equation:

image

So for example, if Vi = 10V, R1 = 10 kOhms, R2 = 5 kOhms then:

Vo = 10 x (10/10+5)

Vo = 10 x (10/15)

Vo = 10 x 0.666666

Vo = 6.66V

or alternatively if Vi = 10V, R1 = 10 kOhms, R2 = 10 kOhms then:

Vo = 10 x (10/10+10)

Vo = 10 x (10/20)

Vo = 10 x 0.5

Vo = 5V

The circuit divides the current by the proportion of R1 to R2.

Light Sensor

The potential divider circuit is used with sensors in a micro-controller circuit. The resistor R2 is replaced with a Light Dependant Resistor (LDR), as the level of illumination changes so does this devices' resistance which then changes the output voltage. If we connect Vout to a ADC on our ESP32 we can determine the light level by the voltage read.

image

In this circuit we form a potential divider with R1 and a LDR, Vin is supplied by our ESP32 and is 3.3V. Vout is fed directly to an ADC input pin (GPIO36).

A complete C++ program file called main.cpp is illustrated below, you can download a link to the actual file here.

// Dr Paul Lunn - Coventry University
// 9/07/2019
// ESP32 LDR Test

#include <Arduino.h>

const int SERIAL_0_SPEED = 115200;

// The setup() function is called once at the beginning of the program
void setup()
{
  Serial.begin(SERIAL_0_SPEED);     // begin serial link
  Serial.println("ESP32 LDR Test"); // print text onto screen via serial link
}

// The loop() function runs over and over again forever
void loop()
{
  int adc_reading = analogRead(36);             // use adc to read current value
  float light_level = (adc_reading / 4096.0) * 100; //convert adc to light level %

  // send results to serial link
  Serial.print("ADC reading = ");
  Serial.print(adc_reading);
  Serial.print(" Light Level = ");
  Serial.print(light_level);
  Serial.println("%\n");

  delay(1000); // wait for a second
}