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, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # GPIO.sh is a set of functions for controlling GPIO pins of Raspberry Pi or similar computer
22 case $1 in 0|1|4|7|8|9|10|11|14|15|17|18|21|22|23|24|25)
29 # export -f _gpio_valid_port
30 # 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'
34 # TODO: $(date --rfc-3339=seconds) or ● ?
35 echo -e "\e[1;31m$1\e[0m"; > /dev/stderr;
39 echo -e "\e[2;33m$1 \e[0m"; > /dev/stderr;
43 # open (export) the port and set its direction
50 if [ $# -ne 2 ] || [[ "$direction" != @("in"|"out") ]]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port> <in|out>"; return 1; fi
51 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
53 if [ -d "/sys/class/gpio/gpio$port" ]; then
54 _gpio_log_warning "port $port is already exported → will just set direction: $direction";
56 echo "$port" > "/sys/class/gpio/export" || return 1;
59 echo "$direction" > "/sys/class/gpio/gpio$1/direction";
63 # close (unexport) the port and set its direction
68 if [ $# -ne 1 ]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port>"; return 1; fi
69 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
71 if [ -d "/sys/class/gpio/gpio$port" ]; then
72 echo "$port" > "/sys/class/gpio/unexport";
74 _gpio_log_error "port $port is not open";
79 # reads value of given port
84 if [ $# -ne 1 ]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port>"; return 1; fi
85 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
87 if ! cat "/sys/class/gpio/gpio$port/value"; then
88 _gpio_log_error "unable to read value of port $port";
93 # writes the value to given port
100 if [ $# -ne 2 ] || [[ "$value" != @("0"|"1") ]]; then _gpio_log_error "usage: ${FUNCNAME[0]} <port> <0|1>"; return 1; fi
101 if ! _gpio_valid_port "$port"; then _gpio_log_error "invalid port number: $port"; return 1; fi;
103 if ! echo "$value" > "/sys/class/gpio/gpio$port/value"; then
104 _gpio_log_error "unable to write value $value to port $port";