1.开启相关时钟
在 STM32 微控制器中,开启 GPIO 端口的时钟是确保 IO 口可以正常工作的第一步。
查找 RCC 寄存器使能时钟
在 STM32 中,时钟控制的寄存器通常位于 RCC (Reset and Clock Control) 模块中。不同的 STM32 系列(如 STM32F1、STM32F4 等)具有不同的寄存器地址。
通过查看参考手册系统架构可以找到GPIO口是在APB2下的。

查找要开启时钟的寄存器,然后通过该寄存器操作时钟的开启或关闭。比如要打开IOPA的时钟就要操作该寄存器的第二位IOPAEN为1,就需要知道RCC_APB2ENR这个寄存器的地址。
RCC的基地址加上这个寄存器的偏移地址就是这个寄存器的实际地址。

比如我要使能GPIOA的时钟
RCC的基地址是0x4002 1000,APB2ENR的偏移量是0x18,所以APB2ENR的地址值是0x4002 1000 + 0x18 = 0x4002 1018
在这个地址写入1,这样就开启了GPIOA的时钟。
在代码中,需要把地址强转成指针才能给这个地址赋值。
*(uint32_t *)(0x40021000 + 0x18) = 0x04;
这样就开启了GPIOA的时钟。
2.给IO口设置模式输出电平
找到GPIOx的基地址,再根据偏移地址找到要使用的寄存器的地址。




如GPIOA的基地址是0x4001 0800 + 0x00,PA0的输出模式寄存器是GPIOA_CRL。
配置MODE0 = 11 输出模式Max50MHz , CNF0 = 00 通用推挽输出模式 (0011)0x3
*(uint32_t *)(0x40010800 + 0x00) = 0x03;
ODR寄存器的地址是 0x40010800 + 0x0c ,设置PA0为高电平。
*(uint32_t *)(0x40010800 + 0x0c) = 0x01;
I/O端口寄存器须按32位访问

