使用结构体方式访问寄存器的实践

朱老师单片机课程学习记录

#ifndef __GPIO_H__
#define __GPIO_H__


#define GPIOB_BASE		0x40010C00
#define GPIOC_BASE		0x40011000

#define GPIOB_CRH		(GPIOB_BASE + 0x04)
#define GPIOB_ODR		(GPIOB_BASE + 0x0C)
#define GPIOB_BSRR		(GPIOB_BASE + 0x10)
#define GPIOB_BRR		(GPIOB_BASE + 0x14)

#define GPIOC_CRL		(GPIOC_BASE + 0x00)
#define GPIOC_ODR		(GPIOC_BASE + 0x0C)
#define GPIOC_BSRR		(GPIOC_BASE + 0x10)
#define GPIOC_BRR		(GPIOC_BASE + 0x14)


#define RCC_APB2ENR		0x40021018

//-------------------------------------------------

#define rGPIOB_CRH 		(*((unsigned int *)GPIOB_CRH))
#define rGPIOB_ODR 		(*((unsigned int *)GPIOB_ODR))
#define rGPIOB_BSRR 	(*((unsigned int *)GPIOB_BSRR))
#define rGPIOB_BRR 		(*((unsigned int *)GPIOB_BRR))

#define rGPIOC_CRL 		(*((unsigned int *)GPIOC_CRL))
#define rGPIOC_ODR 		(*((unsigned int *)GPIOC_ODR))
#define rGPIOC_BSRR 	(*((unsigned int *)GPIOC_BSRR))
#define rGPIOC_BRR 		(*((unsigned int *)GPIOC_BRR))

#define rRCC_APB2ENR 	(*((unsigned int *)RCC_APB2ENR))

// 用结构体的方式对寄存器访问
typedef struct 
{
	volatile unsigned int CRL;
	volatile unsigned int CRH;
	volatile unsigned int IDR;			// 定义为32位
//	volatile unsigned int ODR;
	volatile unsigned int padding;		// 占位
	volatile unsigned int BSRR;	 		// 10
	volatile unsigned int BRR;
	volatile unsigned int LCKR;
}GPIO_Typedef;


GPIO_Typedef *pGPIOB = (GPIO_Typedef *)GPIOB_BASE;

void delay(void);
void led_init(void);
void led_flash(void);

#endif

#include "gpio.h"






void main(void)
{

	led_init();
	led_flash();

 	while (1);
}


void led_init(void)
{
	// 因为RCC部分还没有定义结构体,所以还按照原来的方式去操作
	rRCC_APB2ENR = 0x00000008;

	pGPIOB->CRH = 0x33333333;
	pGPIOB->ODR = 0x0000AA00;
}

void led_flash(void)
{
	unsigned int i = 0;
	
	for (i=0; i<3; i++)
	{
	 	pGPIOB->ODR = 0x0000ff00;		// 全亮
		delay();
		pGPIOB->ODR = 0x00000000;		// 全灭
		delay();
	}

}


/*
void led_init(void)
{
	rRCC_APB2ENR = 0x00000008;

	rGPIOB_CRH = 0x33333333;
	rGPIOB_ODR = 0x0000AA00;
}

void led_flash(void)
{
	unsigned int i = 0;
	
	for (i=0; i<3; i++)
	{
	 	rGPIOB_ODR = 0x0000ff00;		// 全亮
		delay();
		rGPIOB_ODR = 0x00000000;		// 全灭
		delay();
	}	
}
*/

void delay(void)
{
	unsigned int i, j;

	for (i=0; i<1000; i++)
		for (j=0; j<2000; j++);
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值