Open 4.1Rain detection.py and click .
'''
* Filename : Rain detection
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin,PWM,ADC # Import ADC module
import time
# configure ADC, range of 0-3.3V
# define io26,io27,io28,io29 to ADC channel 0,1,2,3
Water = ADC(28) #Water = ADC(2)
conversion_fator = 3.3 / 65535 #Voltage value of a single scale
buzzer = PWM(Pin(3))
buzzer.freq(800)
# read the analog value every 0.1s, convert the analog value into voltage output.
while True:
Water_value = Water.read_u16()
voltage = Water_value * conversion_fator
print('ADC Value:',Water_value,' Voltage:',voltage,'V')
time.sleep(0.1)
if voltage > 1:
buzzer.duty_u16(5000)
else:
buzzer.duty_u16(0)
Conceive:
Set a threshold of voltage to determine the water volume. When there is too much water, the voltage exceeds the threshold, rain is detected, and the buzzer alarms. The buzzer will stop alarming when the voltage is lower than the threshold.
Code structure:
Initialization. Set the pins of the steam sensor and the passive buzzer, set the voltage value of a single scale, and set the frequency of the passive buzzer.
Loop.
Print the analog value and voltage of the steam sensor.
Determine whether the voltage exceeds 1 (Herein, we set 1 as the threshold, which is adjustable according to needs).
voltage > 1: buzzer alarms.
voltage ≤ 1: buzzer does not emit sounds.