天天看點

linux下使用mmap控制GPIO

linux下使用mmap控制GPIO

原文位址:  http://mikenoodle.blog.163.com/blog/static/1133352200861274159875/

如果沒有/dev/mem,則執行

mknod /dev/mem c 1 1

編譯下面的代碼

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include<sys/mman.h> 
#include<fcntl.h> 
#include <asm/page.h>


#define GPIO_CTL_BASE 0x56000000 
#define rGPBCON 0x10 
#define rGPBDAT 0x14 
#define rGPBUP 0x18

unsigned int *GPBCON,*GPBDAT,*GPBUP;

void Led_Display(int data)
{
*(volatile unsigned int *)GPBDAT= (~data & 0xf)<<7;//因為是第7-10位,且隻有4位,故 左移7 
}

int main(int argc, char** argv) 
{ 
int gpio_fd, ip=0, i=0; 
unsigned char *gpio_map; 


gpio_map = NULL; 
GPBCON = NULL; 
GPBDAT = NULL; 
GPBUP = NULL;

gpio_fd =open("/dev/mem",O_RDWR); 
if (gpio_fd == -1) 
{ 
printf("can't open /dev/mem.\n"); 
return ; 
}

gpio_map = (unsigned char *)mmap(0, 0xbc,PROT_READ | PROT_WRITE, MAP_SHARED,gpio_fd, GPIO_CTL_BASE); 
GPBCON = (volatile unsigned int *) (gpio_map+rGPBCON); 
GPBDAT = (volatile unsigned int *) (gpio_map+rGPBDAT); 
GPBUP = (volatile unsigned int *) (gpio_map+rGPBUP);

//初始化io
*(volatile unsigned int *)GPBCON=0x154000;
*(volatile unsigned int *)GPBUP=0x7ff;

for(i=0;i<16;i++)
{
Led_Display(i);
sleep(1);
}

munmap(0, 0xbc);
if (gpio_fd != 0x0) 
{ 
close(gpio_fd); 
}

printf("GPIO Control Test end\n"); 

}
           

繼續閱讀