一、向工程模板添加led.c和led.h文件
二、原理图分析
- LED0与STM32的PB1脚连接,输出低电平时点亮、输出高电平时熄灭。
- LED1与STM32的PB0脚连接,输出低电平时点亮、输出高电平时熄灭。
三、编写LED驱动程序
- led.c
#include "led.h"
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(LED_CLK, ENABLE); // 使能相应 GPIO 时钟
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; // 输出模式
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; // 推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed; // 100MHz
GPIO_InitStructure.GPIO_Pin = LED0_PIN; // 配置 LED0 引脚
GPIO_Init(LED_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = LED1_PIN; // 配置 LED1 引脚
GPIO_Init(LED_PORT, &GPIO_InitStructure);
LED0_ON; // 配置 LED0 初始状态
LED1_OFF; // 配置 LED1 初始状态
}
- led.h
#ifndef __LED_H
#define __LED_H
#include "stm32f4xx.h"
#define LED_CLK RCC_AHB1Periph_GPIOB
#define LED_PORT GPIOB
#define LED0_PIN GPIO_Pin_1
#define LED1_PIN GPIO_Pin_0
#define LED0_ON GPIO_ResetBits(LED_PORT, LED0_PIN)
#define LED0_OFF GPIO_SetBits(LED_PORT, LED0_PIN)
#define LED1_ON GPIO_ResetBits(LED_PORT, LED1_PIN)
#define LED1_OFF GPIO_SetBits(LED_PORT, LED1_PIN)
#define LED0_TOGGLE GPIO_ToggleBits(LED_PORT, LED0_PIN)
#define LED1_TOGGLE GPIO_ToggleBits(LED_PORT, LED1_PIN)
void GPIO_Config(void);
#endif
四、编辑main.c文件
- main.c
#include "stm32f4xx.h"
#include "led.h"
int main(void)
{
GPIO_Config();
while(1)
{
}
}