Skip to content

Instantly share code, notes, and snippets.

@soapergem
Created April 14, 2017 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soapergem/9e3289bb8a693eabf93ead5566d035bd to your computer and use it in GitHub Desktop.
Save soapergem/9e3289bb8a693eabf93ead5566d035bd to your computer and use it in GitHub Desktop.
#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