pi gpio 内存映射 自带led闪烁示例

树霉pi gpio内存映射
/dev/mem 需root权限
/dev/gpiomem 不需要

#include 
#include 
#include 
#include 
#include 

#define BCM2837_PERI_BASE  0x3F000000
#define BCM2835_PERI_BASE  0x20000000 
#define GPIO_BASE   (BCM2835_PERI_BASE + 0x200000)
#define PAGE_SIZE 4096
int main() {
        char* fname = "/dev/gpiomem";
        int fd = open(fname,O_RDWR);
        printf("fd = %d\n", fd);

        unsigned int * adr =  mmap(0,PAGE_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,GPIO_BASE);
        printf("gpio addr %p\n",adr);
		// manipulate 
        munmap(adr,PAGE_SIZE);
        close(fd);
}

闪烁自带led
gpio16

#include 
#include 
#include 
#include 
#include 
#include 

#define BCM2837_PERI_BASE  0x3F000000
#define BCM2835_PERI_BASE  0x20000000 
#define GPIO_BASE   (BCM2835_PERI_BASE + 0x200000)
#define PAGE_SIZE 4096
// int offset 4byte 
#define SEL0 0 //gpio0-9
#define SEL1 1 //gpio10-19
#define SET0 7 
#define SET1 8 
#define CLR0 10  
#define CLR1 11
int main() {
        char* fname = "/dev/gpiomem";
        int fd = open(fname,O_RDWR);
        printf("fd = %d\n", fd);

        uint32_t*  adr  =  mmap(0,PAGE_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,GPIO_BASE);
        printf("gpio addr %p\n",adr);
        
        *(adr + SEL1) &= ~(0x7<< 18); //clear gpio 16  mode   (16-10)*3  
        *(adr + SEL1) |= (1 << 18); // set gpio 16 as output
        for(int i = 0; i < 10; i++) {
                *(adr+SET0) = (1 << 16);  // set gpio16 1
                usleep(300*1000);
                *(adr+CLR0) = (1 << 16);  // set gpio16 0
                usleep(300*1000);
        }

        munmap(adr,PAGE_SIZE);
        close(fd);
}

你可能感兴趣的:(pi,嵌入式硬件,linux)