STM32 流水灯程序:实现周期变化的LED闪烁
STM32 流水灯程序:实现周期变化的LED闪烁
本文将介绍如何使用STM32单片机编写程序,实现两个LED灯以周期变化的方式轮流闪烁。
硬件连接:
- LED灯1连接到GPIOA.9引脚
- LED灯2连接到GPIOA.10引脚
程序实现:
1. LED GPIO引脚初始化函数:
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
2. 流水灯程序函数:
void WaterFlow_LED(uint16_t xms)
{
static uint8_t led_state = 0;
static uint32_t delay_time = 0;
static float period = 2000.0; // 周期初始值为2秒
static float period_step = -100.0; // 周期递减步长为0.1秒
if (delay_time >= period / 2) {
led_state = !led_state;
GPIO_WriteBit(GPIOA, GPIO_Pin_9, led_state ? Bit_SET : Bit_RESET);
GPIO_WriteBit(GPIOA, GPIO_Pin_10, !led_state ? Bit_SET : Bit_RESET);
delay_time = 0;
}
delay_ms(xms);
delay_time += xms;
if (period_step < 0 && period <= 200.0) {
period_step = 100.0;
}
if (period_step > 0 && period >= 2000.0) {
period_step = -100.0;
}
period += period_step;
}
程序功能:
LED_Init()函数初始化GPIOA.9和GPIOA.10引脚为输出模式,并配置相关参数。WaterFlow_LED()函数实现流水灯效果,并控制周期变化。led_state变量记录LED灯的当前状态,0表示灭,1表示亮。delay_time变量记录当前延时时间。period变量记录当前周期时间,单位为ms。period_step变量记录周期变化的步长,单位为ms。- 程序通过判断
delay_time是否超过当前周期的一半来切换LED灯的状态。 - 程序通过判断
period的值来调整period_step的值,实现周期变化。
程序使用方法:
在主函数中调用 LED_Init() 函数进行初始化,并在循环中不断调用 WaterFlow_LED(xms) 函数,其中 xms 为每次延时时间。
最终实现效果:
系统上电后,两个LED灯以2秒为周期(亮1秒灭1秒)切换轮流点亮,并逐渐缩短周期(每次递减0.1秒),直至周期变为0.2秒后,恢复周期为2秒,以此循环往复。
注意:
- 本程序假设
delay_ms(xms)函数已经实现,该函数用于延时指定时间。 - 该程序仅供参考,具体实现方法可能因硬件平台和需求不同而有所差异。
相关资源:
原文地址: https://www.cveoy.top/t/topic/kgVT 著作权归作者所有。请勿转载和采集!