-
Notifications
You must be signed in to change notification settings - Fork 22
Description
This isn't an issue with PiSharp, but more of a general discussion about creating programs that don't require to be run as root to access the GPIO.
I added the pi user to the gpio group, usermod -a -G gpio pi. Logged out and back in again and I was then able to control the GPIO via the command line without the need for sudo. However when I ran a program like LibGPIODemo1 (again without sudo) it would throw exceptions complaining about not having permission to access a pins files.
After doing a bit of digging it seems that when a pin is exported it takes a little while for the directory structure for that pin to be set up under /sys/class/gpio and for the group permission on that directory to be set to gpio. If a non-sudo program tries to access one of the pins' files before the group is changed a permission exception will be raised.
A solution which worked in my case was to put a call to Thread.Sleep(200 at the end of the Export() method in LibGpio.cs. This will of course slow down the starting up of a program by 200ms for each call to Export().
Another more involved option might be to split the SetupChannel() method into two methods one to set export the pin the other to set the direction (this is actually done but the methods are private). This way an application using the library could do all the exports first, wait 200ms, then setup the direction of the pin. This would only require one delay rather than a delay after every export.
There are of course issues with using a delay like this. For instance if other programs were running and putting load on the CPU it might take longer than 200ms to set up the group. It might be possible to wait on the creation of the pins direction file and the setting of it's group to gpio before continuing.
I'm new to the Raspberry Pi so it could be I'm missing something obvious. If I am please let us know, or if there are other ways to solve the permission issue I'd be interested in hearing about them as well.