Advertisement
belrey10

Day 10: Interactive Lighting – Combining Photoresistor, Buttons, and LEDs

Nov 5th, 2024 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. from machine import Pin, PWM, ADC
  2. import time
  3.  
  4. # Initialize the LED pins for PWM and digital output
  5. led_main = PWM(Pin(15))
  6. led_main.freq(1000)
  7. led1 = Pin(16, Pin.OUT)
  8. led2 = Pin(17, Pin.OUT)
  9.  
  10. # Initialize the photoresistor pin for ADC and button pins for input
  11. photoresistor = ADC(Pin(26))
  12. button1 = Pin(14, Pin.IN, Pin.PULL_DOWN)
  13. button2 = Pin(13, Pin.IN, Pin.PULL_DOWN)
  14.  
  15. # Variables to keep track of button states and modes
  16. mode = 0
  17. last_button1_state = 0
  18. last_button2_state = 0
  19.  
  20. while True:
  21.     # Read the value from the photoresistor
  22.     light_level = photoresistor.read_u16()
  23.    
  24.     # Map the light level to the PWM duty cycle (inverse relationship)
  25.     duty_cycle = 65535 - light_level
  26.    
  27.     # Set the main LED brightness
  28.     led_main.duty_u16(duty_cycle)
  29.    
  30.     # Read the button states
  31.     button1_state = button1.value()
  32.     button2_state = button2.value()
  33.    
  34.     # Toggle mode with button 1
  35.     if button1_state == 1 and last_button1_state == 0:
  36.         mode = (mode + 1) % 2
  37.    
  38.     # Control additional LEDs with button 2
  39.     if button2_state == 1 and last_button2_state == 0:
  40.         if led1.value() == 0:
  41.             led1.on()
  42.             led2.off()
  43.         else:
  44.             led1.off()
  45.             led2.on()
  46.    
  47.     # Update last button states
  48.     last_button1_state = button1_state
  49.     last_button2_state = button2_state
  50.    
  51.     # Mode-specific behaviors
  52.     if mode == 0:
  53.         # Mode 0: Main LED controlled by photoresistor, additional LEDs toggle with button 2
  54.         pass
  55.     elif mode == 1:
  56.         # Mode 1: Main LED blinks, additional LEDs toggle with button 2
  57.         led_main.duty_u16(32767)  # Set main LED to half brightness
  58.         time.sleep(0.5)
  59.         led_main.duty_u16(0)      # Turn off main LED
  60.         time.sleep(0.5)
  61.    
  62.     # Delay for a short period
  63.     time.sleep(0.1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement