stm32F103 8个流水灯
时间: 2023-10-18 18:10:30 浏览: 110
基于STM32F103的流水灯
5星 · 资源好评率100%
你可以使用STM32F103的GPIO口控制8个LED灯,实现8个流水灯的效果。下面是一个简单的代码示例:
```c
#include "stm32f10x.h"
int main(void)
{
// 初始化GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 设置定时器
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 1000 - 1; // 定时器周期为 1ms
TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1; // 定时器预分频为 7200,计数频率为 10kHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 设置定时器中断
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
// 启动定时器
TIM_Cmd(TIM2, ENABLE);
while(1);
}
void TIM2_IRQHandler(void)
{
static uint8_t led = 0x01;
GPIO_Write(GPIOB, led);
led <<= 1;
if(led == 0x00)
{
led = 0x01;
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
```
此代码使用定时器中断实现了每1ms更新一次LED灯状态的效果。其中,GPIOB的0~7口分别连接8个LED灯,TIM2定时器的预分频为7200,计数频率为10kHz,所以1ms的定时周期需要计数1000次。在定时器中断中,通过移位操作实现8个LED灯的流水效果。
阅读全文