Skip to content

Instantly share code, notes, and snippets.

@kohlerdominik
Last active November 27, 2018 19:23
Show Gist options
  • Save kohlerdominik/7a025cba1de192a536cece06f2251700 to your computer and use it in GitHub Desktop.
Save kohlerdominik/7a025cba1de192a536cece06f2251700 to your computer and use it in GitHub Desktop.
Raspberry GPIO Helper with SYSFS Commands
#!/bin/sh
# $1 mode
# $2 gpio
# $3 write: value 0/off | 1/on
usage() {
# command help:
echo "
### GPIO Helper ###
USAGE: $0 read [gpio]
Read the gpio
USAGE $0 write [gpio] [value]
Set the GPIO to Value.
Values: off 0 | on 1
";
} # => usage()
set_export() {
# command set_export:
if [ ! -d /sys/class/gpio/gpio$1/ ]; then
echo "$1" > /sys/class/gpio/export
fi
} # => set_export()
set_direction() {
# command set_direction:
if [ "$(cat /sys/class/gpio/gpio$1/direction)" != "$2" ]; then
echo out > /sys/class/gpio/gpio$1/direction
fi
} # => set_direction()
read() {
# command read:
set_export "$1"
set_direction "$1" "in"
sleep 0.2
cat /sys/class/gpio/gpio$1/value
} # => read()
write() {
# command write:
set_export "$1"
set_direction "$1" "out"
sleep 0.2
if [ "$2" = "on" ] || [ "$2" = "1" ]; then
echo "1" > /sys/class/gpio/gpio$1/value
elif [ "$2" = "off" ] || [ "$2" = "0" ]; then
echo "0" > /sys/class/gpio/gpio$1/value
else
echo "Invalid argument for write mode"
fi
} # => write()
# get command name
cmd="$1"
# determine how we were called, then hand off to the function responsible
[ -n "$1" ] && shift # scrape off command
case "$cmd" in
read)
read "$@"
;;
write)
write "$@"
;;
""|help|-h|--help|--usage)
usage "$1"
exit 0
;;
*)
echo "Unknown command '$cmd'. Run without commands for usage help."
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment