python
import RPi.GPIO as GPIO
import time
# Set up GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# Define pin numbers
ldr_pin = 18 # LDR connected to GPIO 18
led_pin = 23 # LED connected to GPIO 23
# Set up pin modes
GPIO.setup(ldr_pin, GPIO.IN)
GPIO.setup(led_pin, GPIO.OUT)
try:
while True:
ldr_value = GPIO.input(ldr_pin) # Read LDR value
if ldr_value == GPIO.LOW:
GPIO.output(led_pin, GPIO.HIGH) # Turn on LED when it's dark
else:
GPIO.output(led_pin, GPIO.LOW) # Turn off LED when it's bright
time.sleep(0.1) # Wait for a short time before reading again
except KeyboardInterrupt:
GPIO.cleanup() # Clean up GPIO on keyboard interrupt