1 硬件设计
上图为 野火_指南者原理图中的LED模块电路图。
通过这张图我们可以知道R、G、B三个灯的阴极是连接到STM32的GPIO引脚的,只要我们控制 GPIO 引脚的电平输出状态,即可控制 LED 灯的亮灭。
2 软件设计
为了使工程更加有条理,我们把 LED 灯控制相关的代码独立分开存储,方便以后移植。在“工程模板”之上新建“bsp_led.c”及“bsp_led.h”文件,其中的“bsp”即 Board Support Packet 的缩写 (板级支持包)。
步骤:
- 1.在bsp_led.h 文件中对LED的端口、引脚、时钟等进行宏定义。
- 2.在bsp_led.c 文件中定义LED_G_GPIO_Config()函数。
- 3.将LED_G_GPIO_Config()函数在bsp_led.h 文件中声明。
// bsp_led.h
#ifndef __BSP_LED_H
#define __BSP_LED_H
#include "stm32f10x.h"
#define LED_G_Pin GPIO_Pin_0
#define LED_PROT GPIOB
#define LED_CLK RCC_APB2Periph_GPIOB
#define LED_B_Pin GPIO_Pin_1
#define LED_R_Pin GPIO_Pin_5
void LED_G_GPIO_Config(void);
void LED_B_GPIO_Config(void);
void LED_R_GPIO_Config(void);
#endif /* __BSP_LED_H */
// bsp_led.c
// bsp : board support package 板级支持包
#include "bsp_led.h"
void LED_G_GPIO_Config(void)
{
RCC_APB2PeriphClockCmd(LED_CLK, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = LED_G_Pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PROT, &GPIO_InitStruct);
}
void LED_B_GPIO_Config(void)
{
RCC_APB2PeriphClockCmd(LED_CLK, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = LED_B_Pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PROT, &GPIO_InitStruct);
}
void LED_R_GPIO_Config(void)
{
RCC_APB2PeriphClockCmd(LED_CLK, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = LED_R_Pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PROT, &GPIO_InitStruct);
}
// main.c
#include "stm32f10x.h"
#include "bsp_led.h"
void Delay()
{
int x, y;
for(x = 3000; x > 0; x--)
{
for(y = 110; y > 0; y--);
}
}
int main(void)
{
LED_G_GPIO_Config();
LED_B_GPIO_Config();
LED_R_GPIO_Config();
GPIO_SetBits(LED_PROT, GPIO_Pin_All);
while(1)
{
GPIO_ResetBits(LED_PROT, LED_G_Pin);
Delay();
GPIO_SetBits(LED_PROT, LED_G_Pin);
Delay();
}
}
如果想使用==LED_B(ON);==的形式来使灯亮起,可以在 bsp_led.h 中定义宏:
#define ON 1
#define OFF 0
// \ 续行符,续行符后面不能有任何东西。
#define LED_B(ON) if(ON) \
GPIO_ResetBits(LED_PROT, LED_B_Pin); \
else \
GPIO_SetBits(LED_PROT, LED_B_Pin);
之后就可以将main.c中的代码更改为:
#include "stm32f10x.h"
#include "bsp_led.h"
void Delay()
{
int x, y;
for(x = 3000; x > 0; x--)
{
for(y = 110; y > 0; y--);
}
}
int main(void)
{
LED_G_GPIO_Config();
LED_B_GPIO_Config();
LED_R_GPIO_Config();
GPIO_SetBits(LED_PROT, GPIO_Pin_All);
while(1)
{
LED_B(ON);
Delay();
LED_B(OFF);
Delay();
}
}