linux环境下面,对gpio的控制,点灯是基本功之一,今天偿试用C语言进行点灯。
对gpio的操作是基于文件/sys/class/gpio下面的读写操作:
1、是对/sys/class/gpio/export
写入需要操作的IO编号,来启用IO,这次选用89、88、87行操作。
2、对/sys/class/gpio/gpio89/direction写入out来定义IO为输出。
3、在上面两个步骤完成后,对/sys/class/gpio/gpio89/value进行写入1或者0来确定输出高低电平。
4、对IO控制结束后,对`/sys/class/gpio/unexport进入关闭,要不然再次对IO进行操作时,会显示IO busy的错误信息。
书写led_example.c内容如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc ,char *argv[])
{
FILE *fp=NULL;
int i=0;
fp = fopen("/sys/class/gpio/export","w");
fprintf(fp,"%d",89);
fclose(fp);
fp = fopen("/sys/class/gpio/export","w");
fprintf(fp,"%d",88);
fclose(fp);
fp = fopen("/sys/class/gpio/export","w");
fprintf(fp,"%d",87);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio89/direction","w");
fprintf(fp,"out");
fclose(fp);
fp = fopen("/sys/class/gpio/gpio88/direction","w");
fprintf(fp,"out");
fclose(fp);
fp = fopen("/sys/class/gpio/gpio87/direction","w");
fprintf(fp,"out");
fclose(fp);
for(i=0;i<100;i++)
{
fp = fopen("/sys/class/gpio/gpio89/value","w");
fprintf(fp,"%d",1);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio88/value","w");
fprintf(fp,"%d",0);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio87/value","w");
fprintf(fp,"%d",0);
fclose(fp);
sleep(1);
fp = fopen("/sys/class/gpio/gpio89/value","w");
fprintf(fp,"%d",0);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio88/value","w");
fprintf(fp,"%d",1);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio87/value","w");
fprintf(fp,"%d",0);
sleep(1);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio89/value","w");
fprintf(fp,"%d",0);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio88/value","w");
fprintf(fp,"%d",0);
fclose(fp);
fp = fopen("/sys/class/gpio/gpio87/value","w");
fprintf(fp,"%d",1);
fclose(fp);
sleep(1);
}
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp, "%d",89);
fclose(fp);
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp, "%d",88);
fclose(fp);
fp = fopen("/sys/class/gpio/unexport","w");
fprintf(fp, "%d",87);
fclose(fp);
return 0;
}
编译,上传到开发板:
parallels@parallels-Parallels-Virtual-Platform:~/Documents/helloworld$ arm-linux-gnueabihf-gcc led_expamle.c -o led_expamle
parallels@parallels-Parallels-Virtual-Platform:~/Documents/helloworld$ scp led_expamle root@192.168.3.169:/root/
root@192.168.3.169's password:
led_expamle 100% 12KB 1.9MB/s 00:00
parallels@parallels-Parallels-Virtual-Platform:~/Documents/helloworld$
然后执行./led_example,可以看到LED灯依次点亮: