Skip to main content

Build. Learn.
Innovate.

Reading Analog Data from a Photoresistor

Written By:

Published on:

Project Overview

This project explores reading analog input by measuring light intensity using a photoresistor. Students will learn about Analog-to-Digital Converters (ADC) and how to interpret analog data in MicroPython.

Educational Goals

  • Understand analog vs. digital signals.
  • Learn how to use a photoresistor.
  • Introduce Analog-to-Digital Conversion (ADC).
  • Read and interpret analog sensor data using MicroPython.

Detailed Parts List

  • ESP32 – 1
  • Photo Resistor – 1
  • Resistor (10k ohm or similar) – 1
  • Breadboard – 1
  • Jumper Wires – Male-to-Male

Circuit Diagram Description

Create a voltage divider circuit. Connect one leg of the photoresistor to a 3.3V pin on the ESP32. Connect the other leg of the photoresistor to one leg of the resistor. Connect the other leg of the resistor to the GND pin on the ESP32. Connect an analog-capable GPIO pin on the ESP32 (e.g., GPIO34-GPIO39, GPIO25-GPIO27, GPIO12-GPIO15 depending on the specific ESP32 board) to the connection point between the photoresistor and the resistor. This point is where the analog voltage, which varies with light intensity, will be read by the ESP32’s ADC.

Software Functionality

The MicroPython code will configure the chosen GPIO pin as an analog input. It will then continuously read the analog value from the photoresistor using the ADC, convert the reading to a more meaningful range (if necessary), and print the value to the console.

Web Interface Features

A simple web interface could display the current light intensity reading numerically or on a basic graphical representation.

Implementation Steps

  • Set up the MicroPython environment on the ESP32.
  • Connect the photoresistor and resistor circuit on the breadboard.
  • Write the MicroPython code to read the analog input.
  • Upload and run the code on the ESP32.
  • Observe the printed sensor readings and see how they change with varying light conditions.

Extensions and Challenges

  • Use the photoresistor reading to control the brightness of an LED (using PWM, if available).
  • Build a simple light-activated switch that turns something on or off based on a light level threshold.
  • Log light intensity data over time.

Troubleshooting Guide

  • Incorrect readings: Ensure the voltage divider circuit is set up correctly. Verify the correct analog GPIO pin is used and configured as an ADC input in the code. Check the resistor value is appropriate for the photoresistor.
  • No readings: Confirm all connections are secure. Double-check the MicroPython code for errors.

Project Code

# This script reads analog data from a photoresistor and displays the raw
# ADC value on an OLED screen.

from machine import ADC, Pin, I2C  # Import ADC, Pin, and I2C
import time                       # Import the time module

# Import the SSD1306 OLED driver library.
# Make sure the ssd1306.py file is uploaded to your ESP32.
try:
    import ssd1306
except ImportError:
    print("ssd1306.py library not found. Please upload it to your ESP32.")
    # Exit or handle the error appropriately if the library is missing.
    # For this example, we'll assume the library exists and continue with a placeholder.
    class MockSSD1306:
        def __init__(self, width, height, i2c):
            print(f"MockSSD1306 initialized ({width}x{height}).")
        def fill(self, color): pass
        def text(self, text, x, y, color): pass
        def show(self): print(f"OLED display content not shown (ssd1306 library missing): {text}")
    ssd1306 = type('ssd1306', (object,), {'SSD1306_I2C': MockSSD1306})()


# --- Photoresistor Setup ---
# Define the GPIO pin number connected to the analog output of the photoresistor circuit.
# Replace 34 with the actual analog-capable GPIO pin you are using.
analog_pin = 34
adc = ADC(Pin(analog_pin))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

# --- OLED Setup ---
# Define the I2C pins for the OLED display.
# These are common default I2C pins on many ESP32 boards.
# Check your specific board's pinout if these don't work.
i2c_sda = 21
i2c_scl = 22

# Define the OLED screen dimensions.
oled_width = 128
oled_height = 32

# Create an I2C object.
# sda=Pin(i2c_sda) sets the SDA pin.
# scl=Pin(i2c_scl) sets the SCL pin.
# freq=400000 sets the I2C clock frequency (400kHz is common for OLEDs).
i2c = I2C(0, sda=Pin(i2c_sda), scl=Pin(i2c_scl), freq=400000)

# Create an SSD1306 OLED display object.
# oled_width, oled_height: The resolution of your display.
# i2c: The I2C object created above.
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

print("Starting photoresistor monitoring with OLED display...")

# Start an infinite loop to continuously read and display the sensor value.
while True:
    # Read the analog value from the photoresistor circuit.
    analog_value = adc.read()

    # --- Display on OLED ---
    # Clear the OLED display buffer.
    oled.fill(0) # 0 for black background

    # Display a title or label.
    oled.text("Light Level:", 0, 0, 1) # Text, x, y, color (1 for white pixels)

    # Display the analog value.
    # Convert the integer value to a string.
    oled.text(str(analog_value), 0, 16, 1) # Display value on the next line

    # Update the OLED display with the buffer content.
    oled.show()

    # Print to console as well (optional, for debugging).
    print("Analog Reading:", analog_value)

    # Wait for a short duration before taking the next reading.
    time.sleep(0.1)

# This loop will run forever.

# Troubleshooting notes for OLED:
# - Double-check the I2C SDA and SCL pin numbers for your specific ESP32 board.
# - Ensure the OLED is wired correctly to the ESP32 (VCC, GND, SDA, SCL).
# - Verify the ssd1306.py library is correctly uploaded to the ESP32's root filesystem.
# - If the display doesn't show anything, try checking the I2C connection using an I2C scanner script in MicroPython to see if the OLED is detected on the I2C bus.

STEM Benefits

Science:

  • Light and Resistance: Students explore the relationship between light intensity and the resistance of a photoresistor.
  • Electricity and Circuits: Understanding how the photoresistor acts as a variable resistor in a voltage divider circuit.

Technology:

  • Sensors: Using a photoresistor to detect a physical property (light).
  • Analog-to-Digital Conversion (ADC): Learning that the microcontroller needs to convert the continuous analog signal from the sensor into a digital value it can process.
  • Programming: Reading sensor data and displaying it.

Engineering:

  • Circuit Design and Building: Assembling a voltage divider circuit.
  • Sensor Interfacing: Connecting an analog sensor to a digital system.
  • Calibration (optional extension): Understanding that sensor readings might need to be calibrated for specific applications.

Mathematics:

  • Data Measurement and Interpretation: Reading numerical values from the sensor and understanding what they represent in terms of light intensity.
  • Ranges and Scaling: Working with the range of values from the ADC and potentially scaling them to a more meaningful range.

Projects
ShowCase

Real-World Projects
with Code & Hardware

Insights, Ideas
& How-Tos

Help, Support, and
Common Questions

What types of projects can I find on your website?

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.