STM32學習筆記——點亮一個LED燈
用寄存器點亮LED0
1.硬件電路
由硬件電路圖可知,LED0對應端口PB5
通過此圖可知,當PB5口清零時,LED0就會亮起。
2.地址操作
int main()
{
//打開GPIOB端口時鐘
*(unsigned int*)0x40021018 |= (1<<3);
//配置PB5爲輸出模式
*(unsigned int*)0x40010C00 &= ~((0x0f)<<(5*4));
*(unsigned int*)0x40010C00 |= ((1)<<(5*4));
//使得PB5_ODR=0,PB5端口置爲0
*(unsigned int*)0x40010C0C &= ~(1<<5);
}
PB5端口清零分爲三步:
- 打開端口時鐘RCC(掛在AHB總線上)
- 配置對應端口爲輸出模式
- 將端口輸出爲0
3.寄存器映射操作
//stm32f10x.h
//用於存放stm32寄存器映射地址
#define PERIPH_BASE ((unsigned int)0x40000000)
#define APB1PERIPH_BASE PERIPH_BASE
#define APB2PERIPH_BASE (PERIPH_BASE + 0x10000)
#define AHBPERIPH_BASE (PERIPH_BASE + 0x20000)
#define RCC_BASE (AHBPERIPH_BASE + 0x1000)
#define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00)
#define RCC_PB2ENR *(unsigned int*)(RCC_BASE + 0x18)
#define GPIOB_CRL *(unsigned int*)GPIOB_BASE
#define GPIOB_CRH *(unsigned int*)(GPIOB_BASE + 0x04)
#define GPIOB_IDR *(unsigned int*)(GPIOB_BASE + 0x08)
#define GPIOB_ODR *(unsigned int*)(GPIOB_BASE + 0x0C)
#define GPIOB_BSRR *(unsigned int*)(GPIOB_BASE + 0x10)
#define GPIOB_BRR *(unsigned int*)(GPIOB_BASE + 0x14)
#define GPIOB_LCKR *(unsigned int*)(GPIOB_BASE + 0x18)
//main.c
#include "stm32f10x.h"
int main()
{
//打開GPIOB端口時鐘
RCC_PB2ENR |= (1<<3);
//配置PB5爲輸出模式
GPIOB_CRL &= ~((0x0f)<<(5*4));
GPIOB_CRL |= ((1)<<(5*4));
//使得PB5_ODR=0,PB5端口置爲0
GPIOB_ODR &= ~(1<<5);
//PB5端口置爲0也可以使用位清零寄存器
//GPIOB_BRR |= (1<<5);
}
未完待續…