基于Linux通用GPIO接口的操作函数

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <string.h>

//char *pin = io第几组 * 32 + 第几号引脚,
//例如:PA8:pin=0*32+8=8;  PF6:pin=6*32+6=198;

//char *mode 通常为out/in, out为输出, in为输入
//char *value 通常为0/1, 0为低电平, 1位高电平

//使用Linux通用gpio接口控制io口函数
int Linux_Gpio_Config(char *pin, char *mode, char *value)
{
	static int dev_fd, export_fd, dir_fd, ret;
	char DEV_PATH[64], EXPORT_PATH[64], DIRECT_PATH[64];
	char buf[10];

	sprintf(DEV_PATH, "/sys/class/gpio/gpio%s/value", pin);
	sprintf(EXPORT_PATH, "/sys/class/gpio/export");
	sprintf(DIRECT_PATH, "/sys/class/gpio/gpio%s/direction", pin);

	export_fd = open(EXPORT_PATH, O_WRONLY);
	if(export_fd == -1)
	{
		perror("export open failed!\n");
		return -1;
	}

	write(export_fd, pin, strlen(pin));

	dev_fd = open(DEV_PATH, O_RDWR);
	if(dev_fd == -1)
	{
		perror("dev open faield!\n");
		return -1;
	}

	dir_fd = open(DIRECT_PATH, O_RDWR);
	if(dir_fd == -1)
	{
		perror("dir open failed!\n");
		return -1;
	}
	
	memset(buf, 0, sizeof(buf));	
	strcpy(buf, mode);

	ret = write(dir_fd, buf, strlen(mode));
	if(ret == -1)
	{
		perror("dir write failed!\n");
		close(export_fd);
		close(dir_fd);
		close(dev_fd);
		return -1;
	}

	memset(buf, 0, sizeof(buf));
	strcpy(buf, value);
	ret = write(dev_fd, buf, strlen(value));
	if(ret == -1)
	{
		perror("dev write failed!\n");
		return -1;
	}

	close(export_fd);
	close(dir_fd);
	close(dev_fd);

	return 0;
}


//demo
int main(void)
{
	while(1)
	{
		Linux_Gpio_Config("7", "out", "1");
		usleep(10);
		Linux_Gpio_Config("7", "out", "0");
	}

	return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值