用stm32设计一个呼吸灯的代码
时间: 2024-09-14 14:12:59 浏览: 40
基于STM32F103单片机设计的LED呼吸灯程序源代码.zip
5星 · 资源好评率100%
在STM32微控制器上设计一个简单的呼吸灯,通常会涉及到GPIO配置、定时器控制以及状态循环更新。这里是一个基本的示例代码,假设我们使用的是STM32F103系列,LED连接到PA8引脚:
```c
#include "stm32f10x.h"
// 定义LED引脚
#define LED_PIN GPIO_Pin_8
#define LED_GPIO_PORT GPIOA
#define LED_GPIO_RCC RCC_AHB1Periph_GPIOA
// 定义定时器
#define TIMER_ID TIM2
#define TIMER_CHANNEL CH1
#define TIMER_RCC RCC_APB1Periph_TIM2
void led_off(void);
void led_breathe(int duration, int pause);
int main(void) {
// 初始化GPIO和定时器
RCC_AHB1PeriphClockCmd(LED_GPIO_RCC, ENABLE);
GPIO_Init(LED_GPIO_PORT, (GPIO_InitTypeDef){
.Pin = LED_PIN,
.Mode = GPIO_Mode_OUT,
.Pull = GPIO_NOPULL,
.Speed = GPIO_Speed_50MHz
});
RCC_APB1PeriphClockCmd(TIMER_RCC, ENABLE);
TIM_TimeBaseInit(TIM2, (TIM_TimeBaseInitTypeDef){
.Prescaler = 8399, // 根据系统频率调整计数周期
.CounterMode = TIM_CounterMode_Up,
.AutoReload = 0xFFF // 设置最大计数值(16位)
});
TIM_OCInit(TIM2, (TIM_OCInitTypeDef){
.OCMode = TIM_OCMode_PWM1,
._OutputState = TIM_OutputState_Enable,
.Pulse = 0x7FF, // 50% PWM duty cycle for red state
.Comparator = 0x7FF
});
TIM_OC2Cmd(ENABLE); // Enable output channel 2 (LED)
while (1) {
led_breathe(500, 250); // 每次亮持续500毫秒,停顿250毫秒
}
}
void led_off(void) {
GPIO_SetBits(LED_GPIO_PORT, LED_PIN);
}
void led_breathe(int on_time, int off_time) {
uint16_t cnt;
TIM_Cmd(TIM2, ENABLE); // Start the timer
for (cnt = 0; cnt < on_time + off_time; cnt++) {
if (cnt >= on_time) {
TIM_OC2Cmd(DISABLE); // Turn off LED when on_time elapsed
cnt = on_time - 1; // Reset counter for off period
} else {
TIM_OC2Cmd(ENABLE); // Turn on LED
}
TIM_DelayUntilNextTrigger(TIM2); // Wait until next trigger
}
TIM_Cmd(TIM2, DISABLE); // Stop the timer after one full cycle
}
```
阅读全文