from machine import ADC, PWM, Pin, SoftI2C
import ssd1306
import uasyncio as asyncio
# 1. Setup I2C & OLED Display
i2c = SoftI2C(scl=Pin(27), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# 2. Setup Analog Sensors
light_sensor = ADC(Pin(32))
light_sensor.atten(ADC.ATTN_11DB)
potentiometer = ADC(Pin(14))
potentiometer.atten(ADC.ATTN_11DB)
# 3. Setup RGB LED (PWM)
led_red = PWM(Pin(17), freq=1000)
led_green = PWM(Pin(22), freq=1000)
led_blue = PWM(Pin(18), freq=1000)
# Shared Global Variables
current_light = 0
current_threshold = 0
current_bright = 0
def map_range(x, in_min, in_max, out_min, out_max):
"""Replicates Arduino's map() function"""
return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
async def read_sensors_task():
"""Reads LDR and Potentiometer continuously"""
global current_light, current_threshold
while True:
current_light = light_sensor.read_u16()
current_threshold = potentiometer.read_u16()
await asyncio.sleep_ms(20)
async def control_lighting_task():
"""Controls RGB LED brightness: High Lux -> Brightness 0, Pot == 0 -> Off"""
global current_light, current_threshold, current_bright
while True:
# Turn off LED completely if potentiometer is set to 0
if current_threshold == 0:
led_brightness = 0
else:
# Low ADC (~512) = Max Lux -> Brightness 0
# High ADC (~65000) = Min Lux -> Brightness 65535
led_brightness = map_range(current_light, 512, 65000, 0, 65535)
led_brightness = max(0, min(65535, led_brightness))
current_bright = led_brightness
# Drive RGB channels
led_red.duty_u16(led_brightness)
led_green.duty_u16(led_brightness)
led_blue.duty_u16(led_brightness)
await asyncio.sleep_ms(20)
async def update_display_task():
"""Renders live reading dashboard on OLED display"""
global current_light, current_threshold, current_bright
while True:
lamp_state = "ON" if current_bright > 0 else "OFF"
oled.fill(0)
oled.text("Adaptive Light", 0, 0)
oled.text(f"Light : {current_light}", 0, 12)
oled.text(f"Thresh: {current_threshold}", 0, 24)
oled.text(f"Bright: {current_bright}", 0, 36)
oled.text(f"Lamp : {lamp_state}", 0, 48)
oled.show()
await asyncio.sleep_ms(100)
async def main():
await asyncio.gather(
read_sensors_task(), control_lighting_task(), update_display_task()
)
asyncio.run(main())