This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

How to Cross-compile and Access GPIOs in Linux

Dear all:

I use community Linux 2.6.33-rc4 on omapl137 custom board. I enabled gpio support from make menuconfig as following:

device drivers

-> * GPIO support

    -> * /sys/class/gpio/... (sysfs interface)

After linux build & running, I can't see any directory or file naming gp*  located in target /sys/class.

Question 1: Is the gpio function setting correctly or is there any menu item I should enabled also to use the gpio function?

Next I try to write a gpio_test app to  check gpio status. The program is shown below:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/gpio.h>

int main()
{
    int    i,iPin;

    printf("\n");

    for(i=0;i<200;i++){
        iPin = gpio_is_valid(i);
        if(iPin != 0) printf("gpio %3d is valid\n",i);
    }
    printf("test over ...\n");
    return 0;
}

However this program can't compile successfully due to compiler can't find include file gpio.h.

Question 2: Should I  include the "gpio.h" directly by  -I option ( I know where the gpio.h located) or I should collect the gpio.h file into a specific directory or there is some methods like "make install" ... to collect all the necessary include files and libraries to somewhere?

Thanks for any idea.

 

  • Your C code attempts to use kernel level functions in a user-space program. Unless you building a loadable module, it is not possible to call those functions. The GPIO sysfs interface is accessed though files at /sys/class/gpio. This forum has a lot of examples. A brief shell command line example below. Usually everybody writes C code wrappers to read and write to those files.

    #---------------
    # Output example
    # Go to sysfx directory
    cd /sys/class/gpio

    # Export a specific GPIO. This will create gpioN subdirectory,
    echo 4 > export

    # Change to the gpioN subdirectory,
    cd gpio4

    # Set the direction of the GPIO to output
    echo out > direction

    # Toggle the level
    echo 1 > value
    echo 0 > value

    # Go back and unexport the GPIO. This will remove  gpioN subdirectory,
    cd ..
    echo 4 > unexport

    #---------------
    # Input example
    # Go to sysfx directory
    cd /sys/class/gpio

    # Export a specific GPIO. This will create gpioN subdirectory,
    echo 5 > export

    # Change to the gpioN subdirectory,
    cd gpio5

    # Set the direction of the GPIO to output
    echo in > direction

    # Read the level
    cat value

    # Go back and unexport the GPIO. This will remove  gpioN subdirectory,
    cd ..
    echo 5 > unexport