STM32F103C8T6使用独立按键控制呼吸灯的代码
时间: 2023-11-22 18:52:23 浏览: 198
您可以参考以下代码实现:
``` c
#include <stm32f10x.h>
#define LED_PIN GPIO_Pin_1
#define LED_PORT GPIOC
#define KEY_PIN GPIO_Pin_0
#define KEY_PORT GPIOA
#define PERIOD 1000
void led_breath(uint16_t delay);
void delay_ms(uint32_t ms);
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
uint8_t state = 0;
while (1)
{
if (GPIO_ReadInputDataBit(KEY_PORT, KEY_PIN) == RESET)
{
if (state == 0)
{
state = 1;
led_breath(10);
}
}
else
{
state = 0;
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_RESET);
}
}
}
void led_breath(uint16_t delay)
{
int i = 0;
while (1)
{
for (i = 0; i <= PERIOD; i++)
{
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_SET);
delay_ms((PERIOD + 1 - i) * delay);
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_RESET);
delay_ms(i * delay);
}
for (i = PERIOD; i >= 0; i--)
{
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_SET);
delay_ms((PERIOD + 1 - i) * delay);
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_RESET);
delay_ms(i * delay);
}
}
}
void delay_ms(uint32_t ms)
{
uint32_t i, j;
for (i = 0; i < ms; i++)
for (j = 0; j < 1000; j++);
}
```
该代码使用独立按键控制一个LED呼吸灯,使用的是STM32F103C8T6开发板。在按下按键时,LED会呼吸灯效果。该代码使用了delay_ms函数进行毫秒级延时。
阅读全文