reading a port (GPIO) value in C (beagleboard-xm) -
i have embedded board (beagleboard-xm) runs ubuntu 12.04. need read gpio continuously see if value of port changes. code herebelow:
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> file *fp; int main(void) { //linux equivalent code "echo 139 > export" export 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" set port 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 have problem, reading value** int value2; while(1){ value2= system("cat /sys/class/gpio/gpio139/value"); printf("value is: %d\n", value2); } return 0; }
the code above reads port continuously (0
default), however, when change port 1
, system
call output correct value, printf
still prints 0
output. problem value2
not store value system()
outputs.
if use code below instead of while
loop above, error opening value
file (cannot open value file.), if put fopen
line outside of while
loop, not show changes in value
file.
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); }
my question: how need fix code? or how should read value
file? additional info wonder: difference e.g. export port system("echo 139 > /sys/class/gpio/export")
, fp = fopen("/sys/class/gpio/export","w"); fprintf(fp,"%d",139);
method suggest me use? why?
thank in advance.
the system()
function returns return value of cat
, 0. not return standard output cat
, expecting.
i think problem second bit of code you're not calling fclose()
. since you're running in tight loop, exceed number of open files allowed.
so, call fclose()
, , think putting sleep()
in there too.
Comments
Post a Comment