功能
4盏灯循环点亮
分析
- 查找原理图4盏灯依次为PF6、PF9、PF10、PC0
- 管脚外设时钟的配置
- 管脚输出状态的配置
-
- 模式配置
- 输出类型配置
- 输出速率配置
- 循环打开、等待、关闭、等待操作
代码
1 //led.h 2 #ifndef _LED_H_ 3 #define _LED_H_ 4 5 #define LED1_ON (GPIOF->ODR &= ~(1<<6)) 6 #define LED2_ON (GPIOF->ODR &= ~(1<<9)) 7 #define LED3_ON (GPIOF->ODR &= ~(1<<10)) 8 #define LED4_ON (GPIOC->ODR &= ~(1<<0)) 9 10 #define LED1_OFF (GPIOF->ODR |= (1<<6)) 11 #define LED2_OFF (GPIOF->ODR |= (1<<9)) 12 #define LED3_OFF (GPIOF->ODR |= (1<<10)) 13 #define LED4_OFF (GPIOC->ODR |= (1<<0)) 14 15 void led_init(int n); 16 void delay(int n); 17 18 #endif
1 //led.c 2 #include "stm32f4xx.h" 3 #include "led.h" 4 5 void delay(int n) 6 { 7 while(n--); 8 } 9 10 void led_init(int n) 11 { 12 //管脚的外设时钟配置 13 RCC->AHB1ENR |=(1<<2); //GPIOC外设时钟使能 14 RCC->AHB1ENR |=(1<<5); //GPIOF外设时钟使能 15 16 //管脚输出状态配置 17 if(!n) 18 { 19 //模式配置 20 GPIOC->MODER &= ~(0X3<<(2 * n)); //清零 21 GPIOC->MODER |= (0X1<<(2 * n)); //通用输出模式 22 //输出类型配置 23 GPIOC->OTYPER &= ~(1<<n); //推挽输出 24 //输出速率配置 25 GPIOC->OSPEEDR &= ~(0X3<<(2 * n)); //清零 26 GPIOC->OSPEEDR |= (0X2<<(2 * n)); //输出速率50M 27 } 28 else 29 { 30 //模式配置 31 GPIOF->MODER &= ~(0X3<<(2 * n)); //清零 32 GPIOF->MODER |= (0X1<<(2 * n)); //通用输出模式 33 //输出类型配置 34 GPIOF->OTYPER &= ~(1<<n); //推挽输出 35 //输出速率配置 36 GPIOF->OSPEEDR &= ~(0X3<<(2 * n)); //清零 37 GPIOF->OSPEEDR |= (0X2<<(2 * n)); //输出速率50M 38 } 39 }
//main.c #include "stm32f4xx.h" #include "led.h" int main() { //PF6 PF9 PF10 PC0 状态初始化 led_init(6); led_init(9); led_init(10); led_init(0); while(1) { LED1_ON; delay(1000000); LED1_OFF; delay(1000000); LED2_ON; delay(1000000); LED2_OFF; delay(1000000); LED3_ON; delay(1000000); LED3_OFF; delay(1000000); LED4_ON; delay(1000000); LED4_OFF; delay(1000000); } }
时间: 2024-12-13 03:11:34