This is a quick guide to show you how you can write you own scripts using the Python API or general system scripts and have them run when certain power events occur on the PiJuice HAT such as low power, no power etc. In this example we will create a python script that will shutdown the Raspberry Pi and remove 5V GPIO power fro the PiJuice. In this instance the PiJuice will then enter a low powered state until it has wakeup. There are some important factors that need to occur when creating the script to be run such as, the user script must be run as a non-prviliaged user such as ‘pi’, the script must be executable by the system and include the shebang line of the programming language. This guide will show you how to do those things and get your user script working with the PiJuice software.
Step 1 – First you will need to make sure that you have the PiJuice software setup and installed on your Raspberry Pi with the latest Raspbian Desktop. You can get the latest version of Raspbian from https://www.raspberrypi.org/downloads/. To install the PiJuice software you need to open up a terminal window and type in the following commands:
sudo apt-get update sudo apt-get install pijuice-gui
Reboot your Raspberry Pi and you should see the PiJuice software running in the taskbar.
Step 2 – Now lets go ahead and create our script that we want run when the main power supply has been removed. Open up a terminal window and type in the following to create the file:
sudo nano shutdown.py
Then add the following to the python script:
#!/usr/bin/python3 from pijuice import PiJuice import os pijuice = PiJuice(1, 0x14) # Remove power to PiJuice MCU IO pins pijuice.power.SetSystemPowerSwitch(0) # Set wakeup pijuice.power.SetWakeUpOnCharge(0.0) # Remove 5V power to RPi after 60 seconds pijuice.power.SetPowerOff(60) # Shut down the RPi os.system("sudo halt")
Save the changes with CTRL+O & ENTER then exit with CTRL+X
Note: Very important that the first line of the code is the shebang line. This tells the system how to run the script. As we ar using the PiJuice Api in our script we need to use Python 3 programming language.
Step 3 – Make the script executable so we can run it from other programs. Open the terminal and enter the following command:
sudo chmod +x shutdown.py
You can check the user permissions of any file with command: