qditer的个人空间 https://bbs.21ic.com/?544816 [收藏] [复制] [RSS]

日志

stm32之TIM1的PWM

已有 1373 次阅读2013-9-16 21:41 |个人分类:stm32|系统分类:单片机| stm32, TIM1, PWM

       
  1. //配置时钟
  2. RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_TIM1,ENABLE);
  3. //设置IO为复用输出
  4.   GPIO_InitTypeDef GPIO_InitStructure;
  5.   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 ;
  6.   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  7.   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  8.   GPIO_Init(GPIOA, &GPIO_InitStructure);
  9. //定时器1配置
  10. void TIM_Configuration(void)
  11. {
  12.     TIM1_TimeBaseInitTypeDef TIM1_BaseInitStructure;
  13.     TIM1_OCInitTypeDef TIM1_OCInitStructure;
  14.     TIM1_BDTRInitTypeDef TIM1_BDTRInitStructure;

  15.     //TIM1基本计数器设置(设置PWM频率)
  16.     //频率=TIM1_CLK/(ARR+1)
  17.     TIM1_BaseInitStructure.TIM1_Period = 1000-1;
  18.     TIM1_BaseInitStructure.TIM1_Prescaler = 72-1;
  19.     TIM1_BaseInitStructure.TIM1_ClockDivision = 0;
  20.     TIM1_BaseInitStructure.TIM1_CounterMode = TIM1_CounterMode_Up;
  21.     TIM1_BaseInitStructure.TIM1_RepetitionCounter = 0;
  22.     TIM1_TimeBaseInit(&TIM1_BaseInitStructure);
  23.     //启用ARR的影子寄存器(直到产生更新事件才更改设置)
  24.     TIM1_ARRPreloadConfig(ENABLE);


  25.     //TIM1_OC1模块设置(设置1通道占空比)
  26.     TIM1_OCInitStructure.TIM1_OCMode = TIM1_OCMode_PWM1;
  27.     TIM1_OCInitStructure.TIM1_OutputState = TIM1_OutputState_Enable;
  28.     TIM1_OCInitStructure.TIM1_OutputNState = TIM1_OutputNState_Enable;
  29.     TIM1_OCInitStructure.TIM1_OCPolarity = TIM1_OCPolarity_High;
  30.     TIM1_OCInitStructure.TIM1_OCNPolarity = TIM1_OCNPolarity_High;
  31.     TIM1_OCInitStructure.TIM1_Pulse = 120;
  32.     TIM1_OC1Init(&TIM1_OCInitStructure);
  33.     //启用CCR1寄存器的影子寄存器(直到产生更新事件才更改设置)
  34.     TIM1_OC1PreloadConfig(TIM1_OCPreload_Enable);

  35.     //TIM2_OC2模块设置(设置2通道占空比)
  36.     TIM1_OCInitStructure.TIM1_OutputState = TIM1_OutputState_Enable;
  37.     TIM1_OCInitStructure.TIM1_OutputNState = TIM1_OutputNState_Enable;
  38.     TIM1_OCInitStructure.TIM1_Pulse = 680;
  39.     TIM1_OC2Init(&TIM1_OCInitStructure);
  40.     //启用CCR2寄存器的影子寄存器(直到产生更新事件才更改设置)
  41.     TIM1_OC2PreloadConfig(TIM1_OCPreload_Enable);
  42.    
  43.     //死区设置
  44.     TIM1_BDTRInitStructure.TIM1_OSSRState = TIM1_OSSRState_Enable;
  45.     TIM1_BDTRInitStructure.TIM1_OSSIState = TIM1_OSSIState_Enable;
  46.     TIM1_BDTRInitStructure.TIM1_LOCKLevel = TIM1_LOCKLevel_OFF;
  47.     TIM1_BDTRInitStructure.TIM1_DeadTime = 0x90;  //这里调整死区大小0-0xff
  48.     TIM1_BDTRInitStructure.TIM1_Break = TIM1_Break_Disable;
  49.     TIM1_BDTRInitStructure.TIM1_BreakPolarity = TIM1_BreakPolarity_High;
  50.     TIM1_BDTRInitStructure.TIM1_AutomaticOutput = TIM1_AutomaticOutput_Enable;
  51.     TIM1_BDTRConfig(&TIM1_BDTRInitStructure);
  52.    
  53.     //TIM1开启
  54.     TIM1_Cmd(ENABLE);
  55.     //TIM1_OC通道输出PWM(一定要加)
  56.     TIM1_CtrlPWMOutputs(ENABLE);
  57. }
复制代码


路过

鸡蛋

鲜花

握手

雷人

评论 (0 个评论)