void TIM4_init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStrtue;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStrtue;
TIM_OCInitTypeDef TIM_OCInitStrtue;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD|RCC_APB2Periph_AFIO,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);//ê±Öóê1Äü
GPIO_InitStrtue.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStrtue.GPIO_Pin=GPIO_Pin_13;
GPIO_InitStrtue.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOD,&GPIO_InitStrtue);//IO3õê¼»ˉ
GPIO_PinRemapConfig(GPIO_Remap_TIM4,ENABLE);//éèÖÃÖØó3éä
TIM_TimeBaseInitStrtue.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStrtue.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStrtue.TIM_Period=arr;
TIM_TimeBaseInitStrtue.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStrtue);//¶¨ê±Æ÷3õê¼»ˉ
TIM_OCInitStrtue.TIM_OCIdleState=TIM_OutputState_Enable;
TIM_OCInitStrtue.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStrtue.TIM_OCNPolarity=TIM_OCPolarity_High;
TIM_OC2Init(TIM4,&TIM_OCInitStrtue);
TIM_OC2PreloadConfig(TIM4,TIM_OCPreload_Enable);//3õê¼»ˉêä3ö±è½Ï2Îêy
TIM_Cmd(TIM4,ENABLE);//¶¨ê±Æ÷ê1Äü
}
以下是主程序
#include"stm32f10x.h"
#include"delay.h"
#include"timer.h"
int main()
{
u16 led0pwmval=0;
u8 dir=1;
//led();
delay_init(162);
TIM4_init(899,0);
while(1)
{
delay_ms(20);
if(dir)led0pwmval++;
else led0pwmval--;
if(led0pwmval>300)dir=0;
if(led0pwmval==0)dir=1;
TIM_SetCompare2(TIM4,led0pwmval);
}
}
LED的接口是PD13,重映射是TIM4_ch2,问题实在找不出,麻烦懂得看一下,谢了
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
void TIM4_init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStrtue;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStrtue;
TIM_OCInitTypeDef TIM_OCInitStrtue;
NVIC_InitTypeDef NVIC_InitStrtue;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD|RCC_APB2Periph_AFIO,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);
GPIO_InitStrtue.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStrtue.GPIO_Pin=GPIO_Pin_13;
GPIO_InitStrtue.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOD,&GPIO_InitStrtue);
GPIO_PinRemapConfig(GPIO_Remap_TIM4,ENABLE);
TIM_TimeBaseInitStrtue.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStrtue.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStrtue.TIM_Period=arr;
TIM_TimeBaseInitStrtue.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStrtue);
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE );
NVIC_InitStrtue.NVIC_IRQChannel=TIM4_IRQn;
NVIC_InitStrtue.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStrtue.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStrtue.NVIC_IRQChannelSubPriority=3;
NVIC_Init(&NVIC_InitStrtue);
TIM_OCInitStrtue.TIM_OCIdleState=TIM_OutputState_Enable;
TIM_OCInitStrtue.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStrtue.TIM_OCNPolarity=TIM_OCPolarity_High;
TIM_OC2Init(TIM4,&TIM_OCInitStrtue);
TIM_OC2PreloadConfig(TIM4,TIM_OCPreload_Enable);
TIM_Cmd(TIM4,ENABLE);
}
一周热门 更多>