Skip to content

Commit 01d1206

Browse files
Kaanoz-enKaan Ozen
andauthored
feat(vl53l1x): Add proximity alert example with buzzer. (#337)
* feat(vl53l1x): Add proximity alert example with buzzer. * fix(vl53l1x): Address review comments on proximity alert example. --------- Co-authored-by: Kaan Ozen <kaanozen@MacBook-Air-de-Kaan.local>
1 parent d1289b0 commit 01d1206

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""Proximity alert using VL53L1X distance sensor and buzzer.
2+
3+
Beeps the buzzer when an object is detected within 200 mm. The pitch
4+
increases as the object gets closer.
5+
"""
6+
7+
from time import sleep_ms
8+
9+
from machine import I2C, Pin
10+
from pyb import Timer
11+
from vl53l1x import VL53L1X
12+
13+
DISTANCE_THRESHOLD_MM = 200
14+
15+
# Sensor configuration
16+
i2c = I2C(1)
17+
tof = VL53L1X(i2c)
18+
19+
# Buzzer initialisation
20+
buzzer_tim = Timer(1, freq=1000)
21+
buzzer_ch = buzzer_tim.channel(4, Timer.PWM, pin=Pin("SPEAKER"))
22+
buzzer_ch.pulse_width_percent(0)
23+
24+
try:
25+
while True:
26+
distance = tof.read()
27+
print("Distance: {} mm".format(distance))
28+
29+
if distance < DISTANCE_THRESHOLD_MM:
30+
# Frequency ranging from 1500 (really close) to 500 (at 200mm)
31+
freq = 1500 - (distance * 5)
32+
# Security limits
33+
freq = max(500, min(1500, freq))
34+
35+
buzzer_tim.freq(freq)
36+
buzzer_ch.pulse_width_percent(50)
37+
else:
38+
buzzer_ch.pulse_width_percent(0)
39+
40+
sleep_ms(50)
41+
42+
except KeyboardInterrupt:
43+
pass
44+
finally:
45+
buzzer_ch.pulse_width_percent(0)

0 commit comments

Comments
 (0)