webwinkelkeur logo

4.7 avg.

5101+ reviews
webwinkelkeur logoView all

5101+ reviews

5101+ reviews

Order by 16:00 for same day shipping

14 days return

EN

Individual

Business

GPIO Project 5 - LDR Introduction

Beginner
30 Minuten
114,90

In this project you will learn how to use an LDR (Light Dependent Resistor) to measure light intensity. The LDR changes its resistance depending on the amount of light, allowing you to use this data to, for example, automatically switch an LED on or off based on the light level.

Connection diagram

Connection diagram

Connect the LDR (light sensor):

  1. Connect one side of the LDR to 3.3V (pin 1). span>
  2. Connect the other side of the LDR:
    • Connect to GPIO 17 (pin 11).
    • Connect with a 10kΩ resistor to GND (pin 6).

Connect the LED:

  1. Long leg (anode):
    • Connect this to GPIO 27 (pin 13).
  2. Short leg (cathode):

Connect toGND (pin 6).

Pinout Reference

GPIO

Pin #

Function

Connection

GPIO 17Pin 11Analog InputLDR
GPIO 27Pin 13Digital outputLED
3.3VPin 1Power supply 3.3VLDR
GNDPin 6Earth (Ground)LDR & LED

Python-code in Thonny

Stap 1: Write the code

Open theThonny Python IDE and see the following code in:

from gpiozero import LED, MCP3008
from time import sleep

# LED en LDR koppelen
led = LED(27)             # LED op GPIO 27
ldr = MCP3008(channel=0)  # LDR op analoge invoer kanaal 0 (MCP3008)

while True:
    light_level = ldr.value  # Lees het lichtniveau (waarde tussen 0 en 1)
    print(f"Lichtniveau: {light_level:.2f}")
    
    if light_level < 0.5:  # Drempelwaarde: weinig licht
        led.on()
    else:
        led.off()
    
    sleep(0.5)

Step 2: Save the file

Click File > Save As and name the file ldr_intro.py.

Step 3: Run the script

Click the greenRun button (▶) at the top the Thonny interface.

How does it work?

  1. LDR (Light Dependent Resistor):
    • The LDR changes its resistance depending on the amount of light.
    • In this project, the MCP3008 is used to read the analog value of the LDR and convert it to a digital value between 0 and 1.
  2. Python program:
    • The script continuously reads the light intensity via the MCP3008.
    • If the light value falls below the threshold value (0.5), the LED switches on. Otherwise it remains off.

result

  • Low light: The LED turns on.
  • High light: The LED stays off.

The terminal displays the light intensity in real time.

Experiment

  1. Adjust threshold: Change the threshold value (0.5) in the code to adjust the sensitivity of the LED.
  2. Advanced applications:
    • Add a second LED that turns on when there is a lot of light.
    • Log the light intensity to a file for further analysis.