Open 4.6Ultraviolet detection.py and click .
'''
* Filename : Ultraviolet detection
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import ADC,Pin
import time
# configure ADC, range of 0-3.3V
# define 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()
Conceive:
When the UV index is within 0 ~ 2, the ultraviolet light is the weakest, and it does not have much effect on the human body. When the index increases to 3 ~ 4, the ultraviolet light is weak, but remember to wear sunscreen when going out.
Herein, we set the threshold of the UV index to 3. If the value exceeds 3, the red LED will light up to remind you to wear sunscreen. If the value does not reach 3, the LED will go off.
Code structure:
Initialization. Set the pins of the ultraviolet sensor and the traffic light module.
Loop.
if elif statement to determine the range of UV index, and output the value.
Determine whether the UV index exceeds 3.
UV index > 3: the red LED lights up as a reminder.
UV index ≤ 3: the red LED goes off.