更多原理请参考跑马灯 库函数版 个人笔记
步骤
使能IO口时钟。配置相关寄存器寄存器
RCC->AHB1ENR
初始化IO口模式。配置四个配置寄存器
GPIOx_MODER/ GPIOx_OTYPER/ GPIOx_OSPEEDR/ GPIOx_PUPDR
操作IO口,输出高低电平。配置寄存器GPIOX_ODR或者BSRRL/BSRRH。
代码
led.c
#include "led.h"#include "stm32f4xx.h"void LED_Init(){ //1.使能pf9 和pf 10 的时钟 //打开中文参考手册,找到时钟使能寄存器ah /* 6.3.12 RCC AHB1 外设时钟使能寄存器 (RCC_AHB1ENR) */ //查手册知,PF是第五位,故第五位置1,其余位不变 RCC->AHB1ENR |= 1<<5; //2.GPIO_init //GPIOF)_9 GPIOF->MODER &= ~(3<<2*9); //查手册知,19,18位为01(通用输出模式)先都置为0 ; gpiof9,每个引脚两位 GPIOF->MODER |= 1<<2*9; //再把18位置为1 GPIOF->OSPEEDR &= ~(3<<2*9); //19~18 10 fast 50MHz GPIOF->OSPEEDR |= 2<<2*9; GPIOF->PUPDR &= ~(3<<2*9); //查手册知,19,18位为01 GPIOF->PUPDR|= 1<<2*9; GPIOF->OTYPER &= ~(1<<9); //第九\十位为0 //GPIOF)_10 GPIOF->MODER &= ~(3<<2*10); //查手册知,19,18位为01(通用输出模式)先都置为0 ; gpiof9,每个引脚两位 GPIOF->MODER |= 1<<2*10; //再把18位置为1 GPIOF->OSPEEDR &= ~(3<<2*10); //19~18 10 fast 50MHz GPIOF->OSPEEDR |= 2<<2*10; GPIOF->PUPDR &= ~(3<<2*10); //查手册知,19,18位为01 GPIOF->PUPDR|= 1<<2*10; GPIOF->OTYPER &= ~(1<<10); //第九\十位为0 //3.输出高低电平 GPIOF->ODR |= 1<<9; GPIOF->ODR |= 1<<10;}
led.h
#ifndef __LED_H#define __LED_Hvoid LED_Init(void);#endif
main.c
#include "stm32f4xx.h"#include "led.h"#include "delay.h"int main(){ delay_init(168); LED_Init(); while(1){ Stm32_Clock_Init(336,8,2,7);//设置时钟,168Mhz,(先开始没加这一句,延时速度很慢) GPIOF->ODR &=~(1<<9); GPIOF->ODR |=1<<10; delay_ms(500); GPIOF->ODR |=1<<9; GPIOF->ODR &=~(1<<10); delay_ms(500); }}