实现跑马灯, 但一个个引脚的操作实在是有些繁琐, 本次使用GPIO_WritePin接口实现批量操作GPIO引脚实现LED跑马灯。
LED灯电路
LED灯连接主控芯片引脚图
/** @defgroup GPIO_pins_define GPIO pins define
* @{
*/
#define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */
#define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */
#define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */
#define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */
#define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */
#define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */
#define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */
#define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */
#define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */
#define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */
#define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */
#define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */
#define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */
#define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */
#define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */
#define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */
#define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */
电路图上LED连接连续的引脚 GPIOC 0~7, 刚好可以使用位的方式
参考 普中STM32-PZ6806L开发板(STM32CubeMX创建项目并点亮LED灯) 创建项目并生成Keil项目
led.c
#include "led.h"
/***
* LED_LightControl : LED控制
* num : LED1 ~ LED8 / LED_ALL
* status: LED_ON/LED_OFF
***/
void LED_LightControl(LED_Number num, LED_Status status)
{
uint16_t pin = 0;
if (num == LED_ALL)
pin = 0xFF; // 引脚0 ~ 7
else
pin = 0x01<<(num-1);
HAL_GPIO_WritePin(LED_PORT, pin, status==LED_ON ? GPIO_PIN_RESET:GPIO_PIN_SET);
}
/***
* LED_DoBlinkAction : 闪动效果实现
* num : LED1 ~ LED8 / LED_ALL
* delay_ms: 延时, 亮灭的间隔
* time : 执行的次数
***/
void LED_DoBlinkAction(LED_Number num, uint32_t delay_ms, uint16_t time)
{
LED_LightControl(LED_ALL, LED_OFF);
while (time--)
{
LED_LightControl(num, LED_ON);
HAL_Delay(delay_ms);
LED_LightControl(num, LED_OFF);
HAL_Delay(delay_ms);
}
}
/***
* LED_DoFlowAction : 流水灯效果实现
* num : LED1 ~ LED8 / LED_ALL
* delay_ms: 延时, 亮灭的间隔
* time : 执行的次数
***/
void LED_DoFlowAction(uint32_t delay_ms, uint16_t time)
{
int i = 0;
LED_LightControl(LED_ALL, LED_OFF);
while (time--)
{
for (i = LED1; i <= LED7; ++i)
{
LED_LightControl(i, LED_ON);
HAL_Delay(delay_ms);
LED_LightControl(i, LED_OFF);
HAL_Delay(delay_ms);
}
}
}
main.c
int main()
{
...
while (1)
{
LED_DoBlinkAction(LED_ALL, 200, 5);
LED_DoFlowAction(50, 10);
}
...
}