参考:
这里还有找到一篇通过文件IO操作的(http://www.linuxdiyf.com/linux/23872.html),以后写程序会用到,先记着。
1.首先查看系统中有没有 “/sys/class/gpio” 这个文件夹。如果没有请在编译内核的时候通过make menuconfig加入
Device Drivers —>
GPIO Support —> /sys/class/gpio/… (sysfs interface)
2.各文件说明:
在/sys/class/gpio下有如下文件:
root@NanoPi2:~/Documents# ls /sys/class/gpio/
export gpiochip128 gpiochip32 gpiochip96
gpiochip0 gpiochip160 gpiochip64 unexport
1].export:用于通知系统需要导出控制的GPIO引脚编号,导出成功会出现 gpio*,如下的gpio62
root@NanoPi2:~/Documents# echo 62 > /sys/class/gpio/export
root@NanoPi2:~/Documents# ls /sys/class/gpio/
export gpiochip0gpiochip160 gpiochip64 unexport
gpio62 gpiochip128 gpiochip32 gpiochip96
2].unexport:用于通知系统取消导出,相应的gpio* 消失
echo 62 > /sys/class/gpio/export
3].gpiochipx : gpio各group的信息,如下
root@NanoPi2:~/Documents# ls /sys/class/gpio/gpiochip0
base device label ngpio power subsystem uevent
base :引脚的起始编号
label:寄存器名称
ngpio: 引脚总数
4].gpio*说明:通过控制该目录下的direction,value就可实现对相应引脚的控件。
root@NanoPi2:~/Documents# ls /sys/class/gpio/gpio62
active_low device direction edge power subsystem uevent value
输入下面命令,在 direction 属性文件设置 GPIO 工作状态
echo out >direction
echo in > direction
输入下面命令,在 value 属性文件分别设置 1 和 0 值, 在 GPIO 分别输出高电平和低电平
echo 1 > value
echo 0 > value
3.写了个脚本如下:
#!/bin/sh
for i in /sys/class/gpio/gpio*
do
if [ "/sys/class/gpio/gpio*" = "$i" ]; then
echo no gpio file exit!
exit
fi
echo the label `cat $i/label`\'s base number is `cat $i/base`
done
if [ ! -e /sys/class/gpio/export ]; then
echo no export file exist!
exit
fi
echo "please input the number of GPIO\`s pin"
echo "eg:GPIOA12, number = GPIOA\`s base number + 12"
read -p "number=" port
m=`echo $port | sed 's/[0-9]//g'`
if [ -n "$m" -o -z "$port" ]; then
echo valied number
exit
fi
if [ $port -gt 160 -o $port -lt 0 ]; then
echo the number is not adapted
exit
fi
echo $port > /sys/class/gpio/export
if [ -d /sys/class/gpio/gpio$port ] ;then
echo "set pin direction output"
echo "out" > /sys/class/gpio/gpio$port/direction
while :
do
read -p "please input(1:high,0:low,other:exit): " level
m=`echo $level | sed 's/[0-1]//g'`
if [ -z "$m" -a -n "$level" ]; then
echo setting pin to $level
echo $level > /sys/class/gpio/gpio$port/value
else
echo exit or valied number
break
fi
done
else
echo "the /sys/class/gpio/gpio$port doesnot exist!"
fi
echo $port > /sys/class/gpio/unexport