STM32F103C8T6使用独立按键控制呼吸灯的代码
时间: 2023-03-20 07:01:53 浏览: 197
按键控制呼吸灯
以下是使用STM32F103C8T6单片机控制呼吸灯的代码,该代码使用独立按键控制呼吸灯的开关:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOC
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_PORT GPIOA
void LED_Init(void);
void Button_Init(void);
void Delay_ms(uint32_t ms);
int main(void)
{
uint8_t led_value = 0;
uint8_t button_status = 0;
LED_Init();
Button_Init();
while (1)
{
button_status = GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN);
if (button_status == 1)
{
led_value = !led_value;
if (led_value == 1)
{
for (int i = 0; i < 255; i++)
{
TIM_SetCompare1(TIM2, i);
Delay_ms(10);
}
}
else
{
for (int i = 255; i >= 0; i--)
{
TIM_SetCompare1(TIM2, i);
Delay_ms(10);
}
}
}
}
}
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStruct.GPIO_Pin = LED_PIN;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(LED_PORT, &GPIO_InitStruct);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Prescaler = 72 - 1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period = 1000 - 1;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStruct.TIM_Pulse = 0;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStruct.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStruct.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStruct.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
TIM_Cmd(TIM2, ENABLE);
}
void Button_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = BUTTON_PIN;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(BUTTON_PORT, &GPIO_InitStruct);
}
void Delay_ms(uint32_t ms)
{
uint32_t delay = ms * 12000;
while (delay--)
;
}
```
在这段代码中,首先需要定义LED和BUTTON的引脚号码和端口号码,然后使用`LED_Init`和`Button_Init`函数分
阅读全文