On raspberry pi 1, raspbian stretch lite release 9.1 - kernel version 4.9.52+
I made a shell program to light up a led via raspberry pi's gpio (filename is led.sh). There's a part where I need to interact with some files:
function makeOn {
# status has value 1 if led is on and 0 if led is off
if [ $(status) -eq 1 ]; then
echo "led is already on"
else
#say we are using pin 18 and set it to output mode
echo "18" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio18/direction # this is line 38
# write output
echo "1" > /sys/class/gpio/gpio18/value # this is line 41
echo "led is on"
fi
}
I am running this as a user in the gpio group. These are the files I am trying to mess with in my program:
This is what happens when I run led.sh:
The weird thing is, I ran those commands on the shell one by one and no problem. But when I run a script that calls them, I get a permission denied even though I am in the gpio group. First I thought the shell might run commands as a special user and checked by adding an echo $EUID to the led.sh in several spots and they all returned my user id.
Why does this program have permission denied to those files and how do I give it permission/fix this?
Both value and direction files are created when the pin is exported in echo "18" > /sys/class/gpio/export
.
A small delay is required (ex: sleep 0.1
) after it so that the system has time "to properly create and set the file's permission".
A working example is:
function makeOn {
# status has value 1 if led is on and 0 if led is off
if [ $(status) -eq 1 ]; then
echo "led is already on"
else
# say we are using pin 18 and set it to output mode
echo "18" > /sys/class/gpio/export
# added to allow time for the file to be created before trying to use it
sleep 0.1
echo "out" > /sys/class/gpio/gpio18/direction
# write output
echo "1" > /sys/class/gpio/gpio18/value
echo "led is on"
fi
}