我有一个运行 ubuntu 12.04 的嵌入式板 (beagleboard-xm)。我需要连续读取 GPIO 以查看端口的值是否发生变化。我的代码如下:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
FILE *fp;
int main(void)
{
//linux equivalent code "echo 139 > export" to export the port
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL){
printf("Cannot open export file.\n");
exit(1);
}
fprintf( fp, "%d", 139 );
fclose(fp);
// linux equivalent code "echo low > direction" to set the port as an input
if ((fp = fopen("/sys/class/gpio/gpio139/direction", "rb+")) == NULL){
printf("Cannot open direction file.\n");
exit(1);
}
fprintf(fp, "low");
fclose(fp);
// **here comes where I have the problem, reading the value**
int value2;
while(1){
value2= system("cat /sys/class/gpio/gpio139/value");
printf("value is: %d\n", value2);
}
return 0;
}
上面的代码连续读取端口(默认为 0
),但是,当我将端口更改为 1
时, system
调用输出正确的值,但是 printf
仍然打印0
作为输出。 value2
有什么问题吗?不存储 system()
的值输出。
如果我使用下面的代码而不是 while
在上面的循环中,我收到有关打开 value
的错误文件(无法打开值文件。),如果我输入 fopen
while
之外的线循环,它不显示value
中的变化文件。
char buffer[10];
while(1){
if ((fp = fopen("/sys/class/gpio/gpio139/value", "rb")) == NULL){
printf("Cannot open value file.\n");
exit(1);
}
fread(buffer, sizeof(char), sizeof(buffer)-1, fp);
int value = atoi(buffer);
printf("value: %d\n", value);
}
我的问题:我需要如何修复代码?或者我应该如何阅读 value
文件?
作为我想知道的附加信息:与例如有什么区别?通过 system("echo 139 > /sys/class/gpio/export")
导出端口和fp = fopen("/sys/class/gpio/export","w"); fprintf(fp,"%d",139);
您建议我使用哪种方法?为什么?
提前谢谢您。
最佳答案
system()
函数返回cat
的返回值,即0。它不返回cat
的标准输出,这正是您所期待的。
我认为你的第二段代码的问题是你没有调用fclose()
。由于您正在紧密循环中运行,因此您几乎立即超出了允许的打开文件数。
因此,调用 fclose()
,并考虑将 sleep()
也放在那里。
关于c - 读取 C 中的端口 (GPIO) 值 (beagleboard-xm),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375884/