#include
#include
#include
#include
#include
#include
#define PIO_BASE_ADDRESS 0x01C20800
typedef struct
{
unsigned int CFG[4];
unsigned int DAT ;
unsigned int DRV0;
unsigned int DRV1;
unsigned int PUL0;
unsigned int PUL1;
}PIO_Struct;
typedef struct
{
PIO_Struct Pn[7];
}PIO_Map;
typedef enum
{
PA = 0,
PB = 1,
PC = 2,
PD = 3,
PE = 4,
PF = 5,
PG = 6,
}PORT;
typedef enum
{
IN = 0x00,
OUT = 0x01,
AUX = 0x02,
INT = 0x06,
DISABLE = 0x07,
}PIN_MODE;
PIO_Map *PIO = NULL;
unsigned int *gpio_map;
void GPIO_Init(void)
{
unsigned int fd;
unsigned int addr_start, addr_offset;
unsigned int PageSize, PageMask;
if((fd = open("/dev/mem",O_RDWR)) == -1)
{
printf("open error\r\n");
return;
}
PageSize = sysconf(_SC_PAGESIZE); //页大小
PageMask = (~(PageSize-1)); //页掩码
// printf("PageSize:%d,PageMask:%.8X\r\n",PageSize,PageMask);
addr_start = PIO_BASE_ADDRESS & PageMask;
addr_offset = PIO_BASE_ADDRESS & ~PageMask;
// printf("addr_start:%.8X,addr_offset:%.8X\r\n",addr_start,addr_offset);
if((gpio_map = mmap(NULL,PageSize*2,PROT_READ|PROT_WRITE, MAP_SHARED,fd,addr_start)) == NULL)
{
// printf("mmap error\r\n");
close(fd);
return;
}
// printf("gpio_map:%.8X\r\n",gpio_map);
PIO = (PIO_Map *)((unsigned int)gpio_map + addr_offset);
// printf("PIO:%.8X\r\n",PIO);
close(fd);
}
void GPIO_ConfigPin(PORT port,unsigned int pin,PIN_MODE mode)
{
if (gpio_map == NULL)
return;
PIO->Pn[port].CFG[pin / 8] &= ~((unsigned int)0x07 << pin % 8 * 4);
PIO->Pn[port].CFG[pin / 8] |= ((unsigned int)mode << pin % 8 * 4);
}
void GPIO_SetPin(PORT port,unsigned int pin,unsigned int level)
{
if (gpio_map == NULL)
return;
if(level) PIO->Pn[port].DAT |= (1 << pin);
else PIO->Pn[port].DAT &= ~(1 << pin);
}
void main()
{
char i;
// printf("this is main!\n\n");
GPIO_Init();
GPIO_ConfigPin(PE,5,OUT);
// for(i=0;i<150;i++)
{
GPIO_SetPin(PE,5,1);
// sleep(0.1);
// GPIO_SetPin(PE,5,0);
// sleep(0.1);
}
}