/sys/class/gpio/gpio41# echo out > direction # 设置红灯GPIO口为输出
/sys/class/gpio/gpio41# echo 1 > value # 设置红灯GPIO口为1
通过代码来实现
通过代码来实现,是通过文件的形式来调用linux自带通用GPIO驱动。
此外,针对按钮,需要使用poll的方式监控文件变化,响应GPIO中断
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<poll.h>
#define MSG(args...) printf(args)
//函数声明
static int gpio_export(int pin);
static int gpio_unexport(int pin);
static int gpio_direction(int pin, int dir);
static int gpio_write(int pin, int value);
static int gpio_read(int pin);
static int gpio_edge(int pin, int edge);
static int gpio_export(int pin)
{
char buffer[64];
int len;
int fd;
fd = open("/sys/class/gpio/export", O_WRONLY);
if (fd < 0)
{
MSG("Failed to open export for writing!n");
return(-1);
}
len = snprintf(buffer, sizeof(buffer), "%d", pin);
printf("%s,%d,%dn",buffer,sizeof(buffer),len);
if (write(fd, buffer, len) < 0)
{
MSG("Failed to export gpio!");
return -1;
}
close(fd);
return0;
}
static int gpio_unexport(int pin)
{
char buffer[64];
int len;
int fd;
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (fd < 0)
{
MSG("Failed to open unexport for writing!n");
return-1;
}
len = snprintf(buffer, sizeof(buffer), "%d", pin);
if (write(fd, buffer, len) < 0)
{
MSG("Failed to unexport gpio!");
return-1;
}
close(fd);
return0;
}
//dir: 0-->IN, 1-->OUT
static int gpio_direction(int pin, int dir)
{
static const char dir_str[] = "in out";
charpath[64];
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", pin);
fd = open(path, O_WRONLY);
if (fd < 0)
{
MSG("Failed to open gpio direction for writing!n");
return-1;
}
if (write(fd, &dir_str[dir == 0 ? 0 : 3], dir == 0 ? 2 : 3) < 0)
{
MSG("Failed to set direction!n");
return-1;
}
close(fd);
return0;
}
//value: 0-->LOW, 1-->HIGH
static int gpio_write(int pin, int value)
{
static const char values_str[] = "01";
charpath[64];
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_WRONLY);
if (fd < 0)
{
MSG("Failed to open gpio value for writing!n");
return-1;
}
if (write(fd, &values_str[value == 0 ? 0 : 1], 1) < 0)
{
MSG("Failed to write value!n");
return-1;
}
close(fd);
return0;
}
static int gpio_read(int pin)
{
charpath[64];
char value_str[3];
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, O_RDONLY);
if (fd < 0)
{
MSG("Failed to open gpio value for reading!n");
return-1;
}
if (read(fd, value_str, 3) < 0)
{
MSG("Failed to read value!n");
return-1;
}
close(fd);
return (atoi(value_str));