STM32基本定时器控制LED闪烁代码
阅读原文时间:2023年07月09日阅读:1

led.c

#include "led.h"

void LED_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

    GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_PP;
    GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0;
    GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStruct);
}

void LED_Toggle(void)
{
    GPIOB->ODR ^= GPIO_Pin_0;
}

led.h

#ifndef __LED_H
#define __LED_H

#include "stm32f10x.h"

void LED_Config(void);
void LED_Toggle(void);

#endif

tim_timebase.c

#include "tim_timebase.h"
#include "led.h"

int a = 0;

static void NVIC_Config(void)
{
    NVIC_InitTypeDef NVIC_InitStruct;

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitStruct.NVIC_IRQChannel=TIM3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;
    NVIC_Init(&NVIC_InitStruct);
}

void TIM3_Config(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

    NVIC_Config();

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

    TIM_TimeBaseInitStruct.TIM_Period=71;
    TIM_TimeBaseInitStruct.TIM_Prescaler=1000;//1ms
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);

    TIM_ClearFlag(TIM3, TIM_FLAG_Update);

    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    TIM_Cmd(TIM3, ENABLE);
}

void TIM3_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM3, TIM_IT_Update)) a++;
    if(a == 1000)
    {
        LED_Toggle();
        a = 0;
    }
    TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}

tim_timebase.h

#ifndef __TIM_TIMEBASE_H
#define __TIM_TIMEBASE_H

#include "stm32f10x.h"

void TIM3_Config(void);

#endif

main.c

#include "stm32f10x.h"
#include "led.h"
#include "tim_timebase.h"

int main(void)
{
    LED_Config();
    TIM3_Config();

    while(1)
    {

    }
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章