4 # Copyright © 2016 František Kučera (frantovo.cz)
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, version 3 of the License.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # GPIO.sh is a set of functions for controlling GPIO pins of Raspberry Pi or similar computer
21 case $1 in 0|1|4|7|8|9|10|11|14|15|17|18|21|22|23|24|25)
28 # export -f _gpio_valid_port
29 # seq 0 30 | xargs -n1 bash -c 'printf "%4s" "$0: "; _gpio_valid_port $0 ; if [ $? -eq 0 ]; then echo "valid port number"; else echo; fi'
33 # TODO: $(date --rfc-3339=seconds) or ● ?
34 echo -e "\e[1;31m$1\e[0m"; > /dev/stderr;
38 echo -e "\e[2;33m$1 \e[0m"; > /dev/stderr;
42 # open (export) the port and set its direction
49 if [ $# -ne 2 ] || [[ "$direction" != @("in"|"out") ]]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port> <in|out>"; return 1; fi
50 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
52 if [ -d "/sys/class/gpio/gpio$port" ]; then
53 _gpio_log_warning "port $port is already exported → will just set direction: $direction";
55 echo "$port" > "/sys/class/gpio/export" || return 1;
58 echo "$direction" > "/sys/class/gpio/gpio$1/direction";
62 # close (unexport) the port and set its direction
67 if [ $# -ne 1 ]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port>"; return 1; fi
68 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
70 if [ -d "/sys/class/gpio/gpio$port" ]; then
71 echo "$port" > "/sys/class/gpio/unexport";
73 _gpio_log_error "port $port is not open";
78 # reads value of given port
83 if [ $# -ne 1 ]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port>"; return 1; fi
84 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
86 if ! cat "/sys/class/gpio/gpio$port/value"; then
87 _gpio_log_error "unable to read value of port $port";
92 # writes the value to given port
99 if [ $# -ne 2 ] || [[ "$value" != @("0"|"1") ]]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port> <0|1>"; return 1; fi
100 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
102 if ! echo "$value" > "/sys/class/gpio/gpio$port/value"; then
103 _gpio_log_error "unable to write value $value to port $port";