Created
April 14, 2017 22:47
-
-
Save soapergem/9e3289bb8a693eabf93ead5566d035bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
#define BCM2708_PERI_BASE 0x20000000 | |
#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) | |
int mem_fd; | |
void *gpio_map; | |
// I/O access | |
volatile unsigned *gpio; | |
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3)) | |
#define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3)) | |
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3)) | |
#define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0 | |
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0 | |
#define GET_GPIO(g) (*(gpio+13)&(1<<g)) // 0 if LOW, (1<<g) if HIGH | |
#define GPIO_PULL *(gpio+37) // Pull up/pull down | |
#define GPIO_PULLCLK0 *(gpio+38) // Pull up/pull down clock | |
void setup_io(); | |
int main(int argc, char *argv[]) | |
{ | |
setup_io(); | |
INP_GPIO(26); | |
OUT_GPIO(26); | |
while (true) { | |
GPIO_SET = 1<<26; | |
usleep(150000); | |
GPIO_CLR = 1<<26; | |
sleep(1); | |
} | |
return EXIT_SUCCESS; | |
} | |
void setup_io() | |
{ | |
// open /dev/mem | |
if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) { | |
printf("can't open /dev/mem \n"); | |
exit(-1); | |
} | |
// mmap GPIO | |
gpio_map = mmap( | |
NULL, //Any adddress in our space will do | |
BLOCK_SIZE, //Map length | |
PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory | |
MAP_SHARED, //Shared with other processes | |
mem_fd, //File to map | |
GPIO_BASE //Offset to GPIO peripheral | |
); | |
// no need to keep mem_fd open after mmap | |
close(mem_fd); | |
if (gpio_map == MAP_FAILED) { | |
printf("mmap error %d\n", (int)gpio_map); // errno also set! | |
exit(-1); | |
} | |
// always use volatile pointer! | |
gpio = (volatile unsigned *)gpio_map; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment