gpio这里的调试要注意的是管脚的功能配置,需要更改设备树文件;
更改设备树文件:https://blog.csdn.net/cao849861802/article/details/111604277
然后注意gpio的计算比如gpio2_8
(2-1)*32 + 8 = 40
这个计算公式可以算出操作的gpio管脚是哪个。
#include "fcntl.h"
#include "stdio.h"
#include "poll.h"
#include "string.h"
#include "stdlib.h"
#include "unistd.h"
#define GPIO_EXPORT_BASE 118
#define GPIO_KEY_NUMBER 6
void edgfdinit()
{
char buf[64];
int i = 0;
int edgfd;
int len = 0;
int ret ;
for(i = 0; i < GPIO_KEY_NUMBER; i++)
{
memset(buf,0,sizeof(buf));
sprintf(buf,"echo %d > /sys/class/gpio/export",GPIO_EXPORT_BASE + i);
ret = system(buf);
if(ret < 0)
{
printf("system %s failed\r\n",buf);
continue;
}
memset(buf,0,sizeof(buf));
sprintf(buf,"/sys/class/gpio/gpio%d/edge",GPIO_EXPORT_BASE + i);
edgfd = open(buf,O_RDWR);
if(edgfd < 0)
{
printf("open %s failed\r\n",buf);
continue;
}
len = write(edgfd,"falling",strlen("falling"));
if(len < strlen("falling"))
{
printf("write edgfd falling failed GPIO = %d\r\n",i + GPIO_EXPORT_BASE);
close(edgfd);
continue;
}
}
}
void main()
{
int i = 0;
char buf[64];
int ret ;
struct pollfd fds[GPIO_KEY_NUMBER];
printf("gpio task start\r\n");
edgfdinit();
for(i = 0; i < GPIO_KEY_NUMBER; i++)
{
memset(buf,0,sizeof(buf));
sprintf(buf,"/sys/class/gpio/gpio%d/value",GPIO_EXPORT_BASE + i);
fds[i].fd = open(buf,O_RDONLY);
if(fds[i].fd < 0)
{
printf("open fd %s failed\r\n",buf);
continue;
}
fds[i].events = POLLPRI;
}
while(1)
{
ret = poll(fds,GPIO_KEY_NUMBER,-1);
if(ret < 0)
{
printf("poll fds failed \r\n");
return ;
}
for(i = 0; i < GPIO_KEY_NUMBER; i++)
{
if(fds[i].revents & POLLPRI)
{
printf("get fd is %d\r\n",fds[i].fd);
ret = lseek(fds[i].fd,0,SEEK_SET);
if(ret < 0)
{
printf("lseek seek_set failed i = %d\r\n",i);
return ;
}
memset(buf,0,sizeof(buf));
ret = read(fds[i].fd,buf,1);
if(ret < 0)
{
printf("read fds.fd failed\r\n");
return ;
}
printf("the key %d is %s",i,buf);
}
}
}
}