Today I decided to play a bit with my Raspberry Pi and one of my Relay shields that I have for the Arduino.
I was surprised to see how easy it was to control and read the GPIOs on the Raspberry. So I decided to make it even easier by writing a simple bash script which I use to turn on and off relays from the shield.

This is the script:

#!/bin/bash

GPIO=11
if [ $# == 1 ]; then
        if ! [[ "$1" =~ ^[0-9]+$ ]]; then
                echo "Error: wrong pin format"
                echo "Usage: $0 [GPIO]"
                echo "GPIOs: [0-24]"
                exit
        fi
        GPIO=$1
fi

# export GPIO 11 to userspace if it isn't exported already
if [ ! -d /sys/class/gpio/gpio${GPIO} ]; then
        echo "Exporting GPIO $GPIO"
        echo $GPIO > /sys/class/gpio/export
        sleep 1
fi

if [ "$(</sys/class/gpio/gpio${GPIO}/direction)" != 'out' ]; then
        echo "Setting GPIO $GPIO to OUT"
        echo out > /sys/class/gpio/gpio${GPIO}/direction
fi

if [ "$(</sys/class/gpio/gpio${GPIO}/value)" == 1 ]; then
        echo "Set GPIO $GPIO OFF"
        echo 0 > /sys/class/gpio/gpio${GPIO}/value
else
        echo "Set GPIO $GPIO ON"
        echo 1 > /sys/class/gpio/gpio${GPIO}/value
fi

I decided to use GPIO 11 as default, because it is the closest to pin 25(ground). So it was easier to have the wires close to each other.


Comments are closed.

Posted by HackMan
Dated: 1st December 2012
Filled Under: Uncategorized