/*
*说明:
*PA0:KEY1;PA1:KEY2;
*PA2:LED1;PA3:LED2;
*PA9:USART1_TX;PA10:USART1_RX
*/
#include "stm32f10x.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_pwr.h"
#include "stm32f10x_exti.h"
#include "system_stm32f10x.h"
#include "misc.h"
void RCC_Configuration(void);
void GPIO_Configuration(void);
void TIM2_Configuration(void);
void delay_ms(u16 time);
int main()
{
u8 led_fx=1;
u16 led_dt=0;
RCC_Configuration();
GPIO_Configuration();
TIM2_Configuration();
while(1)
{
delay_ms(10);
if(led_fx==1)
{
led_dt++;
}else{
led_dt--;
}
if(led_dt>100) led_fx=0;//可以和初始值一样
if(led_dt==0) led_fx=1;
TIM_SetCompare3(TIM2,led_dt);//通道3没有重影像是PA2对应LED1
TIM_SetCompare4(TIM2,led_dt);//通道4没有重影像是PA3对应LED2
}
}
void RCC_Configuration(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//GPIO_AFIODeInit();和下面相同效果,可以查看源码证明
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//GPIO_PinRemapConfig(GPIO_PartialRemap2_TIM2,ENABLE);//端口映射函数
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3;//GPIO_Pin_3对应channel3,主函数改为:TIM_SetCompare3
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_DeInit(TIM2);
TIM_InternalClockConfig(TIM2);
//定时器初始化
TIM_TimeBaseStructure.TIM_Period = 100-1;//初始值是100,2MHz=2000KHz,2MHz/100=0.02MHz,所有周期T=1/0.02MHz=50us,示波器显示周期应该为50us
TIM_TimeBaseStructure.TIM_Prescaler = 36-1;//36倍分频,72MHz/36=2MHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
//PWM初始化
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 50;//占空比值是50,所以占空比是:50/100=50%
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC3Init(TIM2,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse = 20;
TIM_OC4Init(TIM2,&TIM_OCInitStructure);
//TIM_OC3PreloadConfig(TIM2,TIM_OCPreload_Enable);
//TIM_ARRPreloadConfig(TIM2, ENABLE);
TIM_Cmd(TIM2,ENABLE);
TIM_CtrlPWMOutputs(TIM2,ENABLE);
}
void delay_ms(u16 time)
{
u16 i=0;
while(time--)
{
i=12000;
while(i--);
}
}