CFSection9's Studio.

控制GPIO

字数统计: 447阅读时长: 2 min
2018/10/13 Share

Control GPIO in C code user space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define PANELVCC_VALUE "/sys/class/gpio/gpio31/value"
#define PANELVCC_DIRECTION "/sys/class/gpio/gpio31/direction"

int main()
{
int valuefd, directionfd;
// Update the direction of the GPIO to be an output
directionfd = open(PANELVCC_DIRECTION, O_RDWR);
if (directionfd < 0)
{
printf("Cannot open GPIO direction it\n");
exit(1);
}
write(directionfd, "out", 4);
close(directionfd);
printf("GPIO direction set as output successfully\n");

// Get the GPIO value ready to be toggled
valuefd = open(PANELVCC_VALUE, O_RDWR);
if (valuefd < 0)
{
printf("Cannot open GPIO value\n");
exit(1);
}
printf("GPIO value opened, now toggling...\n");

// toggle the GPIO as fast a possible forever, a control c is needed to stop it
while (1)
{
write(valuefd,"0", 2);
printf("Panel Vcc, set low...\n");
sleep(5);
write(valuefd,"1", 2);
printf("Panel Vcc, set high...\n");
sleep(5);
}
}

应用层调用kernel gpio接口需要用到/sys/class/gpio, 其中内容如下:

1
2
3
4
5
6
7
root@xxx:/sys/class/gpio # ls
export //创建一个gpio节点
gpio1 //单个GPIO控制节点
gpio2 //单个GPIO控制节点
...
gpiochip0 //一组GPIO控制节点
unexport //移除一个gpio节点

命令行方式:
echo 3 > export // 在/sys/class/gpio/下生成1个gpio3节点
以GPIO3为例:

1
2
3
4
5
6
7
root@xxxx:/sys/class/gpio/gpio3 # ls -l
-rw-r--r-- root root 4096 1970-01-01 08:10 active_low //0:不反转, 1: 反转(反转时value=1 为低电平)
-rw-r--r-- root root 4096 1970-01-01 08:10 direction //gpio 输入/输出, in or out
drwxr-xr-x root root 1970-01-01 08:00 power
lrwxrwxrwx root root 1970-01-01 08:10 subsystem -> ../../../../class/gpio
-rw-r--r-- root root 4096 1970-01-01 08:00 uevent
-rw-r--r-- root root 4096 1970-01-01 08:10 value //gpio 电平状态, 0 or 1

通用的还有edge设置中断触发方式,设置为in时才有。
none表示引脚为输入,不是中断引脚
rising表示引脚为中断输入,上升沿触发
falling表示引脚为中断输入,下降沿触发
both表示引脚为中断输入,边沿触发

CATALOG
  1. 1. Control GPIO in C code user space