---
title: "Bash controlled Raspberry Pi 3B relay hat"
url: https://michalasobczak.pl/posts/bash-controlled-raspberry-pi-3b-relay-hat.html
author: "Michał Sobczak"
description: "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."
published: 2023-12-13T08:12:32.000Z
updated: 2024-08-29T08:17:19.000Z
language: en
categories: ["Hobby"]
tags: ["Automation", "Raspberry Pi", "Ruby"]
license: CC BY-NC-ND 4.0 (https://creativecommons.org/licenses/by-nc-nd/4.0/)
---
# 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.

![](https://michalasobczak.pl/wp-content/uploads/2023/12/image.png)

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.

![](https://michalasobczak.pl/wp-content/uploads/2023/12/image-1.png)

In order to control relay connectors first you export pins:

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

Then you set pin direction:

```bash
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:

```bash
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.

```bash
sudo apt update
sudo apt install git ruby
sudo gem install sintara
```

```ruby
require 'sinatra'
set :bind, '0.0.0.0'
get '/open' do
	system("echo 0 > /sys/class/gpio/gpio21/value")
	sleep 28
	system("echo 1 > /sys/class/gpio/gpio21/value")
	return 'Opened &amp; Closed' 
end
```

To run:

```text
ruby server.rb -o 0.0.0.0
```
