转自:http://blog.csdn.net/cjyusha/article/details/50418862
在Linux嵌入式设备开发中,对GPIO的操作是最常用的,在一般的情况下,一般都有对应的驱动,应用程序打开对应的驱动,然后通过ioctl函数就可以对其进行操作。在linux中,其实有一个通用的GPIO驱动,应用通过调用文件的形式来进行读写操作,这个文件是/sys/class/gpio,本文就简单的来讲解一下通用GPIO接口的读写。
一、 以echo的形式调用system函数进行操作,这种形式编程比较简单,结构比较清晰,如下:
- set_gpio64_low
void set_gpio64_low(void)
{
system("echo 64 > /sys/class/gpio/export");
system("echo out > /sys/class/gpio/gpio64/direction");
system("echo 0 > /sys/class/gpio/gpio64/value");
}
- set_gpio64_high
void set_gpio64_high(void)
{
system("echo 64 > /sys/class/gpio/export");
system("echo out > /sys/class/gpio/gpio64/direction");
system("echo 1 > /sys/class/gpio/gpio64/value");
}
二、 通过文件的形式来调用
- set_io_value_low
int set_io_value_low(int gpio)
{
FILE *fp;
char buffer[];
int value;
char s[]="";
char s1[]="";
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL)
{
printf("Cannot open export file.\n");
return -;
}
fprintf(fp, "%d", gpio);
fclose(fp); sprintf(s,"/sys/class/gpio/gpio%d/direction",gpio);
if ((fp = fopen(s, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s);
return -;
}
fprintf(fp, "out");
fclose(fp); sprintf(s1,"/sys/class/gpio/gpio%d/value",gpio); if ((fp = fopen(s1, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s1);
return -;
}
strcpy(buffer,"");
fwrite(buffer, sizeof(char), sizeof(buffer) - , fp);
fclose(fp);
return ; }
- set_io_value_high
int set_io_value_high(int gpio)
{
FILE *fp;
char buffer[];
int value;
char s[]="";
char s1[]="";
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL)
{
printf("Cannot open export file.\n");
return -;
}
fprintf(fp, "%d", gpio);
fclose(fp); sprintf(s,"/sys/class/gpio/gpio%d/direction",gpio);
if ((fp = fopen(s, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s);
return -;
}
fprintf(fp, "out");
fclose(fp); sprintf(s1,"/sys/class/gpio/gpio%d/value",gpio); if ((fp = fopen(s1, "rb+")) == NULL)
{
printf("Cannot open %s.\n",s1);
return -;
}
strcpy(buffer,"");
fwrite(buffer, sizeof(char), sizeof(buffer) - , fp);
fclose(fp);
return ;
}