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!
Lesson 11: Photoresistor Module
In this lesson, you’ll learn how to connect a photoresistor module to the Raspberry Pi Pico W in order to measure light intensity. By linking the photoresistor to the analog input, you can read different analog values that correspond to varying light levels. This project is ideal for beginners and provides hands-on experience in utilizing analog inputs on the Raspberry Pi Pico W with MicroPython.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Universal Maker Sensor Kit |
94 |
You can also buy them separately from the links below.
Component Introduction |
Purchase Link |
|---|---|
Raspberry Pi Pico W |
|
Wiring
Code
import machine # Hardware control library
import time # Time control library
photoresistor = machine.ADC(26) # Initialize ADC on pin 26
while True:
value = photoresistor.read_u16() # Read analog value
print(value) # Print the value
time.sleep_ms(200) # Delay of 200 ms between reads
Code Analysis
Importing Libraries:
The code begins by importing necessary libraries. The
machinelibrary is used for controlling hardware components, and thetimelibrary is used for managing time-related tasks such as delays.import machine # Hardware control library import time # Time control library
Initializing the Photoresistor:
Here, we initialize the photoresistor. We use the
machine.ADCclass to create an ADC object on pin 26, where the photoresistor is connected. The ADC object will be used to read the analog values from the photoresistor.photoresistor = machine.ADC(26) # Initialize ADC on pin 26
Reading from the Photoresistor:
In this loop, the code continuously reads the analog value from the photoresistor using
photoresistor.read_u16(). This method reads the value as a 16-bit unsigned integer. The value is then printed to the console.while True: value = photoresistor.read_u16() # Read analog value print(value) # Print the value
Adding a Delay:
To prevent the code from running too quickly and flooding the console with data, a delay of 200 milliseconds is introduced after each read using
time.sleep_ms(200).time.sleep_ms(200) # Delay of 200 ms between reads