嵌入式linux文件io方式操作gpio口示例
在嵌入式linux中应用层操作gpio口,如果懒得写驱动或者懒得翻寄存器手册,有一种简单的方式操作,只需要终端申请io,然后设置方向就可以直接操作,这里以野火的imx板子为例示范,后面以一个led闪烁灯程序作为例子
一、命令行操作示范
1.确认文件系统根目录里面有sys目录,没有的话需要在内核编译的时候打开Device Drivers —> GPIO Support —> /sys/class/gpio/… (sysfs interface)
2.查看计算申请的编号,这里我们以IO1.1为例
root@npi:/sys/class/gpio# cat gpiochip0/label
209c000.gpio
这里基地址是209c000 ,在imx6ullrm手册里面P1141里,GPIO memory map查到就是GPIO1
root@npi:/sys/class/gpio# cat gpiochip0/base
0
我们要申请的是IO1.1,0+1=1
2.申请io
在/sys/class/gpio目录下,命令终端输入echo 1 > export,会在当前目录下产生一个gpio1的目录
root@npi:/sys/class/gpio# echo 1 > export
3.设置输出
进入gpio1目录,修改direction
root@npi:/sys/class/gpio/gpio1# echo out > direction
4.设置电平
进入gpio1目录,修改value
root@npi:/sys/class/gpio/gpio1# echo 0 > value
5.配置输入
root@npi:/sys/class/gpio/gpio1# echo in > direction
6.读取电平
root@npi:/sys/class/gpio/gpio1# cat value
0
附:active_low device direction edge power subsystem uevent value
active_low:中断配置 低电平有效 高电平有效
edge:中断配置 ,上升沿 下降沿
uevent:中断事件
二、c程序操作
#include <stdio.h>
#include <fcntl.h>
int led_init()
{
#defien led "1"
#define led_path "/sys/class/gpio/gpio1"
#define led_dir "/sys/class/gpio/gpio1/direction"
//申请io
int fd = 0;
fd = open("/sys/class/gpio/export", O_WRONLY);
if(-1 == fd)
{
printf("[%s]:[%d] open gpio export file error\r\n", __FUNCTION__, __LINE__);
exit(1);
}
if(-1 == write(fd, led, 1))
{
printf("write file operation error\r\n");
exit(1);
}
close(fd);
//配置
fd = open(led_dir, O_WRONLY);
if(-1 == fd)
{
printf("[%s]:[%d] open gpio direction file error\r\n", __FUNCTION__, __LINE__);
exit(1);
}
if(-1 == write(fd, "in", sizeof("in")))
{
printf("[%s]:[%d] write operation direction error\r\n", __FUNCTION__, __LINE__);
close(direction_fd);
exit(1);
}
close(fd);
return 0;
}
int led_ctrl(unsigned char x)
{
#define led_value "/sys/class/gpio/gpio1/value"
int fd = 0;
fd = open(led_value, O_WRONLY);
if(-1 == fd)
{
printf("[%s]:[%d] open gpio export file error\r\n", __FUNCTION__, __LINE__);
exit(1);
}
if(x)
{
if(-1 == write(fd, "1", sizeof("in")))
{
printf("[%s]:[%d] write operation value error\r\n", __FUNCTION__, __LINE__);
close(direction_fd);
exit(1);
}
}
else
{
if(-1 == write(fd, "0", sizeof("in")))
{
printf("[%s]:[%d] write operation value error\r\n", __FUNCTION__, __LINE__);
close(direction_fd);
exit(1);
}
}
return 0;
}
int read_ledstate()
{
#define led_value "/sys/class/gpio/gpio1/value"
int fd = 0;
char value;
fd = open(led_value, O_WRONLY);
if(-1 == fd)
{
printf("[%s]:[%d] open gpio export file error\r\n", __FUNCTION__, __LINE__);
exit(1);
}
if(-1 == read(gpiovalue_fd, &value, sizeof(value)))
{
printf("[%s]:[%d] read gpiovalue is fail\r\n", __FUNCTION__, __LINE__);
close(gpiovalue_fd);
exit(1);
}
return value;
}
int main()
{
int x = 0;
led_init();
led_ctrl(1);
x = read_ledstate();
printf("led state = %d \r\n", x);
return 0;
}