pi gpio mmap 各功能简单实现 设置 读取 上拉下拉
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#define BCM2835_PERI_BASE 0x20000000
#define GPIO_BASE (BCM2835_PERI_BASE + 0x200000)
#define CPUFREQ 7e8
#define PAGE_SIZE 4096
enum Mode { INPUT,OUTPUT };
enum PullMode {PUD_OFF,PUD_DOWN,PUD_UP};
int fd;
uint32_t* gpio;
int gpioSetup(){
char* fname = "/dev/gpiomem";
fd = open(fname,O_RDWR | O_SYNC );
gpio = mmap(0,PAGE_SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,fd,GPIO_BASE);
}
int gpioRelease(){
munmap(gpio,PAGE_SIZE);
close(fd);
}
void pinMode(int pin, int mode)
{
unsigned int offset = pin / 10;
unsigned int shift = (pin%10)*3;
*(gpio+offset) &= ~(0x7 << shift);
if (mode == OUTPUT)
*(gpio+offset) |= (1<< shift);
}
#define SET0 7
#define CLR0 10
void writePin(int pin, int value)
{
unsigned int offset = pin / 32;
unsigned int shift = pin % 32;
if(value == 0)
*(gpio+CLR0+offset)= 1<<shift;
else
*(gpio+SET0+offset)= 1<<shift;
}
#define LEV0 13
int readPin(int pin)
{
unsigned int offset = pin / 32;
unsigned int shift = pin % 32;
unsigned int value = *(gpio+LEV0+offset);
return (value >> shift) & 1;
}
unsigned long long readAllPin()
{
unsigned long long* res1 = gpio+LEV0;
return *res1;
}
#define PUD 37
#define PUDCLK0 38
void setPud(int pin, int value)
{
unsigned int offset = pin / 32;
unsigned shift = pin % 32;
*(gpio+PUD)=value;
for(int i = 0; i < 150; i++)
asm("nop");
*(gpio+PUDCLK0+offset) |= (1<<shift);
for(int i = 0; i < 150; i++)
asm("nop");
*(gpio+PUD) = 0;
*(gpio+PUDCLK0+offset) = 0;
}
简易库函数