WarBerryPi – Adding a switch

On one of my devices, I installed a toggle switch to control the script execution. This allows me to first check on the LCD that the WarBerryPi has obtained a valid IP address before starting the execution. Installing the switch is an easy job, but it does require you to drill a hole in the case.

Picture2

The connection schematic is shown below. Of course, you can connect to another pin of your preference, but in my setup, I used PIN16, which corresponds to BCM23 on the Raspberry Pi.

Depending on the toggle switch you purchased, you need to identify which pin is the ground pin.

Then create the switch controller script. Change the pins and script location according to your setup. On the RPi3, I have the switch connected to PIN6 and PIN16, which correspond to GND and BCM23 respectively.

Picture3

Once you have installed the switch correctly, you need a way to control it. The controller script is a Python script, which in essence waits for a change on the GPIO PIN 23. As soon as it detects that, it will execute whatever command we want.

 cd /home/pi/WarBerry/warberry 
nano switch.py

And paste the following code.

#!/usr/bin/env python2.7  
import RPi.GPIO as GPIO  
import subprocess  
GPIO.setmode(GPIO.BCM)  
import os  
	  
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)  
	  
try:  
	GPIO.wait_for_edge(23, GPIO.FALLING)  	
	subprocess.call("sudo python warberry.py", shell = True)  
except KeyboardInterrupt:  
	GPIO.cleanup()  
GPIO.cleanup()  

Make any amendments you would like at Line 11, which is the part that controls which code will be executed. My example above will simply execute the warberry.py script without any additional parameters.

In order for the Python script to run, we need another controller script to call our Python script. This will be a very short Bash script.

 cd /home/pi/WarBerry/
nano start_switch.sh

And paste the following code.

#!/bin/sh   
cd /home/pi/WarBerry/warberry/   
sudo python switch.py  

Now for the start_switch.sh script to be called at boot time, so our system is waiting for a change on the pin. We need to put an entry inside the rc.local file as follows:

sudo nano /etc/rc.local

Scroll to the end and add the line

sudo bash /home/pi/WarBerry/start.sh & 

If you have named your files differently or used different pins assignment, now is the time to make the necessary changes.

And that’s it. Reboot your WarBerryPi and toggle the switch. Nothing will appear on the command line, because the process is running in the background. But if you run the command ps aux | grep warberry you should see a process running.