[fpc-other] [fpc-pascal] Access GPIO pins on RPi2 without root?

Mark Morgan Lloyd markMLl.fpc-other at telemetry.co.uk
Sat Oct 10 15:27:24 CEST 2015


Bo Berglund wrote:

> Notice that the file used is /dev/mem
> 
> I don't know if there exists a user group named mem, but in any case the
> user pi is not member of any such group.
> Could this be the cause for root to be required?

No, if you do

$ ls -l /dev/mem
crw-r----T 1 root kmem 1, 1 Jan  1  1970 /dev/mem

I'll step through those bits in stages. First, I've prefixed the  ls 
command with $ since this is the prompt that was displayed. You don't 
enter that, it's just "unixspeak" shorthand showing that the command was 
entered by an unprivileged user.

Looking at the response, c shows that the thing you're looking at 
represents a character device. After that you get permissions: the user 
that owns it has rw- (i.e. read, write, no execute), the group has r-- 
(read only) and others have --- (i.e. no access at all). Skipping a bit, 
the owner is root and the group that has limited access is kmem.

If you look in /etc/group, you'll probably see that no users are in the 
kmem group. The RPi probably has something in the GUI to add/remove 
users from groups and that should be used if possible, but otherwise you 
can do it by editing BOTH /etc/group and /etc/gshadow CAREFULLY so that 
you see something like

kmem:x:15:pi

and

kmem:*::pi

respectively. DO NOT GET THIS WRONG, A SCREWED FILE HERE WILL LOCK YOU OUT.

Look, I've not got much time but going back to another point. The 
example at 
http://wiki.freepascal.org/Lazarus_on_Raspberry_Pi#1._Native_hardware_access 
shows the /sys tree being manipulated to get access to GPIO pins, and 
this sort of thing can be the easiest way to start off since you can 
twiddle things by hand. So initially in /sys/class/gpio we've got

$ ls -l
total 0
-rwxrwx--- 1 root gpio 4096 Jan  1  1970 export
lrwxrwxrwx 1 root gpio    0 Jan  1  1970 gpiochip0 -> ...
-rwxrwx--- 1 root gpio 4096 Jan  1  1970 unexport

If I now do

$ echo '17' >export

it creates a new entry

lrwxrwxrwx 1 root gpio    0 Oct 10 13:18 gpio17 -> ...

If I cd into gpio17 there are various things exposed, /but/ you'll see 
that they're owned by root... that's going to be a problem for 
production code but is still OK for getting things working by hand.

Switch to root using su [root password here] or sudo su [your password 
here] as appropriate. Note password prompt now ends in #

# cat direction
in
# echo 'out' >direction
# cat direction
out

and so on.

I'll try to keep an eye on this ML, but our gateway rejects quite a lot 
of stuff /particularly/ if it's formatted as HTML or has an attachment.

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]


More information about the fpc-other mailing list