1. gpio pins

./pic/pi3_gpio.png

2. gpio programming from bash

This code sets up pin 21 to be an output, sets the pin high and low.

# exports pin to userspace
echo "21" > /sys/class/gpio/export

# set pin 21 as an output
echo "out" > /sys/class/gpio/gpio21/direction

# set pin 21 to high
echo "1" > /sys/class/gpio/gpio21/value

# set pin 21 to low
echo "0" > /sys/class/gpio/gpio21/value

This code sets up pin 11 to be an input, then reads the value of the input.

# exports pin to userspace
echo "11" > /sys/class/gpio/export

# set pin 11 as an output
echo "in" > /sys/class/gpio/gpio11/direction

# get the value of pin 11
cat /sys/class/gpio/gpio11/value

3. sample code

#!/bin/sh

 pin1="11"
 pin2="21"

 init()
  {
   pinnr="$1"
   state="$2"
   if test -d /sys/class/gpio/gpio${pinnr}/
     then :
     else {
           echo ". init ${pinnr}"
           echo "${pinnr}" > /sys/class/gpio/export
           echo "${state}" > /sys/class/gpio/gpio${pinnr}/direction
          }
   fi
  }

 init ${pin1} in
 init ${pin2} out

 while :
  do {
      if cat /sys/class/gpio/gpio${pin1}/value | grep -q "1"
        then echo "1" | tee /sys/class/gpio/gpio${pin2}/value
        else echo "0" | tee /sys/class/gpio/gpio${pin2}/value
      fi
      sleep 0.5
     }
  done

 exit 0

4. rswitch

echo "13" > /sys/class/gpio/export
echo "in" > /sys/class/gpio/gpio21/direction
cat /sys/class/gpio/gpio13/value
vi /usr/lib/systemd/system/rswitch.service
#
[Unit]
Description="rswitch exec"

[Service]
ExecStart=/opt/rswitch/bin/rswitch
vi /usr/lib/systemd/system/rswitch.path
#
[Unit]
Description="rswitch monitor"

[Path]
PathModified=/sys/class/gpio/gpio13/
Unit=rswitch.service

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now rswitch.path rswitch.service
systemctl status rswitch.path rswitch.service
● rswitch.path - "rswitch monitor"
     Loaded: loaded (/lib/systemd/system/rswitch.path; enabled; vendor preset: enabled)
     Active: active (waiting) since Wed 2023-08-30 00:17:06 CEST; 1s ago
   Triggers: ● rswitch.service

Aug 30 00:17:06 srv006.d14.net systemd[1]: Started "rswitch monitor".

● rswitch.service - "rswitch exec"
     Loaded: loaded (/etc/systemd/system/rswitch.service; static)
     Active: inactive (dead) since Wed 2023-08-30 00:17:06 CEST; 1s ago
TriggeredBy: ● rswitch.path
    Process: 2963 ExecStart=/opt/rswitch/bin/rswitch (code=exited, status=0/SUCCESS)
   Main PID: 2963 (code=exited, status=0/SUCCESS)
        CPU: 26ms

Aug 30 00:17:06 srv006.d14.net systemd[1]: Started "rswitch exec".
Aug 30 00:17:06 srv006.d14.net systemd[1]: rswitch.service: Succeeded.