NetBSD-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: GPIO programs for Raspberry Pi in Python and C



On gen 14 22:30, Rocky Hotas wrote:
> 
> I never used ioctl(2) and maybe it's not immediate to integrate it with
> gpio(4). If you have some piece of code performing even a trivial
> operation like turning ON a pin, and you are OK with sharing it, it
> would be welcome.

It's easier than I thought, but I would like to share the procedure if
anyone else is wondering how to do it.

First, GPIO must be configured:

1) add a line `gpio=YES' in /etc/rc.conf;
2) specify in /etc/gpio.conf the pins you want to use. For example,

gpio0 21 set out just_a_test

See gpio.conf(5) for more information, and the following useful
page:

 <https://github.com/catskillmarina/netbsd-gpio-doc>

Then, add to your non-privileged user `_gpio' as a secondary group:

# usermod -G _gpio exampleuser

In fact, the device representing GPIO pins is:

$ ls -l /dev/gpio0
crw-rw-r--  1 root  _gpio  173, 0 Oct 19 04:20 /dev/gpio0

This will allow also `exampleuser' to read and write the configuration
of GPIO pins. Root can always do this, also with gpioctl(8).

See gpio(4) for the available macros and for the data structures to be
used. Also, obviously, see ioctl(2). A simple example:


#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/gpio.h>
#include <sys/ioctl.h>

struct gpio_info mytest;
struct gpio_req mystatus;
int myfd;

int main() {
        if ( (myfd = open("/dev/gpio0", O_RDWR)) == -1 ) {
                perror("Can't open GPIO device file\n");
                return 1;
        }

        if (ioctl(myfd, GPIOINFO, &mytest) == -1) {
                perror("ioctl GPIOINFO failed");
        }

        printf("Number of currently active GPIO pins: %d\n", mytest.gpio_npins);

        mystatus.gp_pin = 21;

        if (ioctl(myfd, GPIOREAD, &mystatus) == -1) {
                perror("ioctl GPIOREAD failed");
        }

        printf("Requested pin: %d\n", mystatus.gp_pin);
        printf("Name of requested pin: %s\n", mystatus.gp_name);
        printf("Value of requested pin: %d\n", mystatus.gp_value);

        mystatus.gp_value = GPIO_PIN_LOW;

        if (ioctl(myfd, GPIOWRITE, &mystatus) == -1) {
                perror("ioctl GPIOWRITE failed");
        }

        printf("Value of requested pin was: %d. It is now 0.\n", mystatus.gp_value);
}


The last statement can be verified, for example, from the root shell:

# gpioctl gpio0 21

Thanks again for your help!

Rocky


Home | Main Index | Thread Index | Old Index