67 lines
1.6 KiB
Python
Executable File
67 lines
1.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import RPi.GPIO as GPIO
|
|
import time
|
|
import os
|
|
import sys
|
|
|
|
# --- Configuración del pin del botón ---
|
|
BOTON_PIN = 18
|
|
GPIO.setmode(GPIO.BCM)
|
|
GPIO.setup(BOTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
|
|
|
|
# --- Umbral en segundos para distinguir pulsación corta/larga ---
|
|
UMBRAL_LARGO = 2.0
|
|
|
|
def accion_corta():
|
|
print("Acción corta detectada: Apagando el sistema...")
|
|
time.sleep(1)
|
|
os.system("sudo shutdown -h now")
|
|
|
|
def accion_larga():
|
|
print("Acción larga detectada: Reiniciando el sistema...")
|
|
time.sleep(1)
|
|
os.system("sudo reboot")
|
|
|
|
def esperar_liberacion(pin):
|
|
"""
|
|
Espera a que el botón sea liberado (deje de estar presionado).
|
|
Incluye una pequeña pausa para evitar rebotes.
|
|
"""
|
|
while GPIO.input(pin) == GPIO.LOW:
|
|
time.sleep(0.01)
|
|
time.sleep(0.05) # Espera adicional para evitar rebote al soltar
|
|
|
|
def detectar_pulsacion():
|
|
"""
|
|
Detecta cuánto tiempo se mantiene presionado el botón.
|
|
"""
|
|
tiempo_inicio = time.time()
|
|
esperar_liberacion(BOTON_PIN)
|
|
tiempo_pulsado = time.time() - tiempo_inicio
|
|
return tiempo_pulsado
|
|
|
|
# --- Bucle principal ---
|
|
try:
|
|
print("Esperando pulsación del botón (GPIO 18)...")
|
|
while True:
|
|
if GPIO.input(BOTON_PIN) == GPIO.LOW:
|
|
print("Botón presionado")
|
|
duracion = detectar_pulsacion()
|
|
|
|
if duracion < UMBRAL_LARGO:
|
|
accion_corta()
|
|
else:
|
|
accion_larga()
|
|
|
|
time.sleep(0.1)
|
|
|
|
except KeyboardInterrupt:
|
|
print("\nPrograma interrumpido por el usuario.")
|
|
except Exception as e:
|
|
print(f"Error inesperado: {e}")
|
|
finally:
|
|
GPIO.cleanup()
|
|
sys.exit(0)
|
|
|