【发布时间】:2012-07-07 14:35:39
【问题描述】:
我有一个运行 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 循环,如果我将fopen 行放在while 循环之外,我会收到关于打开value 文件的错误(无法打开值文件。) ,它不会显示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(3)非常昂贵——您的进程首先执行fork(2),然后在子进程上执行/bin/sh以处理命令。
标签: c beagleboard gpio