Tuesday, 5 March 2013

Raspberry Pi - raw gpio access

Sourced From :-  http://elinux.org/RPi_GPIO_Code_Samples

 
Gert van Loo & Dom, have provided some tested code which accesses the GPIO pins through direct GPIO register manipulation in C-code.
(Thanks to Dom for doing the difficult work of finding and testing the mapping.)
Note: For Raspberry Pi 2 and Pi 3, change BCM2708_PERI_BASE to 0x3F000000 for the code to work.

// BCM2835-ARM-Peripherals.pdf section 6.1

// Each GPFSELn has 10 x 3 bits (with bits 31:30 reserved) 'b000 = i/p, 'b001 = o/p, others = alternate uses
// Always use INP_GPIO(x) before using OUT_GPIO(x) as this will force 000 before setting 001


#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3)) // existing bits ANDed with 111..111000111..111
#define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3)) // existing bits ORed with 000..000001000..000

// GPSETn is at PERI_BASE + GPIO_BASE + 0x1C bytes. 0x1C = 28 bytes = 7 dwords
#define GPIO_SET *(gpio+7) // assigning 1<<n will set bit(n) only

// GPCLRn is at PERI_BASE + GPIO_BASE + 0x28 bytes. 0x28 = 40 bytes = 10 dwords
#define GPIO_CLR *(gpio+10) // assigning 1<<n will clear bit(n) only

No comments:

Post a Comment