2 // How to access GPIO registers from C-code on the Raspberry-Pi
6 // Revised: 15-Feb-2013
9 // Access from ARM Running Linux
11 #define BCM2708_PERI_BASE 0xFE000000
12 #define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */
19 #define PAGE_SIZE (4*1024)
20 #define BLOCK_SIZE (4*1024)
26 volatile unsigned *gpio;
29 // GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
30 #define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
31 #define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3))
32 #define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))
34 #define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0
35 #define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
37 #define GET_GPIO(g) (*(gpio+13)&(1<<g)) // 0 if LOW, (1<<g) if HIGH
39 #define GPIO_PULL *(gpio+37) // Pull up/pull down
40 #define GPIO_PULLCLK0 *(gpio+38) // Pull up/pull down clock
41 extern int GPIORead(int pin){
44 extern void GPIOPinmode(int pin,int dir){
53 if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
54 printf("can't open /dev/mem \n");
60 NULL, //Any adddress in our space will do
61 BLOCK_SIZE, //Map length
62 PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
63 MAP_SHARED, //Shared with other processes
65 GPIO_BASE //Offset to GPIO peripheral
68 close(mem_fd); //No need to keep mem_fd open after mmap
70 if (gpio_map == MAP_FAILED) {
71 printf("mmap error %llu\n", (uint64_t)gpio_map);//errno also set!
75 // Always use volatile pointer!
76 gpio = (volatile unsigned *)gpio_map;