'''
 * Filename    : Ultraviolet detection
 * Thonny      : Thonny 4.1.4
 * Auther      : http//www.keyestudio.com
'''
from machine import ADC,Pin
import time

# confugure ADC, range of 0-3.3V
# define pins io26,io27,io28,io29 to ADC channel 0,1,2,3
ultraviolet = ADC(26)  #ultraviolet = ADC(0)
conversion_fator = 3.3 / 65535  #Voltage value of a single scale

red = Pin(13, Pin.OUT)

while True:
    ultraviolet_value = ultraviolet.read_u16()
    voltage = int(ultraviolet_value * conversion_fator * 1000)  #convert unit into mV
    print(voltage,'mV',end = '     ')
    # voltage < 50
    if voltage < 50:
        uv = 0
    # 50 < voltage < 227
    elif voltage < 227:
        uv = 1
    # 227 < voltage < 318
    elif voltage < 318:
        uv = 2
    # 318 < voltage < 408
    elif voltage < 408:
        uv = 3
    # 408 < voltage < 503
    elif voltage < 503:
        uv = 4
    # 503 < voltage < 606
    elif voltage < 606:
        uv = 5
    # 606 < voltage < 696
    elif voltage < 696:
        uv = 6
    # 696 < voltage < 795
    elif voltage < 795:
        uv = 7
    # 795 < voltage < 881
    elif voltage < 881:
        uv = 8
    # 881 < voltage < 976
    elif voltage < 976:
        uv = 9
    # 976 < voltage < 1079
    elif voltage < 1079:
        uv = 10
    # 1079 < voltage
    else:
        uv = 11
    time.sleep(0.1)
    print('uv Index = ',uv)
    if uv > 3:
        red.on()
    else:
        red.off()