背景
嵌入式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