1.GPIO输入
加入了些自己的注释
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
// 全局变量用于存储GPIO路径
static char gpio_path[100];
// 配置GPIO属性的函数
static int gpio_config(const char *attr, const char *val)
{
char file_path[100]; // 用于存储文件路径
int len; // 字符串长度
int fd; // 文件描述符
// 生成属性文件的完整路径
sprintf(file_path, "%s/%s", gpio_path, attr);
// 打开属性文件
if (0 > (fd = open(file_path, O_WRONLY))) {
perror("open error"); // 打开文件出错时输出错误信息
return fd;
}
len = strlen(val); // 获取值字符串的长度
// 写入值到属性文件
if (len != write(fd, val, len)) {
perror("write error"); // 写入出错时输出错误信息
close(fd); // 关闭文件
return -1;
}
close(fd); // 关闭文件
return 0;
}
int main(int argc, char *argv[])
{
char file_path[100]; // 用于存储文件路径
char val; // 用于存储读取的值
int fd; // 文件描述符
// 校验传参个数,必须是2个
if (2 != argc) {
fprintf(stderr, "usage: %s <gpio>\n", argv[0]); // 提示正确用法
exit(-1);
}
// 生成GPIO路径
sprintf(gpio_path, "/sys/class/gpio/gpio%s", argv[1]);
// 检查GPIO目录是否存在
if (access(gpio_path, F_OK)) { // 如果目录不存在,则需要导出
int len; // 字符串长度
// 打开导出文件
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error"); // 打开文件出错时输出错误信息
exit(-1);
}
len = strlen(argv[1]); // 获取GPIO编号字符串的长度
// 写入GPIO编号到导出文件
if (len != write(fd, argv[1], len)) { // 导出GPIO
perror("write error"); // 写入出错时输出错误信息
close(fd); // 关闭文件
exit(-1);
}
close(fd); // 关闭文件
}
// 配置GPIO为输入模式
if (gpio_config("direction", "in"))
exit(-1);
// 配置GPIO极性为默认(不反转)
if (gpio_config("active_low", "0"))
exit(-1);
// 配置GPIO为非中断方式
if (gpio_config("edge", "none"))
exit(-1);
// 读取GPIO电平状态
sprintf(file_path, "%s/%s", gpio_path, "value");
// 打开值文件
if (0 > (fd = open(file_path, O_RDONLY

最低0.47元/天 解锁文章
1265

被折叠的 条评论
为什么被折叠?



