Question

Working on a Raspberry Pi running Raspbian, I am trying to use driver-style C code to access the GPIOs. To export a GPIO pin to the userspace, I have to write the pin number to /sys/class/gpio/export. Is it possible to export multiple pins in a single file write? For example, I would like to do:

int initGPIO(int pins[], int numPins){
char buffer [50]; int numBytes; 

int fh = open("/sys/class/gpio/export", O_WRONLY);
if(fh<0) return -1;

int i;
numBytes = 0; 
sprintf(buffer, "");
for (i=0; i<numPins; i++){
    numBytes += sprintf(buffer, "%s\n%d", buffer, pins[i]);
}
return write(fh, buffer, numBytes);
close(fh);
}

When given [2,3,4] as an input array, this function only exports pin 2. Is there some way to write the pins into the export file such that they all get exported? Thanks for your time!

Was it helpful?

Solution

Nope :)

A quick solution may be to wrap your code in a loop, like so:

int initSingleGPIO(int pin)
{
    char buffer [50]; 
    int numBytes; 

    int fh = open("/sys/class/gpio/export", O_WRONLY);

    if(fh<0) return -1;

    sprintf(buffer, "");

    numBytes = sprintf(buffer, "%s\n%d", buffer, pin);

    int rv = write(fh, buffer, numBytes);

    close(fh);

    return rv;
}

int initGPIO(int pins[], int numPins)
{     
    int i;   
    for (i=0; i<numPins; i++)
    {
        initSingleGPIO(pins[i]);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top