Open 4.2Trigger mode.py and click .
'''
* Filename : Trigger mode
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin
import time
Trig = Pin(21, Pin.OUT)
Echo = Pin(27, Pin.IN)
INA = Pin(14, Pin.OUT)
INB = Pin(15, Pin.OUT)
distance = 0 # set initial distance to 0
soundVelocity = 340 #Set the speed of sound.
def getDistance():
# maintain Trig pin at high level for 10us to enable the ultrasonic sensor
Trig.value(1)
time.sleep_us(10)
Trig.value(0)
#Start counting, record the initial time when ultrasonic waves starts to transmit
while Echo.value() == 0:
Start = time.ticks_us()
#record the time when the ultrasonic echo is received
while Echo.value() == 1:
Stop = time.ticks_us()
#total time = the receiving time - the initial time
Time = time.ticks_diff(Stop,Start)
# Calculat the distance according to the formula: distance(m)
# distance value devide by 100: distance(cm)
distance = Time * soundVelocity //2 // 10000
#return the distance value in cm
return distance
while True:
Distance = getDistance()
print('Distance: ', Distance, 'cm')
time.sleep_ms(500)
if Distance < 10:
INA.value(0)
INB.value(1)
time.sleep(1)
else:
INA.value(0)
INB.value(0)
time.sleep(1)
Conceive:
Initialization: set pins of the ultrasonic sensor and the 130 motor.
Loop:
① Print the detected distance value every 500ms.
② Determine whether the value is less than 10 (this threshold is adjustable according to needs).
distance < 10: the fan starts to rotates.
distance >= 10: the fan does not work.