Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

πŸ‘‰ Ready to explore and create with us? Click [here] and join today!

2.2.1 Photoresistor(MCP3008)

Note

../_images/mcp3008_and_adc0834.jpg

Depending on your kit version, please identify whether you have ADC0834 or MCP3008 and proceed with the matching section.

Introduction

Photoresistor is a commonly used component of ambient light intensity in life. It helps the controller to recognize day and night and realize light control functions such as night lamp. This project is very similar to potentiometer, and you might think it changing the voltage to sensing light.

Required Components

In this project, we need the following components.

../_images/list2_2.2.1_photoresistor1.png

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Raphael Kit

337

Raphael Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

GPIO Extension Board

BUY

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

MCP3008

-

Photoresistor

BUY

Schematic Diagram

T-Board Name

physical

WiringPi

BCM

SPICE0

pin24

10

8

SPIMOSI

pin19

12

10

SPIMISO

pin21

13

9

SPISCLK

pin23

14

11

GPIO22

pin15

3

22

../_images/schematic_2.2.1_photoresistor_mcp30081.png

Experimental Procedures

Step 1: Build the circuit.

../_images/july24_2.2.1_photoresistor_mcp30081.png

Step 2: Set up the SPI interface and install the spidev library (see SPI Configuration for detailed instructions). If you have already completed these steps, you can skip this.

Step 3: Go to the folder of the code.

cd ~/raphael-kit/python-pi5

Step 4: Run the executable file.

sudo python3 2.2.1-2_Photoresistor_zero.py

When the code is running, the brightness of the LED will change according to the light intensity sensed by the photoresistor.

Warning

If there is an error prompt RuntimeError: Cannot determine SOC peripheral base address, please refer to If gpiozero doesn’t work.

Code

Note

You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path like raphael-kit/python-pi5. After modifying the code, you can run it directly to see the effect.

#!/usr/bin/env python3
import spidev
import time
from gpiozero import PWMLED

# Initialize a PWM LED on GPIO pin 22
led = PWMLED(22)

# Initialize SPI communication (Bus 0, CE0 -> GPIO8)
spi = spidev.SpiDev()
spi.open(0, 0)  # Bus 0, CS0
spi.max_speed_hz = 1000000  # 1 MHz

# Function to read from MCP3008 channel (0–7)
def read_adc(channel):
    """
    Read analog value from MCP3008 (0–1023)
    """
    if channel < 0 or channel > 7:
        return -1
    # MCP3008 protocol: Start bit, Single-ended mode, Channel (3 bits), filler
    r = spi.xfer2([1, (8 + channel) << 4, 0])
    value = ((r[1] & 3) << 8) | r[2]
    return value

# Define a function for mapping values from one range to another
def MAP(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# Main loop for reading ADC value and controlling LED brightness
def loop():
    while True:
        # Read analog value from channel 0 of MCP3008
        analogVal = read_adc(0)
        print('value = %d' % analogVal)

        # Map 0–1023 to PWM range 0.0–1.0
        led.value = analogVal / 1023.0

        # Wait for 0.2 seconds
        time.sleep(0.2)

# Run the main loop and handle KeyboardInterrupt for graceful shutdown
try:
    loop()
except KeyboardInterrupt:
    led.value = 0  # Turn off LED before exiting

Code Explanation

  1. This segment imports the PWMLED class from the gpiozero library for controlling PWM LEDs, spidev for SPI communication with MCP3008, and time for executing sleep/delay operations.

    #!/usr/bin/env python3
    import spidev
    import time
    from gpiozero import PWMLED
    
  2. Initializes a PWM LED connected to GPIO pin 22, and sets up the SPI interface for MCP3008 (Bus 0, CE0). The SPI clock speed is set to 1 MHz.

    # Initialize a PWM LED on GPIO pin 22
    led = PWMLED(22)
    
    # Initialize SPI communication (Bus 0, CE0 -> GPIO8)
    spi = spidev.SpiDev()
    spi.open(0, 0)  # Bus 0, CS0
    spi.max_speed_hz = 1000000  # 1 MHz
    
  3. Defines a function to read from a specific MCP3008 ADC channel. It sends a 3-byte command over SPI and extracts a 10-bit value (0–1023) from the response.

    # Function to read from MCP3008 channel (0–7)
    def read_adc(channel):
        """
        Read analog value from MCP3008 (0–1023)
        """
        if channel < 0 or channel > 7:
            return -1
        # MCP3008 protocol: Start bit, Single-ended mode, Channel (3 bits), filler
        r = spi.xfer2([1, (8 + channel) << 4, 0])
        value = ((r[1] & 3) << 8) | r[2]
        return value
    
  4. Defines a helper function MAP() that maps a number from one range to another. This is useful for converting raw ADC values into a suitable PWM range.

    # Define a function for mapping values from one range to another
    def MAP(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
    
  5. This section implements a loop that repeatedly reads an analog value from channel 0 of the MCP3008, maps it to a PWM brightness value (0.0–1.0), and applies it to the LED. The loop pauses for 0.2 seconds between readings.

    # Main loop for reading ADC value and controlling LED brightness
    def loop():
        while True:
            # Read analog value from channel 0 of MCP3008
            analogVal = read_adc(0)
            print('value = %d' % analogVal)
    
            # Map 0–1023 to PWM range 0.0–1.0
            led.value = analogVal / 1023.0
    
            # Wait for 0.2 seconds
            time.sleep(0.2)
    
  6. Executes the loop and gracefully handles KeyboardInterrupt. When the user stops the program (Ctrl+C), the LED is turned off before exiting.

    # Run the main loop and handle KeyboardInterrupt for graceful shutdown
    try:
        loop()
    except KeyboardInterrupt:
        # Turn off LED before exiting
        led.value = 0