目录
一、GPIO介绍
1.属性介绍
进入/sys/class/gpio目录下,有7个文件夹,export和unexport文件夹用于导出gpio和将导出的gpio删除,需要控制某个gpio前需要将该gpio端口导出。
tips:使用完后将该导出的gpio删除
echo 0 > export //导出gpio0
echo 1 > export //导出gpio1
echo 1 > unexport //将导出的gpio1删除
2.gpio1文件介绍
(1)direction:配置 GPIO 引脚为输入或输出模式。
tips:"out"(输出模式)和"in"(输入模式)
(2)value:输出模式时,向 value 文件写入"0"控制 GPIO 引脚输出低电平,写入"1"则控制 GPIO 引脚输出高电平。输入模式时,读取 value 文件获取 GPIO 引脚电平状态。
(3)edge:控制中断的触发模式。
(4)active_low:这个属性文件用于控制极性
tips:
//active_low 等于 0 时
echo "1" > value #输出高
echo "0" > value #输出低
//active_low 等于1时
echo "1" > value #输出低
echo "0" > value #输出高
二、编程控制GPIO输出高低电平
1.控制GPIO输出高低电平代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.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;
//将需要配置的IO的电气属性模式放入数组中
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;
}
close(fd);//关闭文件
return 0;
}
int main(int argc,char* argv[])
{
int ret;
//检验传入参数
if(argc != 3)
{
fprintf(stderr,"usage:%s<gpio><value>\n",argv[0]);
exit(-1);
}
//判断指定编号的GPIO是否导出
sprintf(gpio_path,"/sys/class/gpio/gpio%s",argv[1]);
if(access(gpio_path,F_OK)) //F_OK标志,检查文件是否存在
{
//目录不存在,需要将其导出
int fd,len;
fd = open("/sys/class/gpio/export",O_WRONLY);
if(fd < 0)
{
perror("open error1");
exit(-1);
}
len = strlen(argv[1]);
if(write(fd,argv[1],len) != len)
{
perror("write error1");
close(fd);
exit(-1);
}
close(fd);//导出后关闭export文件
}
//配置为输出模式
ret = gpio_config("direction","out");
if(ret != 0)
{
fprintf(stderr,"gpio_config error1");
exit(-1);
}
//配置IO口极性
ret = gpio_config("active_low","0");//0为正常情况,1为相反
if(ret != 0)
{
fprintf(stderr,"gpio_config error2");
exit(-1);
}
//输出高/低电平
ret = gpio_config("value",argv[2]);//0为正常情况,1为相反
if(ret != 0)
{
fprintf(stderr,"gpio_config error3");
exit(-1);
}
exit(0);
}
2.交叉编译生成可执行文件
使用命令:arm-linux-gnueabihf-gcc gpio.c -o gpioAPP
tips:gpio.c为自己写的程序名称,gpioAPP为编译生成的可执行文件名称
三、GPIO输出高低电平
1.执行可执行程序
将文件放到开发板根文件系统中,进入开发板系统,找到自己的编译生成的车可执行文件,使用命令 ./gpioAPP 2 1 将GPIO端口输出高电平。
tips: ./gpioAPP 2 1 #./gpioAPP为编译生成的可执行文件,“2”为gpio2,“1”为输出高电平。
2.观察实验现象
(1)控制gpio2端口输出高电平
./gpioAPP 2 1
(2)控制gpio2端口输出低电平
./gpioAPP 2 0
到此,本实验结束,实验现象说明程序是可行的。
四、作者自述
记录生活。