Skip to content

Instantly share code, notes, and snippets.

@katogiso
Created November 5, 2017 06:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save katogiso/768eba46574d7b59f9ae97dd47a8c9d2 to your computer and use it in GitHub Desktop.
RaspberryPi gpio sample
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#define PERI_BASE 0x3F000000
#define GPIO_BASE (PERI_BASE + 0x200000) /* GPIO controller */
#define PAGE_SIZE (4*1024)
#define BLOCK_SIZE (4*1024)
// I/O access
volatile unsigned *gpio;
static int mem_fd = 0;
void check( int condition, char* msg )
{
if( condition ){ printf("%s", msg); exit (-1);}
}
volatile unsigned * io_mapping(int base_addr)
{
char *gpio_mem, *gpio_map;
if (!mem_fd) {
mem_fd = open("/dev/mem", O_RDWR|O_SYNC);
check((mem_fd < 0), "can't open /dev/mem \n");
}
gpio_mem = malloc(BLOCK_SIZE + (PAGE_SIZE-1));
check( ( gpio_mem == NULL), "allocation error \n");
// Make sure pointer is on 4K boundary
if ((unsigned long) gpio_mem % PAGE_SIZE)
gpio_mem += PAGE_SIZE - ((unsigned long)gpio_mem % PAGE_SIZE);
// Now map it
gpio_map = (char *)mmap((caddr_t)gpio_mem,
BLOCK_SIZE,
PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_FIXED,
mem_fd,
base_addr );
check( ((long)gpio_map < 0), "mmap error \n");
return (volatile unsigned *)gpio_map;
}
void main()
{
int count;
volatile unsigned *addr;
gpio = io_mapping(GPIO_BASE);
// set GPIO20 to output mode ( bit[2:0] ). offset is 0x8( byte address ) .
*( gpio + 0x8/4 ) = (*( gpio + 0x8/4 ) & ~(0x7)) | (0x1 << 0);
for( count = 0 ; ; count++){
usleep(1000);
addr = ( count % 2 ) ? gpio + 0x1C/4 : gpio + 0x28/4 ;
*addr = 0x1 << 20;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment