Make an LED automatically brighten in the dark and dim in bright light, using a photoresistor to sense ambient light — an automatic night lamp.
A photoresistor (LDR) is a light-sensitive resistor — its resistance drops as more light hits its surface, and rises in the dark.

Pairing it with a fixed resistor in a voltage divider turns that resistance change into a voltage change, which the ADC can read.

As ambient light changes, the photoresistor’s resistance changes, which shifts the voltage measured between it and the fixed resistor.

Disconnect all power before building the circuit. Reconnect once verified.

Connections:

File: 03_sensors/code/NightLamp.py
from machine import Pin,PWM,ADC
import time
pwm =PWM(Pin(14,Pin.OUT),1000)
adc=ADC(Pin(1))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
def remap(value,oldMin,oldMax,newMin,newMax):
return int((value)*(newMax-newMin)/(oldMax-oldMin))
try:
while True:
adcValue=adc.read()
pwmValue=remap(adcValue,0,4095,0,1023)
pwm.duty(pwmValue)
print(adcValue,pwmValue)
time.sleep_ms(100)
except:
adc.deinit()
pwm.deinit()
This is the exact same code as Soft Light — only the sensor wired to GPIO1 has changed.
03_sensors/code/.NightLamp.py.Since the circuit and code are logically identical to Soft Light, see Soft Light’s Code Explanation for a full walkthrough of remap() and the ADC → PWM pipeline. The only conceptual difference: the ADC value now reflects ambient light level instead of a knob’s position, and because the photoresistor’s resistance drops in bright light, more light produces a lower voltage on GPIO1 — which remaps to a lower PWM duty, dimming the LED in bright conditions and brightening it in the dark.
remap() → PWM code from Soft Light works unchanged with a different sensor, because both produce a 0–4095 ADC readingSee Class ADC and Class PWM(pin, freq) for the full API reference.
Adapted from Python_Tutorial.pdf Project 11.1