Recreados todos los scripts

This commit is contained in:
root
2026-01-27 21:33:04 +01:00
parent 6a20265d6b
commit 5799a17507
13 changed files with 71 additions and 196 deletions

11
blink_led.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/bash
source /opt/raspberry_scripts/led_config.conf
trap "gpioset $CHIP $LINE=1; exit" SIGINT SIGTERM
while true; do
gpioset $CHIP $LINE=1
sleep 0.5
gpioset $CHIP $LINE=0
sleep 0.5
done

11
button-monitor.service Normal file
View File

@@ -0,0 +1,11 @@
[Unit]
Description=Monitor de botón para Apagado y Reinicio
After=multi-user.target
[Service]
Type=simple
ExecStart=/bin/bash /opt/raspberry_scripts/button_control.sh
Restart=always
[Install]
WantedBy=multi-user.target

21
button_control.sh Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/bash
source /opt/raspberry_scripts/led_config.conf
while true; do
gpiomon --num-events=1 --rising $CHIP $BTN_LINE > /dev/null
START_TIME=$(date +%s)
while [ $(gpioget $CHIP $BTN_LINE) -eq 1 ]; do
sleep 0.1
done
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
if [ $DURATION -ge 5 ]; then
reboot
elif [ $DURATION -ge 0 ]; then
poweroff
fi
done

View File

@@ -1,66 +0,0 @@
#!/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)

View File

@@ -1,12 +0,0 @@
[Unit]
Description=Script to reboot or shutdown by button in raspi
After=network.target
[Service]
ExecStart=/opt/raspberry_scripts/escucha.py
Type=simple
Restart=on-failure
[Install]
WantedBy=multi-user.target

View File

@@ -1,43 +0,0 @@
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import argparse
# Configuración del modo de los pines GPIO
GPIO.setmode(GPIO.BCM) # Usamos el esquema BCM, que hace referencia al número de pin GPIO
GPIO.setup(17, GPIO.OUT) # Configuramos el pin GPIO 14 como salida
# Función para hacer parpadear el LED
def parpadear_led(duracion_on, duracion_off, repeticiones):
for _ in range(repeticiones):
GPIO.output(17, GPIO.HIGH) # Encender el LED
time.sleep(duracion_on) # Mantener encendido
GPIO.output(17, GPIO.LOW) # Apagar el LED
time.sleep(duracion_off) # Mantener apagado
# Mantener el LED encendido al final del ciclo
GPIO.output(17, GPIO.HIGH)
# Definir los argumentos de línea de comandos
def parse_arguments():
parser = argparse.ArgumentParser(description="Hacer parpadear un LED en GPIO 14 de la Raspberry Pi.")
parser.add_argument('--on', type=float, default=0.5, help='Tiempo (en segundos) que el LED permanece encendido. (Default: 0.5)')
parser.add_argument('--off', type=float, default=0.5, help='Tiempo (en segundos) que el LED permanece apagado. (Default: 0.5)')
parser.add_argument('--reps', type=int, default=100, help='Número de veces que el LED parpadeará. (Default: 10)')
return parser.parse_args()
# Ejecución del script
if __name__ == "__main__":
# Parsear los argumentos desde la línea de comandos
args = parse_arguments()
try:
# Llamar a la función con los argumentos pasados desde la línea de comandos
parpadear_led(args.on, args.off, args.reps)
except KeyboardInterrupt:
print("Saliendo del programa...")
GPIO.output(17, GPIO.HIGH)
finally:
GPIO.output(17, GPIO.HIGH) # Restablecer la configuración de los pines GPIO al finalizar el script

13
led-off.service Normal file
View File

@@ -0,0 +1,13 @@
[Unit]
Description=Apaga el LED al apagar o reiniciar
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
[Service]
Type=oneshot
EnvironmentFile=/opt/raspberry_scripts/led_config.conf
ExecStart=/bin/sh -c '/usr/bin/gpioset ${CHIP} ${LINE}=0'
RemainAfterExit=yes
[Install]
WantedBy=shutdown.target reboot.target halt.target

12
led-on.service Normal file
View File

@@ -0,0 +1,12 @@
[Unit]
Description=Enciende el LED al arrancar
After=multi-user.target
[Service]
Type=oneshot
EnvironmentFile=/opt/raspberry_scripts/led_config.conf
ExecStart=/bin/sh -c '/usr/bin/gpioset ${CHIP} ${LINE}=1'
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target

3
led_config.conf Normal file
View File

@@ -0,0 +1,3 @@
CHIP=0
LINE=16
BTN_LINE=18

View File

@@ -1,12 +0,0 @@
[Unit]
Description=Ejecutar Mi Script en el Apagado
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
[Service]
Type=oneshot
ExecStart=/opt/raspberry_scripts/off.py
RemainAfterExit=true
[Install]
WantedBy=halt.target reboot.target shutdown.target

View File

@@ -1,12 +0,0 @@
[Unit]
Description=Mi Script de Inicio
After=network.target
[Service]
ExecStart=/opt/raspberry_scripts/on.py
Type=simple
Restart=on-failure
[Install]
WantedBy=multi-user.target

22
off.py
View File

@@ -1,22 +0,0 @@
#!/usr/bin/env python3
import RPi.GPIO as GPIO
# Configuraciones
LED_PIN = 16 # Número del pin BCM donde está conectado el LED
def main():
# Configuración del GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
# Apagar el LED
GPIO.output(LED_PIN, GPIO.LOW)
# Liberar los recursos del GPIO
GPIO.cleanup()
if __name__ == "__main__":
main()

29
on.py
View File

@@ -1,29 +0,0 @@
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import atexit
# Configuraciones
LED_PIN = 16 # Número del pin BCM donde está conectado el LED
def cleanup():
"""Apaga el LED y limpia los recursos de GPIO al salir."""
GPIO.output(LED_PIN, GPIO.LOW)
GPIO.cleanup()
def main():
# Configuración inicial del GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.HIGH)
# Registrar la función de limpieza al salir
atexit.register(cleanup)
# Aquí podrías dejarlo encendido o realizar otras tareas.
# Este script simplemente deja el LED encendido al iniciar.
# while True:
# time.sleep(60) # Evita que el script termine. Puedes ajustar esto o eliminarlo si solo necesitas encender el LED.
if __name__ == "__main__":
main()