Linux下操作GPIO

背景

嵌入式Linux下需要經常操作GPIO管腳,其中一種方式是使用/sys/文件系統下內核暴露出來的gpio文件。

代碼

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int set_gpio_val(int gpio, int val)
{
    int fd = -1;
    char buf[64] = {0};

    /* export */
    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (fd < 0) {
        printf("/sys/class/gpio/export open error\n");
        return -1;
    }
    sprintf(buf, "%d", gpio);
    write(fd, buf, 3);
    close(fd);

    /* set direction: in or out */
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
    fd = open(buf, O_WRONLY);
    if (fd < 0) {
        printf("open direction\n");
        return -1;
    }
    write(fd, "out", 3);
    close(fd);

    /* set value: 1 or 0 */
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
    fd = open(buf, O_WRONLY);
    if (fd < 0) {
        printf("set value error\n");
        return -1;
    }
    sprintf(buf, "%d", val ? 1 : 0);
    write(fd, buf, 1);
    close(fd);

    /* unexport */
    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (fd < 0) {
        printf("unexport error\n");
        return -1;
    }
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "%d", gpio);
    write(fd, buf, 3);

    return 0;
}
                                                                         
int main()
{
	/* lora aux: 205 + 232 */
	set_gpio_val(437, 0);

	return 0;
}

參考

https://blog.csdn.net/donglicaiju76152/article/details/49962631

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章