在汇编语言中0x50000A28是一个地址,在c语言中需要通过指针来实现地址的访问,并通过*来访问地址中的值,用结构体对GPIO控制器进行封装 typedef struct{
volatile unsigned int MODER;
volatile unsigned int OTYPER;
volatile unsigned int OSPEEDR;
volatile unsigned int PUPDR;
volatile unsigned int IDR;
volatile unsigned int ODR;
}gpio_t;
之后再将#define GPIOE ((gpio_t*)0x50006000)即刻通过GPIOE对各个寄存器进行访问更改
实现结果:
如图所示完成不同led循环点亮
代码示例:gpio.c
#include "gpio.h"
extern void printf(const char *fmt, ...);
void led1_init()
{
//时钟使能
rcc_ahb4_ensetr |= (0x1 << 4);
//将[21]端口置0
GPIOE->MODER &= (~(0x1 <<21));
//将[20]端口置1 设置为输出模式
GPIOE->MODER |= (0x1 <<20);
//设置为推挽模式
GPIOE->OTYPER &= (~(0x1 << 10));
//设置低速模式
GPIOE->OSPEEDR &=(~(0x3<<20));
//将[21:20]置0 禁止上下拉
GPIOE->PUPDR &= (~(0x3 <<20 ));
}
void led1_on()
{
GPIOE->ODR |= (0x1<<10);
}
void led1_off()
{
GPIOE->ODR &= (~(0x1<<10));
}
void led2_init()
{
//时钟使能
rcc_ahb4_ensetr |= (0x1 << 5);
//将[21]端口置0
GPIOF->MODER &= (~(0x1 <<21));
//将[20]端口置1 设置为输出模式
GPIOF->MODER |= (0x1 <<20);
//设置为推挽模式
GPIOF->OTYPER &= (~(0x1 << 10));
//设置低速模式
GPIOF->OSPEEDR &=(~(0x3<<20));
//将[21:20]置0 禁止上下拉
GPIOF->PUPDR &= (~(0x3 <<20 ));
}
void led2_on()
{
GPIOF->ODR |= (0x1<<10);
}
void led2_off()
{
GPIOF->ODR &= (~(0x1<<10));
}
void led3_init()
{
//时钟使能
rcc_ahb4_ensetr |= (0x1 << 4);
//将[17]端口置0
GPIOE->MODER &= (~(0x1 <<17));
//将[16]端口置1 设置为输出模式
GPIOE->MODER |= (0x1 <<16);
//设置为推挽模式
GPIOE->OTYPER &= (~(0x1 << 8));
//设置低速模式
GPIOE->OSPEEDR &=(~(0x3<<16));
//将[17:16]置0 禁止上下拉
GPIOE->PUPDR &= (~(0x3 <<16 ));
}
void led3_on()
{
GPIOE->ODR |= (0x1<<8);
}
void led3_off()
{
GPIOE->ODR &= (~(0x1<<8));
}
gpio.h
#ifndef __GPIO_H__
#define __GPIO_H__
//封装RCC寄存器
#define rcc_ahb4_ensetr (*(volatile unsigned int *)0x50000A28)
typedef struct{
volatile unsigned int MODER;
volatile unsigned int OTYPER;
volatile unsigned int OSPEEDR;
volatile unsigned int PUPDR;
volatile unsigned int IDR;
volatile unsigned int ODR;
}gpio_t;
#define GPIOE ((gpio_t*)0x50006000)
#define GPIOF ((gpio_t*)0x50007000)
void led1_init();
void led1_on();
void led1_off();
void led2_init();
void led2_on();
void led2_off();
void led3_init();
void led3_on();
void led3_off();
#endif
main.c
#include "gpio.h"
extern void printf(const char *fmt, ...);
void delay_ms(int ms)
{
int i,j;
for(i = 0; i < ms;i++)
for (j = 0; j < 1800; j++);
}
int main()
{
led1_init();
led2_init();
led3_init();
while(1)
{
led1_on();
delay_ms(1000);
led1_off();
led2_on();
delay_ms(1000);
led2_off();
led3_on();
delay_ms(1000);
led3_off();
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)