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; }
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; }
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; }
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; }
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)); }
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); }
# 可执行文件 TARGET=test # 依赖目标 SRCS=gpio-sysfs.c # 目标文件 OBJS = $(SRCS:.c=.o) # 指令编译器和选项 CC=gcc CFLAGS=-Wall -std=gnu99 $(TARGET):$(OBJS) $(CC) -o $@ $^ clean: rm -rf $(TARGET) $(OBJS) # 连续动作,先清除再编译链接,最后执行 exec:clean $(TARGET) @echo 开始执行 sudo ./$(TARGET) @echo 执行结束 # 编译规则 $@代表目标文件 $< 代表第一个依赖文件 %.o:%.c $(CC) $(CFLAGS) -o $@ -c $<
树莓派学习笔记——使用文件IO操作GPIO SysFs方式,布布扣,bubuko.com
原文地址:http://blog.csdn.net/xukai871105/article/details/38456801