首先用 C 实现一个 GPIO 初始化的 子函数。int GPIO_Init( char port, char pin, char direc )
{
int fd_export;
int fd_IO;
fd_export = open( GPIO_EXPORT_PATH, O_WRONLY );
if( fd_export )
{
snprintf( buf, sizeof( buf ), "%d", port * 32 + pin );
if( -1 == write( fd_export, buf, strlen( buf ) ) )
{
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d", port * 32 + pin );
if( opendir( &buf ) )
{
printf( "GPIO %d.%d Already Exist..\n", port, pin );
}
else
{
close( fd_export );
printf( "GPIO %d.%d Exprot Fail..\n", port, pin );
return -1;
}
}
close( fd_export );
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d/direction", port * 32 + pin );
if( fd_IO = open( buf, O_WRONLY ) )
{
if( direc == 0 )
{
write( fd_IO, "out", strlen("out") );
printf( "GPIO %d.%d Output\n", port, pin );
}
else
{
write( fd_IO, "in", strlen("in") );
printf( "GPIO %d.%d Input\n", port, pin );
}
}
close( fd_IO );
printf( "GPIO %d.%d Init Success..\n", port, pin );
return 0;
}
else
{
close( fd_export );
printf( "GPIO %d.%d Init Fail..\n", port, pin );
return -1;
}
}
再实现一个改变GPIO值的子函数。 即控制输出 高电平 / 低电平。
int GPIO_SetValue( char port, char pin, char value )
{
int fd;
snprintf( buf, sizeof( buf ), "/sys/class/gpio/gpio%d/value", port * 32 + pin );
fd = open( buf, O_WRONLY );
if( 1==value )
{
write( fd, "1" , 1 );
}
else if( 0 == value )
{
write( fd, "0" , 1 );
}
close( fd );
return 0;
}
|