stm32f103x.h
#ifndef __STM32F10X_H
#define __STM32F10X_H
//用来存放STM32寄存器映射的代码
//外设 peripheral
#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)
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef struct
{
uint32_t CRL;
uint32_t CRH;
uint32_t ODR;
uint32_t BSRR;
uint32_t BRR;
uint32_t LCKR;
}GPIO_TypeDef;
typedef struct
{
uint32_t CR;
uint32_t CFGR;
uint32_t CIR;
uint32_t APB2RSTR;
uint32_t APB1RSTR;
uint32_t AHBENR;
uint32_t APB2ENR;
uint32_t APB1ENR;
uint32_t BCDR;
uint32_t CSR;
}RCC_TypeDef;
#define GPIOB ((GPIO_TypeDef*)GPIOB_BASE)
#define RCC ((RCC_TypeDef*)RCC_BASE)
#endif
将GPIOB强制类型转换为GPIO_TypeDef类型的指针,指向CRL。
GPIO_CRL,GPIO_CRH等都是32bit的大小,这些寄存器全部按顺序排列。
main.c
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
int main (void)
{
//把GPIOB端口的时钟打开
RCC->APB2ENR|=((1)<<(3));
//把GPIOB PB5的IO口模式设置为输出
(*GPIOB).CRL &=~((0x0f)<<(4*5));
GPIOB->CRL |=((1)<<(4*5));
//配置GPIOB ODR寄存器 让PB5 输出低电平(其实复位后就是默认输出高电平)
GPIOB->ODR &=~(1<<5);
}
void SystemInit(void)
{
//函数体为空,目的是骗过编译器,让它不报错
}
GPIOB->CRL就是GPIOB中的CRL成员的值,等价于(*GPIOB).CRL。
进阶版:
stm32f10x_gpio.h
#ifndef __STM32F10X_GPIO_H
#define __STM32F10X_GPIO_H
#include "stm32f10x.h"
#define GPIO_Pin_0 ((uint16_t)0x0001) //00000000 00000001
#define GPIO_Pin_1 ((uint16_t)0x0002) //00000000 00000010
#define GPIO_Pin_2 ((uint16_t)0x0004) //00000000 00000100
#define GPIO_Pin_3 ((uint16_t)0x0008) //00000000 00001000
#define