Bash controlled Raspberry Pi 3B relay hat

If you would like to control some electrical devices by switching them on and off then one possiblity is to use Rasberry Pi relay hat. It is from Waveshare/Botland and it fits on top of your Raspberry Pi. It contains 3 relays controllers with screw connectors.

Once you wire your devices you can even put it within DIN box like this one below. Be sure to be careful inserting micro SD card as this box fits tight and you can easily break card apart like I once did.

In order to control relay connectors first you export pins:

echo '20' > /sys/class/gpio/export
echo '21' > /sys/class/gpio/export
echo '26' > /sys/class/gpio/export

Then you set pin direction:

echo 'out' > /sys/class/gpio/gpio20/direction
echo 'out' > /sys/class/gpio/gpio21/direction
echo 'out' > /sys/class/gpio/gpio26/direction

And finally initialize relay state to switched off:

echo 1 > /sys/class/gpio/gpio20/value
echo 1 > /sys/class/gpio/gpio21/value
echo 1 > /sys/class/gpio/gpio26/value

You can change logic settings on board using jumpers. I have tested this setup 12V wiring but it is possible to have lower or even higher voltages. Also many devices require only to close loop without any current draw.

To expose your Raspberry Pi to network (for further control from OpenHAB for instance) you can set up simple HTTP server using Ruby and Sinatra library.

sudo apt update
sudo apt install git ruby
sudo gem install sintara
require 'sinatra'
set :bind, ''
get '/open' do
	system("echo 0 > /sys/class/gpio/gpio21/value")
	sleep 28
	system("echo 1 > /sys/class/gpio/gpio21/value")
	return 'Opened & Closed' 

To run:

ruby server.rb -o