|
可以参考一下下面的gpio输出和输入下降沿中断
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
int gpio_open(int gpio)
{
FILE *fp;
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL)
{
printf("Cannot open export file.\n");
return -1;
}
fprintf(fp, "%d", gpio);
fclose(fp);
return 0;
}
int gpio_direction(int gpio)
{
FILE *fp;
char s[50]="";
sprintf(s,"/sys/class/gpio/gpio%d/direction",gpio);
if ((fp = fopen(s, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s);
return -1;
}
fprintf(fp, "out");
fclose(fp);
return 0;
}
int gpio_high(int gpio)
{
FILE *fp;
char buffer[10];
char s1[50]="";
sprintf(s1,"/sys/class/gpio/gpio%d/value",gpio);
if ((fp = fopen(s1, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s1);
return -1;
}
strcpy(buffer,"1");
fwrite(buffer, sizeof(char), sizeof(buffer) - 1, fp);
fclose(fp);
return 0;
}
int gpio_low(int gpio)
{
FILE *fp;
char buffer[10];
char s1[50]="";
sprintf(s1,"/sys/class/gpio/gpio%d/value",gpio);
if ((fp = fopen(s1, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s1);
return -1;
}
strcpy(buffer,"0");
fwrite(buffer, sizeof(char), sizeof(buffer) - 1, fp);
fclose(fp);
return 0;
}
int main(int argc, char *argv[])
{
int fd, ret;
char value;
struct pollfd pfd;
gpio_open(435);
gpio_direction(435);
gpio_low(435);
system("echo \"444\" > /sys/class/gpio/export");
system("echo \"in\" > /sys/class/gpio/gpio444/direction");
system("echo \"falling\" > /sys/class/gpio/gpio444/edge");
// system("echo \"both\" > /sys/class/gpio/gpio443/edge");
fd = open("/sys/class/gpio/gpio444/value", O_RDWR);
if (fd < 0) {
printf("open file fail\n");
return -1;
}
pfd.fd = fd;
pfd.events = POLLPRI | POLLERR;
ret = lseek(fd, 0, SEEK_SET);
if (ret == -1) {
printf("lseek error\n");
return -1;
}
//读取1字节
ret = read(fd, &value, 1);
while (1) {
/* 监听个数1, 等待时间无限 */
ret = poll(&pfd, 1, -1);
if (ret == -1) {
printf("poll error\n");
return -1;
}
/* 监听的时间会保存在revents成员中 */
if (pfd.revents & POLLPRI) {
//文件指针只想文件的开头
ret = lseek(fd, 0, SEEK_SET);
if (ret == -1) {
printf("lseek error\n");
return -1;
}
//读取,结果为字符'0'或者‘1’
read(fd, &value, 1);
printf("value:%c\n", value);
/* if (value == '0')
gpio_high(434);
if (value == '1')
gpio_low(434); */
}
}
close(fd);
return 0;
}
|
|