Ubuntu GPIO操作

参考:

https://blog.csdn.net/kris_fei/article/details/69553422

https://blog.csdn.net/qwq1503/article/details/89321291

  • 查询GPIO信息

# 目录跳转
cd /sys/kernel/debug
# 查询信息
cat gpio

查询结果如下

Ubuntu GPIO操作_第1张图片
可以看到gpio1是以nubmer为32开始, 那么GPIO1_A1就是 32 + 1 = 33

  • 导入GPIO1_A1

echo 33 > /sys/class/gpio/export
  • 导出GPIO1_A1

echo 33 > /sys/class/gpio/unexport
  • 定义GPIO1_A1输入输出方向

# direction接受的参数:in, out, high, low。high/low同时设置方向为输出,并将value设置为相应的1/0。
echo out > /sys/class/gpio/gpio33/direction
  • 定义GPIO1_A1 Value值

echo 1 >/sys/class/gpio/gpio33/value

下面是C语言编写的GPIO控制例程,实现LED的每隔一秒闪烁一次。

示例1:

// 参考:https://blog.csdn.net/qwq1503/article/details/89321291
#include 
#include 
#include 
#include 
int main( void )
{
	FILE	*p	= NULL;
	int	i	= 0;
	p = fopen( "/sys/class/gpio/export", "w" );
	fprintf( p, "%d", 38 );
	fclose( p );
	p = fopen( "/sys/class/gpio/gpio38/direction", "w" );
	fprintf( p, "out" );
	fclose( p );
	for ( i = 0; i < 100; i++ )
	{
		p = fopen( "/sys/class/gpio/gpio38/value", "w" );
		fprintf( p, "%d", 1 );
		sleep( 1 );
		fclose( p );
		p = fopen( "/sys/class/gpio/gpio38/value", "w" );
		fprintf( p, "%d", 0 );
		sleep( 1 );
		fclose( p );
	}
	p = fopen( "/sys/class/gpio/unexport", "w" );
	fprintf( p, "%d", 38 );
	fclose( p );
	return(0);
}

 示例2:

#include 
#include 
#include 
#include 
int main( void )
{
	FILE	*p	= NULL;
	int	i	= 0;
	for ( i = 0; i < 100; i++ )
	{
		p = fopen( "/proc/rp_gpio/gpio0", "w" );
		fprintf( p, "%d", 1 );
		sleep( 1 );
		fclose( p );
		p = fopen( "/proc/rp_gpio/gpio0", "w" );
		fprintf( p, "%d", 0 );
		sleep( 1 );
		fclose( p );
		
	}
	return(0);
}

 

你可能感兴趣的:(linux)