在linux嵌入式设备开发中,对GPIO的操作是最常用的,在一般的情况下,一般都有对应的驱动,应用程序打开对应的驱动,然后通过ioctl函数就可以对其进行操作。在linux中,其实有一个通用的GPIO驱动,应用通过调用文件的形式来进行读写操作,这个文件是/sys/class/gpio,本文就简单的来讲解一下通用GPIO接口的读写。
一、 以echo的形式调用system函数进行操作,这种形式编程比较简单,结构比较清晰,如下:
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");
}
只要完成三个步骤,就可以了
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");
}
二、 通过文件的形式来调用
int set_io_value_high(int gpio)
{
FILE *fp;
char buffer[10];
int value;
char s[50]="";
char s1[50]="";
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL)
{
printf("Cannot open export file.\n");
return -1;
}
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 -1;
}
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 -1;
}
strcpy(buffer,"1");
fwrite(buffer, sizeof(char), sizeof(buffer) - 1, fp);
fclose(fp);
return 1;
}
int set_io_value_low(int gpio)
{
FILE *fp;
char buffer[10];
int value;
char s[50]="";
char s1[50]="";
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL)
{
printf("Cannot open export file.\n");
return -1;
}
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 -1;
}
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 -1;
}
strcpy(buffer,"0");
fwrite(buffer, sizeof(char), sizeof(buffer) - 1, fp);
fclose(fp);
return 1;
}