正点原子阿尔法获取GPIO电平状态

目录

一、如何获取GPIO电平状态

二、编程实现

三、运行测试

四、作者自述


一、如何获取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的时候电平状态为低电平。

四、作者自述

        记录生活

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值