I want to access the GPIO registers and write data to them and control them directly. How do I do this in C? Are there any sites or any resources that help with this, or explain it?
access internal GPIO registers
Accessing these registers directly seems to be everybody wants to do... ;) Search for the mmap() system call to map this physical address space into your process.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
FILE *fp;
int main(int argc, char** argv)
{
printf("\n**********************************\n"
"* Welcome to PIN Blink program *\n"
"**********************************\n");
//create a variable to store whether we are sending a '1' or a '0'
char set_value[20];
//Integer to keep track of whether we want on or off
int toggle = 0;
//Using sysfs we need to write "160" to /sys/class/gpio/export
//This will create the folder /sys/class/gpio/gpio160
if ((fp = fopen("/sys/class/gpio/export", "ab")) == NULL)
{
printf("Cannot open export file.\n");
exit(1);
}
//Set pointer to begining of the file
rewind(fp);
//Write our value of "160" to the file
strcpy(set_value,"160");
fwrite(&set_value, sizeof(char), 3, fp);
fclose(fp);
printf("...export file accessed, new pin now accessible\n");
//SET DIRECTION
//Open the LED's sysfs file in binary for reading and writing, store file
pointer in fp
if ((fp = fopen("/sys/class/gpio/gpio160/direction", "rb+")) == NULL)
{
printf("Cannot open direction file.\n");
exit(1);
}
//Set pointer to begining of the file
rewind(fp);
//Write our value of "out" to the file
strcpy(set_value,"out");
fwrite(&set_value, sizeof(char), 3, fp);
fclose(fp);
printf("...direction set to output\n");
strcpy(set_value,"1");
int ch;
while(ch!=3)
{
printf("1:LED ON\n2:LED OFF\n3:exit");
printf("\nenter your choice\n");
scanf("%d",&ch);
switch(ch){
case 1:
{if ((fp = fopen("/sys/class/gpio/gpio160/value", "rb+")) == NULL)
{
printf("Cannot open value file.\n");
exit(1);
}
//Set pointer to begining of the file
rewind(fp);
//Write our value of "1" to the file
strcpy(set_value,"1");
fwrite(&set_value, sizeof(char), 1, fp);
fclose(fp);
printf("...value set to 1...\n");
} break;
case 2:
{if ((fp = fopen("/sys/class/gpio/gpio160/value", "rb+")) == NULL)
{
printf("Cannot open value file.\n");
exit(1);
}
//Set pointer to begining of the file
rewind(fp);
//Write our value of "0" to the file
strcpy(set_value,"0");
fwrite(&set_value, sizeof(char), 1, fp);
fclose(fp);
printf("...value set to 0...\n");
} break;
}
}
return 0;
}


