gpt4 book ai didi

c - 在 C (beagleboard-xm) 中读取端口 (GPIO) 值

转载 作者:行者123 更新时间:2023-12-04 18:17:28 26 4
gpt4 key购买 nike

我有一个运行 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 (beagleboard-xm) 中读取端口 (GPIO) 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com