Raspberry Pi Study Notes-using file IO to operate gpio sysfs

Source: Internet
Author: User
0 PrefaceThis article describes how to control the Raspberry Pi gpio port through the file IO sysfs. Control gpio through sysfs, first access the/sys/class/gpio directory, write the gpio number to the export file, so that the operation interface of this gpio is exposed from the kernel space to the user space, gpio operation interfaces include ction and value. Direction controls the gpio direction, while value controls the gpio output or obtains the gpio input. For Linux learning, you can start from the application. First, you don't have to worry about writing the Linux driver. First, you can get started with Linux.
[Same and different] This article is similar to [easyarm I. mx28 Study Notes-file IO operations gpio], and most of the Code is the same. File IO operations can effectively avoid platform differences. Although the easyarm im287 platform and Raspberry Pi are completely different, the gpio code through sysfs operations is roughly the same. Unlike easyarm im287, the cross-compilation tool is not used here. There is a GCC tool chain compilation link in Raspberry Pi to obtain executable files, while easyarm im287 cannot. Easyarm im287 uses the busybox instruction set, which is also different from the Debian Instruction Set in Raspberry Pi.
[Related blog] [easyarm I. mx28 learning notes-file IO operations gpio] [Raspberry Pi learning notes-shell script operations gpio] [Raspberry Pi learning notes-Cross-compilation tool chain] [Linux learning notes-Example: makefile index blog]
[Code repository] The code repository is located in Bitbucket -- RPI-gpio-sysfs. Use Hg to clone or directly download the zip package. Do not use any version of Internet Explorer to access the link, unless you know that the Internet Explorer you are using complies with the HTML5 standard. Google or Firefox browser is recommended for access. If the domestic dual-core browser is used, switch to the speed mode. Schematic diagram]
Figure 1 Link 1. Expose the gpio operation interface
static int gpio_export(int pin){    char buffer[BUFFER_MAX];    int len;    int fd;    fd = open("/sys/class/gpio/export", O_WRONLY);    if (fd < 0) {        fprintf(stderr, "Failed to open export for writing!\n");        return(-1);    }    len = snprintf(buffer, BUFFER_MAX, "%d", pin);    if (write(fd, buffer, len) < 0) {        fprintf(stderr, "Fail to export gpio!");        return -1;    }       close(fd);    return 0;}

2. Hide the gpio operation interface
static int gpio_unexport(int pin){    char buffer[BUFFER_MAX];    int len;    int fd;    fd = open("/sys/class/gpio/unexport", O_WRONLY);    if (fd < 0) {        fprintf(stderr, "Failed to open unexport for writing!\n");        return -1;    }    len = snprintf(buffer, BUFFER_MAX, "%d", pin);    if (write(fd, buffer, len) < 0) {        fprintf(stderr, "Fail to unexport gpio!");        return -1;    }       close(fd);    return 0;}

3. Configure the gpio direction
static int gpio_direction(int pin, int dir){    static const char dir_str[] = "in\0out";    char path[DIRECTION_MAX];    int fd;    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);    fd = open(path, O_WRONLY);    if (fd < 0) {        fprintf(stderr, "failed to open gpio direction for writing!\n");        return -1;    }    if (write(fd, &dir_str[dir == IN ? 0 : 3], dir == IN ? 2 : 3) < 0) {        fprintf(stderr, "failed to set direction!\n");        return -1;    }    close(fd);    return 0;}
[Simple description] [1] dir_str [dir = in? 0: 3], Dir = in? 2: 3 if the input is a constant macro in, take dir_str [0] = "in"; if the input constant macro is out, take dir_str [0] = "out ". Here, the "\ 0" in the array is cleverly used ".
4. Control gpio output
static int gpio_write(int pin, int value){    static const char values_str[] = "01";    char path[DIRECTION_MAX];    int fd;    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/value", pin);    fd = open(path, O_WRONLY);    if (fd < 0) {        fprintf(stderr, "failed to open gpio value for writing!\n");        return -1;    }    if (write(fd, &values_str[value == LOW ? 0 : 1], 1) < 0) {        fprintf(stderr, "failed to write value!\n");        return -1;    }    close(fd);    return 0;}

5. Obtain gpio Input
static int gpio_read(int pin){    char path[DIRECTION_MAX];    char value_str[3];    int fd;    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/value", pin);    fd = open(path, O_RDONLY);    if (fd < 0) {        fprintf(stderr, "failed to open gpio value for reading!\n");        return -1;    }    if (read(fd, value_str, 3) < 0) {        fprintf(stderr, "failed to read value!\n");        return -1;    }    close(fd);    return (atoi(value_str));}

6. gpio flip operation[Main function]
int main(int argc, char *argv[]){    int i = 0;        GPIOExport(POUT);    GPIODirection(POUT, OUT);        for (i = 0; i < 20; i++) {        GPIOWrite(POUT, i % 2);        usleep(500 * 1000);    }    GPIOUnexport(POUT);    return(0);}
[Makefile] -- the code tab here may display problems. Use the code repository as the main component.
# Executable File target = test # dependency target SRCS = gpio-sysfs.c # target file objs =$ (SRCS :. C =. o) # command compiler and options cc = gcccflags =-wall-STD = gnu99 $ (target): $ (objs) $ (CC)-O [email protected] $ ^ clean: rm-RF $ (target) $ (objs) # for continuous actions, clear and compile the Link first, and execute Exec: clean $ (target) @ echo to execute sudo. /$ (target) @ echo execution ends # The compilation rule [email protected] indicates the target file $ <indicates the first dependent file %. o: %. C $ (CC) $ (cflags)-O [email protected]-C $ <

[Upload the download link from Raspberry Pi and execute it.] The exec target in make exec makefile includes the following process: first clear the target and executable files, and then perform cross-compilation, finally, run the executable file with the super permission. For more information about how to use makefile, see [Linux study notes -- for example, makefile index blog]
7. Conclusion[1] Raspberry Pi differs from other embedded Linux development boards, and Raspberry Pi can also use sysfs to control gpio. [2] Raspberry Pi is cross-compiled in other aids, and can also be directly compiled on the platform.
8 references[1] RPI low-level peripherals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.