利用已经建立的工程模板,在Keil for ARM V5中编写代码,使用按键控制LED灯电路,实现如下功能:选择两个定时器,分别控制LED1和LED2,使得LED1每1秒钟改变一次状态,和LED2每2秒钟改变一次状态。
main.c
int main()
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
ST_Init();
LED1 = 1; LED2 = 1;LED3 = 1;LED4 = 1;
TIM2_Init(1000 - 1 , 7200 - 1);
TIM3_Init(2000 - 1 , 7200 - 1);
while(1)
{
}
}
st.c
#include "st.h"
void ST_Init()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB , ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
st.h
#ifndef __ST_H
#define __ST_H
#include "sys.h"
#define LED1 PBout(8)
#define LED2 PBout(9)
#define LED3 PBout(10)
#define LED4 PBout(11)
void ST_Init(void);
#endif
time.c
#include "time.h"
#include "st.h"
void TIM2_Init(u16 arr , u16 psc)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 , ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, & TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE );
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2,ENABLE);
}
void TIM3_Init(u16 arr , u16 psc)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3 , ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV2;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, & TIM_TimeBaseStructure);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE );
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3,ENABLE);
}
void TIM2_IRQHandler()
{
LED1=~LED1;
TIM_ClearFlag(TIM2,TIM_IT_Update);
}
void TIM3_IRQHandler()
{
LED2=~LED2;
TIM_ClearFlag(TIM3,TIM_IT_Update);
}
time.h
#ifndef __TIME_H
#define __TIME_H
#include "sys.h"
void TIM1_Init(u16 arr , u16 psc);
void TIM2_Init(u16 arr , u16 psc);
#endif