其他分享
首页 > 其他分享> > STM32F103ZE点亮发光二极管例程

STM32F103ZE点亮发光二极管例程

作者:互联网

    下载本程序至STM32F103ZE中,循环闪烁发光二极管,0.5ms亮,0.5ms灭。外部四个发光二极管分别接在GPIOC的PIN4,PIN6,PIN8,PIN9上。程序使用TIMER3进行定时,以中断作为触发条件,在时钟中断程序中改变状态。

    下面是例程example.h

#include "stm32f10x.h"
#include "time.h"

#define GPIO_LED_PROT GPIOC
#define GPIO_LED_CLK  RCC_APB2Periph_GPIOC
#define GPIO_LED_PIN  GPIO_Pin_9 | GPIO_Pin_8 | GPIO_Pin_6 | GPIO_Pin_4

#define LED_OFF 0
#define LED_ON  1

extern uint16_t LED_STATUS;

void GPIO_Config(void);
void Tim3_Config(uint16_t per, uint16_t psc);
void sys_init(void);

void TIM3_IRQHandler(void);

    下面是例程example.c

#include "example.h"

uint16_t LED_STATUS = LED_OFF;

void GPIO_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	RCC_APB2PeriphClockCmd(GPIO_LED_CLK, ENABLE);
	GPIO_InitStruct.GPIO_Pin = GPIO_LED_PIN;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIO_LED_PROT, &GPIO_InitStruct);
}

void Tim3_Config(uint16_t per, uint16_t psc)
{
	//step.1. enable the periph timer3
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	
	//step.2. init timer
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	TIM_TimeBaseStructure.TIM_Period = per; 
	TIM_TimeBaseStructure.TIM_Prescaler = psc; 
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; 
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; 
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); 
	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); 
	
	//step.3. timer interupt
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; 
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; 
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; 
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
	NVIC_Init(&NVIC_InitStructure); 
	
	//step.4. enable timer3
	TIM_Cmd(TIM3, ENABLE);
}

void sys_init(void)
{
	GPIO_Config();											//init GPIO
	Tim3_Config(4999,7199);							//init Timer3   0.5s
}

void TIM3_IRQHandler(void)
{	
	if (TIM_GetITStatus(TIM3, TIM_IT_Update))
	{
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update );
		if(LED_STATUS == LED_OFF)
		{LED_STATUS = LED_ON;}
		else if(LED_STATUS == LED_ON)
		{LED_STATUS = LED_OFF;}
	}
}
int main(void)
{
	sys_init();
	
	while(1)
	{
		if(LED_STATUS == LED_ON)
		{GPIO_SetBits(GPIO_LED_PROT, GPIO_LED_PIN);}
		else if(LED_STATUS == LED_OFF)
		{GPIO_ResetBits(GPIO_LED_PROT, GPIO_LED_PIN);}
	}
	return 0;
}

     在keil5环境中编译下载至STM32F103ZE中后,上电执行程序,便可观察到LED灯闪烁(板子不同,引脚选择可能不同)

标签:TIM3,LED,例程,void,STM32F103ZE,二极管,NVIC,TIM,GPIO
来源: https://blog.csdn.net/weixin_52004777/article/details/122268680