On/off switch and LED
Intro
This is a project to provide an on/off switch for the Raspberry Pi, which performs a clean shutdown when pressed, and a reboot when pressed again (i.e. when Pi is off). There is also a LED to indicate whether Pi is safe to switch off (i.e. down).
It requires a button (a momentary switch) and an LED - I used a switch which has an integral LED. There is also a bit of programming and sysadmin required.
Hardware
- parts required
- 1 momentary switch with integral LED, or switch and separate LED
- 1 330Ω resistor, or similar
- 4 M/F breadboard jumper wires, or similar
- My switch has 4 poles - 2 for the switch, 2 for the LED marked + and - (if you look very hard). The 330Ω resistor needs to soldered to the - LED pole. The male end of a jumper wire is soldered to the other end of the resistor, and the male end of another jumper to the + LED pole. Without the resistor you will have no LED - too high a resistance resistor and you'll have a very dim LED. The remaining two jumper wires are soldered male end to the on/off switch poles. WE should now have switch/LED with four wires with female ends.
- Attach the four female ends to the following GPIO pins of the Pi
- + LED to TRX - GPIO 14 pin 8
- - LED to GROUND - e.g. GPIO pin 6
- the switch wires to SCL - GPIO3 pin 5 and to GROUND - e.g. pin 9
Software
The wake functionality relies on the fact that grounding SCL (GPIO3 pin 5) wakes the Pi up - at least it does on Pi3. Capturing grounding of SCL when the Pi is up can be used to trigger a shutdown request. The LED works by the fact that the TxD pin monitors the serial console so if the serial port is enabled and the Pi is on the TxD pin will be high.
- see [https://howchoo.com/g/mwnlytk3zmm/how-to-add-a-power-button-to-your-raspberry-pi]
- Program to listen for button press - listen-for-shutdown.py in /usr/local/bin
- #!/usr/bin/env python
- import RPi.GPIO as GPIO
- import subprocess
- GPIO.setmode(GPIO.BCM)
- GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
- GPIO.wait_for_edge(3, GPIO.FALLING)
- subprocess.call(['shutdown', '-h', 'now'], shell=False)
- create a service - listen-for-shutdown.service in /lib/systemd/system
- [Unit]
- Description=Bradnor MonitorService
- After=multi-user.target
- [Service]
- Type=idle
- StandardOutput=append:/var/log/monitor.log
- StandardError=append:/var/log/monitor.err
- ExecStart=/usr/bin/python3 /usr/local/bin/listen-for-shutdown.py
- [Install]
- WantedBy=multi-user.target
- and enable it
- sudo systemctl daemon-reload
- sudo systemctl enable listen-for-shutdown.service
- sudo reboot
- Program to listen for button press - listen-for-shutdown.py in /usr/local/bin
- see [https://howchoo.com/g/ytzjyzy4m2e/build-a-simple-raspberry-pi-led-power-status-indicator]
- edit the /boot/config.txt file
- and add
- enable_uart=1
- and add
- edit the /boot/config.txt file