This one is short and sweet, based on the blinking LED example found here.
Here’s a shell script to read a GPIO and generate a square wave on the console:
#!/bin/sh
#
# Read a GPIO input
GPIO=$1
cleanup() { # Release the GPIO port
echo $GPIO > /sys/class/gpio/unexport
echo ""
echo ""
exit
}
# Open the GPIO port
#
echo "$GPIO" > /sys/class/gpio/export
echo "in" > /sys/class/gpio/gpio${GPIO}/direction
trap cleanup SIGINT # call cleanup on Ctrl-C
THIS_VALUE=`cat /sys/class/gpio/gpio${GPIO}/value`
LAST_VALUE=$THIS_VALUE
NEWLINE=0
# Read forever
while [ "1" = "1" ]; do
# next three lines detect state transition
if [ "$THIS_VALUE" != "$LAST_VALUE" ]; then
EV="|"
else
EV=""
fi
# "^" for high, '_' for low
if [ "1" = "$THIS_VALUE" ]; then
EV="${EV}^"
else
EV="${EV}_"
fi
echo -n $EV
# sleep for a while
sleep 0.05
# wrap line every 72 samples
LAST_VALUE=$THIS_VALUE
THIS_VALUE=`cat /sys/class/gpio/gpio${GPIO}/value`
NEWLINE=`expr $NEWLINE + 1`
if [ "$NEWLINE" = "72" ]; then
echo ""
NEWLINE=0
fi
done
cleanup # call the cleanup routine
I saved this as ~/read_gpio, did a ‘chmod 755 read_gpio’and invoked it to read the user button, GPIO 7:
root@beagleboard:~# ./read_gpio 7 _________________________________|^^^^|_____|^^^|_____________|^^^|___|^^^|_____ ____|^^|____|^^|____|^|________|^^^|_______|^^|____________|^^^|______|^^|_______ root@beagleboard:~#
Sampling at a 50ms interval appeared to catch most of my button pushes, even at an unreasonably high rate. A 100ms interval was too long and some of the faster button pushes were missed.