Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions lib/vl53l1x/examples/proximity_alert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Proximity alert using VL53L1X distance sensor and buzzer.

Beeps the buzzer when an object is detected within 200 mm. The pitch
increases as the object gets closer.
"""

from time import sleep_ms

from machine import I2C, Pin
from pyb import Timer
from vl53l1x import VL53L1X

DISTANCE_THRESHOLD_MM = 200

# Sensor configuration
i2c = I2C(1)
tof = VL53L1X(i2c)

# Buzzer initialisation
buzzer_tim = Timer(1, freq=1000)
buzzer_ch = buzzer_tim.channel(4, Timer.PWM, pin=Pin("SPEAKER"))
buzzer_ch.pulse_width_percent(0)

try:
while True:
distance = tof.read()
print("Distance: {} mm".format(distance))

if distance < DISTANCE_THRESHOLD_MM:
# Frequency ranging from 1500 (really close) to 500 (at 200mm)
freq = 1500 - (distance * 5)
# Security limits
freq = max(500, min(1500, freq))

buzzer_tim.freq(freq)
buzzer_ch.pulse_width_percent(50)
else:
buzzer_ch.pulse_width_percent(0)

Comment on lines +24 to +39
Copy link

Copilot AI Mar 30, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tof.read() can raise OSError("VL53L1X data ready timeout") (see lib/vl53l1x/vl53l1x/device.py:_ensure_data). If that happens while the buzzer is on, this script will exit without silencing it. Consider using a try: ... finally: (or catching Exception) around the loop to always set the buzzer duty back to 0 before exiting.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an excellent point, I had handled the KeyboardInterrupt to prevent the PWM from running indefinitely, but I completely missed the potential OSError from the I2C bus timeouts. Moving the cleanup code to a finally: block is the perfect way to guarantee the buzzer is silenced no matter how the script exits. I'm updating the structure right away.

sleep_ms(50)

except KeyboardInterrupt:
pass
finally:
buzzer_ch.pulse_width_percent(0)
Loading