gpio.h
/*
* GPIO user space helpers
*
* Copyright 2009 Analog Devices Inc.
* Michael Hennerich (hennerich@blackfin.uclinux.org)
*
* Licensed under the GPL-2 or later
*/
#ifndef __GPIO_H_YP
#define __GPIO_H_YP
int gpio_export(unsigned gpio);
int gpio_unexport(unsigned gpio);
int gpio_dir_out(unsigned gpio);
int gpio_dir_in(unsigned gpio);
int gpio_set_value(unsigned gpio, unsigned value);
int gpio_get_value(unsigned gpio);
#endif
gpio.cpp
/*
* GPIO user space helpers
*
* Copyright 2009 Analog Devices Inc.
* Michael Hennerich (hennerich@blackfin.uclinux.org)
*
* Licensed under the GPL-2 or later
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define GPIO_DIR_IN 0
#define GPIO_DIR_OUT 1
int gpio_export(unsigned gpio)
{
int fd, len;
char buf[11];
fd = open("/sys/class/gpio/export", O_WRONLY);
if (fd < 0) {
perror("gpio/export");
return fd;
}
len = snprintf(buf, sizeof(buf), "%d", gpio);
write(fd, buf, len);
close(fd);
return 0;
}
int gpio_unexport(unsigned gpio)
{
int fd, len;
char buf[11];
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (fd < 0) {
perror("gpio/export");
return fd;
}
len = snprintf(buf, sizeof(buf), "%d", gpio);
write(fd, buf, len);
close(fd);
return 0;
}
int gpio_dir(unsigned gpio, unsigned dir)
{
int fd, len;
char buf[60];
len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/direction", gpio);
fd = open(buf, O_WRONLY);
if (fd < 0) {
perror("gpio/direction");
return fd;
}
if (dir == GPIO_DIR_OUT)
write(fd, "out", 4);
else
write(fd, "in", 3);
close(fd);
return 0;
}
int gpio_dir_out(unsigned gpio)
{
return gpio_dir(gpio, GPIO_DIR_OUT);
}
int gpio_dir_in(unsigned gpio)
{
return gpio_dir(gpio, GPIO_DIR_IN);
}
int gpio_set_value(unsigned gpio, unsigned value)
{
int fd, len;
char buf[60];
len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
fd = open(buf, O_WRONLY);
if (fd < 0) {
perror("gpio/value");
return fd;
}
if (value)
write(fd, "1", 2);
else
write(fd, "0", 2);
close(fd);
return 0;
}
int gpio_get_value(unsigned gpio)
{
int fd, len, ret;
char buf[60];
ret = 0;
len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
fd = open(buf, O_RDONLY);
if (fd < 0) {
perror("gpio/value");
return fd;
}
char result[2]={0};
if (read(fd, result, 2) < 0)
{
perror("read gpio/value err");
ret = -1;
}
else
{
if (result[0] == '1')
{
ret = 1;
}
else if (result[0] == '0')
{
ret = 0;
}
else
{
ret = -1;
}
}
close(fd);
return ret;
}
#if 0
int main(int argc, char *argv[])
{
int i = 2;
gpio_export(60);
gpio_dir_out(60);
while(i--) {
gpio_set_value(60, i & 1);
sleep(1);
}
gpio_unexport(60);
i = 2;
gpio_export(73);
gpio_dir_out(73);
while(i--) {
gpio_set_value(73, i & 1);
sleep(1);
}
gpio_unexport(73);
gpio_export(42);
gpio_dir_in(42);
for (i = 0; i < 5; i++)
{
printf ("42 PB10 pin level:%d\n", gpio_get_value(42));
sleep(1);
}
gpio_unexport(42);
}
#endif