目录
一、如何获取GPIO电平状态
1.将需要控制gpio导出
2.读取导出的gpio文件夹中的value文件即可获取电平状态
二、编程实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
static char gpio_path[100];
static int gpio_config(const char *attr,const char *val)
{
char file_path[100];
int len,fd;
//打开gpio配置文件
sprintf(file_path,"%s/%s",gpio_path,attr);
fd = open(file_path,O_WRONLY);
if(fd < 0)
{
perror("open error2");
return -1;
}
//将需要配置的属性写入相应文件夹
len = strlen(val);
if(write(fd,val,len) != len)
{
perror("write error2");
close(fd);
return -1;
}
}
int main(int argc,char* argv[])
{
char file_path[100];
char val;
int fd,ret;
//检验命令行传入参数
if(argc != 2)
{
fprintf(stderr,"usage:%s<gpio>\n",argv[0]);
exit(-1);
}
//判断需要操作的GPIO是否已经导出
sprintf(gpio_path,"/sys/class/gpio/gpio%s",argv[1]);
//查看目录下是否有该文件
ret = access(gpio_path,F_OK);
if(ret != 0) //目录下不存在该文件
{
int len,fd;
//打开export文件
fd = open("/sys/class/gpio/export",O_WRONLY);
if(fd < 0)
{
perror("open error1");
exit(-1);
}
len = strlen(argv[1]);
//导出gpio
if(write(fd,argv[1],len) != len)
{
perror("write error1");
close(fd);
exit(-1);
}
close(fd);
}
//配置为输入模式
ret = gpio_config("direction","in");
if(ret < 0)
{
fprintf(stderr,"配置成输入模式出错!!!\n");
exit(-1);
}
//配置极性
ret = gpio_config("active_low","0");
if(ret < 0)
{
fprintf(stderr,"配置极性出错!!!\n");
exit(-1);
}
//配置为非中断模式
ret = gpio_config("edge","none");
if(ret < 0)
{
fprintf(stderr,"配置非中断模式出错!!!\n");
exit(-1);
}
//读取GPIO电平状态
sprintf(file_path,"%s/%s",gpio_path,"value");
//只读打开文件
fd = open(file_path,O_RDONLY);
if(fd < 0)
{
perror("open error3");
exit(-1);
}
ret = read(fd,&val,1);
if(ret < 0)
{
perror("read error");
close(fd);
exit(-1);
}
printf("value:%c\n",val);
close(fd);
exit(0);
}
三、运行测试
将生成的可执行文件放在开发板根文件系统中,使用命令 ./gpio_inAPP 1 即可读取电平状态,运行结果为高电平。
tips:结果为高电平是因为我给开发板gpio1引脚连接到了开发板3.3V的引脚上,默认没连接到3.3V的时候电平状态为低电平。
四、作者自述
记录生活