Thu Apr 26, 2012 11:50 pm
In my opinion, the easiest way to use the GPIO is the way implied by the shell script (should work from any language that supports file IO) as it"s just file IO, and has no need to know special knowledge of BCM2835 (and therefore less likely to have subtle bugs):
void init_gpio(int n)
{
char filename[256];
snprintf(filename, 256, "/sys/class/gpio/gpio%i/direction", n);
FILE *f = fopen("/sys/class/gpio/export", "w");
if (!f){
//some kind of error handling
}
fprintf(f, "%i", n);
fclose(f);
f = fopen(filename, "w");
if (!f){
//some kind of error handling
}
fprintf(f, "in", n);
fclose(f);
}
void deinit_gpio(int n)
{
FILE *f = fopen("/sys/class/gpio/unexport", "w");
if (!f){
//some kind of error handling
}
fprintf(f, "%i", n);
fclose(f);
}
int read_gpio(int n)
{
char filename[256];
snprintf(filename, 256, "/sys/class/gpio/gpio%i/value", n);
FILE *f = fopen(filename, "r");
if (!f){
//some kind of error handling
}
char c = 0;
if (1 != fread(&c, 1, 1, f)){
//some kind of error handling
}
fclose(c);
return c;
}
void write_gpio(int n, int v)
{
char filename[256];
snprintf(filename, 256, "/sys/class/gpio/gpio%i/value", n);
FILE *f = fopen(filename, "w");
if (!f){
//some kind of error handling
}
fprintf(f, "%i", v);
fclose(c);
return c;
}
Yeah, I guess file IO like this is long winded in C, but you get the idea.
Check out cool stuff I'm doing, e.g my PIC Programmer for the Raspberry Pi: http://www.techmeology.co.uk/rpipic/