Skip to content

Instantly share code, notes, and snippets.

@CortesAguilar
Created October 16, 2025 23:22
Show Gist options
  • Select an option

  • Save CortesAguilar/d0ac7320e9d8a42cb6c2506df07732f0 to your computer and use it in GitHub Desktop.

Select an option

Save CortesAguilar/d0ac7320e9d8a42cb6c2506df07732f0 to your computer and use it in GitHub Desktop.
16 Medidor de distancia + alarma Alerta si un objeto se acerca demasiado.
from microbit import *
import music
# Umbral: menor luz => más "cerca" => alarma
threshold = 80 # 0 (oscuridad total) .. 255 (mucha luz)
alarm_on = True
def light_level():
# 0..255 (v2 y v1 lo estiman con la matriz LED)
return display.read_light_level()
def beep(dark):
# Más oscuro => más rápido y más agudo
freq = 600 + int(min(600, dark * 3))
dur = 100
music.pitch(freq, dur)
sleep(max(30, 200 - dark)) # más oscuro => menos espera
def show_level(lvl):
# Muestra 0..9 para rapidez
display.show(str(min(9, lvl // 26)))
while True:
lvl = light_level() # luz actual
dark = max(0, 255 - lvl) # "cercanía" por oscuridad
show_level(lvl)
if alarm_on and lvl < threshold:
beep(dark)
# Ajusta umbral: A baja, B sube
if button_a.was_pressed():
threshold = max(0, threshold - 5)
display.scroll("TH {}".format(threshold), wait=False)
if button_b.was_pressed():
threshold = min(255, threshold + 5)
display.scroll("TH {}".format(threshold), wait=False)
# A+B calibra al instante: fija umbral = luz actual - 5
if button_a.is_pressed() and button_b.is_pressed():
threshold = max(0, lvl - 5)
display.scroll("CAL", wait=False)
sleep(400)
# Logo toca para activar/desactivar alarma (micro:bit v2)
if hasattr(pin_logo, "is_touched") and pin_logo.is_touched():
alarm_on = not alarm_on
display.show(Image.YES if alarm_on else Image.NO)
sleep(250)
sleep(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment