from machine import Pin, ADC, SoftI2C, PWM
from time import sleep, time
from lcd_api import LcdApi
from i2c_api import I2cLcd
# Configuration
LDR_PIN = 34 # LDR Analog pin (GPIO34)
LED_PIN = 5 # LED pin (GPIO5)
SERVO_PIN = 18 # Servo control pin (GPIO18)
I2C_SDA = 21 # I2C SDA pin (GPIO21)
I2C_SCL = 22 # I2C SCL pin (GPIO22)
I2C_ADDR = 0x27 # LCD I2C address
LCD_ROWS = 2
LCD_COLS = 16
# Initialize I2C and LCD
i2c = SoftI2C(scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, LCD_ROWS, LCD_COLS)
# Initialize LDR (Light Dependent Resistor)
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB) # Full voltage range: 0-3.3V
# Initialize LED
led = Pin(LED_PIN, Pin.OUT)
# Initialize Servo
servo = PWM(Pin(SERVO_PIN), freq=100)
def set_servo_angle(angle):
# Convert angle (0-180) to duty cycle (40-118) for the servo motor
duty = int(20 + (angle / 180) * 78)
servo.duty(duty)
# Start a software-based clock
start_time = time()
# Main loop
while True:
# Read light level from LDR
light_level = ldr.read()
# Map light level (0-4095) to servo angle (0-180)
servo_angle = int((light_level / 4095) * 180)
set_servo_angle(servo_angle)
# Control the LED: Turn on only if servo angle is 0 degrees
led.value(1 if servo_angle == 0 else 0)
# Calculate elapsed time for a simple clock display (HH:MM:SS)
elapsed_time = int(time() - start_time)
hours = (elapsed_time // 3600) % 24
minutes = (elapsed_time % 3600) // 60
seconds = elapsed_time % 60
# Update LCD Display
lcd.clear()
lcd.putstr(f"Angle: {servo_angle} deg")
lcd.move_to(1, 0) # Move to second line
lcd.putstr(f"Time: {hours:02}:{minutes:02}:{seconds:02}")
# Print time to console (optional)
print(f"Current Time: {hours:02}:{minutes:02}:{seconds:02}")
# Delay before the next reading
sleep(0.5)