前言
1.利用LINUX内核的GPIO子统驱动LED灯.
2. 编写应用程序控制LED灯的亮灭.
3.不用写驱动程序,只写应用程序.
1.原理图
使用的是PE12这个IO口,计算一个IO编号: PE=4*32, IO编号 = 4*32 +12= 140.
注解一下:
PAX = 0*32 + X
PBX = 1*32 + X
PCX = 2*32 + X
PDX = 3*32 + X
PEX = 4*32 + X
看上面大家一定都会了.不会的话,自己看文档吧.
2.查看是否有/sys/class/gpio这个目录
ls /sys/class
我已经有这个内核驱动程序.
3.重新配置内核
如果没有 gpio 这个项驱动,我们需要重新配置内核
首先cd到buildroot目录下,对kernel单独进行编译,输入的命令如下:
make linux-menuconfig
选中它并保存,退出menuconfig,编译它
4. 应用程序 gpioctrl.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int fd;
int len;
int ret;
char gpio_path[100];
int gpio_export(char * argv)
{
fd = open("/sys/class/gpio/export",O_WRONLY);
if (fd <0)
{
printf("open /sys/class/gpio/export error\r\n");
return -1;
}
len = strlen(argv);
ret = write(fd,argv,len);
if (ret < 0)
{
printf("write /sys/class/gpio/export error\r\n");
close(fd);
return -2;
}
close(fd);
}
int gpio_unexport(char * argv)
{
fd = open("/sys/class/gpio/unexport",O_WRONLY);
if (fd <0)
{
printf("open /sys/class/gpio/unexport error\r\n");
return -1;
}
len = strlen(argv);
ret = write(fd,argv,len);
if (ret < 0)
{
printf("write /sys/class/gpio/unexport error\r\n");
close(fd);
return -2;
}
close(fd);
}
int gpio_ctrl(char * argv,char *val )
{
char file_path[100];
sprintf(file_path,"%s/%s",gpio_path,argv);
fd = open(file_path,O_WRONLY);
if (fd <0)
{
printf("open file_path error\r\n");
return -1;
}
len = strlen(val);
ret = write(fd,val,len);
if (ret < 0)
{
printf("write file_path error\r\n");
close(fd);
return -2;
}
close(fd);
}
int main( int argc, char *argv[])
{
sprintf(gpio_path,"/sys/class/gpio/gpio%s",argv[1]);
if (access(gpio_path,F_OK))
{
gpio_export(argv[1]);
}
else
{
gpio_unexport(argv[1]);
}
gpio_ctrl("direction","out");
gpio_ctrl("value",argv[2]);
gpio_unexport(argv[1]);
}
5.测试
# ./gpioctrl 140 0
# ./gpioctrl 140 1
标签:LED,int,32,PRO,sys,gpio,include,class
From: https://blog.csdn.net/weixin_43756274/article/details/143693786