每次使用gpio比较麻烦,所以参考教程写了一个gpio的头文价和大家分享一下。
每次只需包含头文件即可调用gpio。
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>
#include <time.h>
/*******************************************************************
nanopi2 gpio库:
整理者:扎哥
*******************************************************************/
#define A 0
#define B 1
#define C 2
#define D 3
#define E 4
/*******************************************************************
gpio初始化 gpio_init(B,29,0);
* 0 输出
* 1 输入
*******************************************************************/
void gpio_init( char port, char pin, char direc )
{
char buf[100];
int fd=-1,i=0;
DIR *dir;
fd = open( "/sys/class/gpio/export", O_WRONLY );
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d", port * 32 + pin );
if( ( dir = opendir( buf ) ) == NULL )
{
snprintf( buf, sizeof( buf ), "%d", port * 32 + pin );
write( fd, buf, sizeof( buf ) );
}
closedir( dir );
close( fd );
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d/direction", port * 32 + pin );
if( fd = open( buf, O_WRONLY ) )
{
printf("%d\n",fd);
if( direc == 0 )
{
i=write( fd, "out", sizeof("out") );
printf( "GPIO %d.%d Output\n", port, pin );
}
else
{
i= write( fd, "in", sizeof("in") );
printf( "GPIO %d.%d Input\n", port, pin );
}
}
close( fd );
printf( "GPIO %d.%d Init Success..\n", port, pin );
}
/*******************************************************************
gpio电平配置
实例:gpio_write(B,29,1);
*******************************************************************/
void gpio_write(char port, char pin, char value)
{
char buf[100];
int fd=-1,i=0;
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d/value", port * 32 + pin );
if( fd = open( buf, O_WRONLY) )
{
if( value == 0 )
{
i=write( fd, "0", sizeof("0") );
printf( "GPIO %d.%d Output low\n", port, pin );
}
else
{
i=write( fd, "1", sizeof("1") );
printf( "GPIO %d.%d Output high\n", port, pin );
}
close(fd);
}
}
/*******************************************************************
gpio输入读取
实例:int zhage=gpio_read(B,29);
0:低电平
1:高电平
*******************************************************************/
int gpio_read( char port, char pin )
{
int keyValue=1;
char buf[100];
int fd=-1;
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d/value", port * 32 + pin );
fd = open( buf, O_RDONLY );
printf("%d\n",fd);
if( read( fd, &keyValue, 1) == -1 )
{
printf( "PIN%d.%d read error\n", port, pin );
}
close(fd);
return keyValue-48;
} |