参考网址:
Linux操作GPIO(文件IO方式)_Leon-CSDN博客
在Linux 中的应用层操作gpio的方法_仗劍走天涯-CSDN博客
位置
控制GPIO
的目录位于/sys/class/gpio
例子
1 2 3 4 5 6 7 8 9 10 11 12
| 1. 导出 /sys/class/gpio# echo 44 > export 2. 设置方向 /sys/class/gpio/gpio44# echo out > direction 3. 查看方向 /sys/class/gpio/gpio44# cat direction 4. 设置输出 /sys/class/gpio/gpio44# echo 1 > value 5. 查看输出值 /sys/class/gpio/gpio44# cat value 6. 取消导出 /sys/class/gpio# echo 44 > unexport
|
以echo的形式调用system函数进行操作,这种形式编程比较简单,结构比较清晰,如下
1 2 3 4 5 6
| void set_gpio64_low(void) { system("echo 64 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio64/direction"); system("echo 0 > /sys/class/gpio/gpio64/value"); }
|
通过文件的形式来调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> void initGpio(int n) { FILE * fp =fopen("/sys/class/gpio/export","w"); if (fp == NULL) perror("export open filed"); else fprintf(fp,"%d",n); fclose(fp); } void setGpioDirection(int n,char *direction) { char path[100] = {0}; sprintf(path,"/sys/class/gpio/gpio%d/direction",n); FILE * fp =fopen(path,"w"); if (fp == NULL) perror("direction open filed"); else fprintf(fp,"%s",direction); fclose(fp); } int getGpioValue(int n) { char path[64]; char value_str[3]; int fd; snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", n); fd = open(path, O_RDONLY); if (fd < 0) { perror("Failed to open gpio value for reading!"); return -1; } if (read(fd, value_str, 3) < 0) { perror("Failed to read value!"); return -1; } close(fd); return (atoi(value_str)); }
void setGpioValue(int n,int value) { char path[64]; char value_str[3]; int fd; snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", n); fd = open(path, O_WRONLY); if (fd < 0) { perror("Failed to open gpio value for writing!"); return; } if (value) strcpy(value_str,"1"); else strcpy(value_str,"0"); if (write(fd, value_str, 1) != 1) { perror("Failed to write value!"); return; } close(fd); } int main() { initGpio(18); setGpioDirection(18,(char*)"out"); while(1) { setGpioValue(18,0); printf("%d\n",getGpioValue(18)); sleep(1); setGpioValue(18,1); printf("%d\n",getGpioValue(18)); sleep(1); } return 0; }
|