from machine import Pin, SoftI2C, ADC, PWM
from i2c_lcd import I2cLcd
from time import sleep_ms
led = PWM(Pin(12), freq=10000, duty=0)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) #i2c, address, 2 rows, 16 cols
lcd.backlight_on()
lcd.clear()
lcd.putstr("ADC:\n")
lcd.putstr("Vol:")
ldr = ADC(Pin(35))
ldr.atten(ADC.ATTN_11DB)
def map(x, in_min, in_max, out_min, out_max):
return int((x - in_min)*(out_max - out_min)/(in_max - in_min) + out_min)
while True:
val = ldr.read() # reads 0-4096
duty = map(val, 0, 4095, 1023, 0) #duty writes 0-1023
lcd.move_to(5, 0)
lcd.putstr("%-5d" %(val))
lcd.move_to(5, 1)
voltage = str((val*5)/1023) # convert to voltage
lcd.putstr("%sV" %(voltage[0:3]))
led.duty(duty) #set duty cycle
print(val, "|", duty)
sleep_ms(100)