On a Raspberry Pi you can set the GPIO pins as an output or an input. An output or an input can be either high or low.
For example, to monitor the input state (high or low) of GPIO pin 26 you can check the value of /sys/class/gpio/gpio26/value
.
Now I want to monitor the input value of GPIO pin 26 continuesly and wrote this script.
#!/bin/bash
# return GPIO input status
# select pin
GPIO=26
# prepare the pin
if [ ! -d /sys/class/gpio/gpio${GPIO} ]; then
echo "${GPIO}" > /sys/class/gpio/export
fi
echo "in" > /sys/class/gpio/gpio"${GPIO}"/direction
# continuously monitor current value
while true; do
if [ 1 == "$(</sys/class/gpio/gpio"${GPIO}"/value)" ]; then
printf "high \r"
else
printf "low \r"
fi
done
This script works as expected. My main concern is that it uses 30% CPU of one of the cores continuesly.
How can I improve this method of monitoring my GPIO pins without such a high CPU usage? Can I skip cycles? Can I use some kind of 'device event manager' or 'system call manager' like udev
?
I really prefer to use Bash scripting only (I have seen some Python code that does this ;)
sleep
in there. You can use a decimal value in seconds, e.g.,sleep 0.05
.