zoukankan      html  css  js  c++  java
  • STM32F0的PWM配置

    void PWM3_Config(void){
        TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
        TIM_OCInitTypeDef TIM_OCInitStructure;
        uint16_t TimerPeriod = 0;
        uint16_t Channel1Pulse = 0, Channel2Pulse = 0;
        
        GPIO_InitTypeDef GPIO_InitStructure;
        RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;                          //这里设置的输出引脚为A6
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
        GPIO_Init(GPIOA,&GPIO_InitStructure);
        
        GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_1);       //F0还需要设置AF为功能1
     
        TimerPeriod = (SystemCoreClock/17570)-1;
        Channel1Pulse = (uint16_t)(((uint32_t)5*(TimerPeriod -1)) / 100);   //这里设置了高电平的时长, 这个公式的意思其实是1/20的时长是高电平, 举个例子, 现在F0的SystemCoreClock是48M, TimerPeriod=2700, 除以20, 就是136左右.
        
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
        
        TIM_TimeBaseStructure.TIM_Prescaler = 0;
        TIM_TimeBaseStructure.TIM_CounterMode =  TIM_CounterMode_Up;
        TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
        TIM_TimeBaseStructure.TIM_ClockDivision = 0;
        TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
        
        TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
        
        TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
        TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
        TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
        TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
        TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCPolarity_Low;
        TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
        TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;
        
        TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
        TIM_OC1Init(TIM3, &TIM_OCInitStructure);
        
        TIM_Cmd(TIM3, ENABLE);
        TIM_CtrlPWMOutputs(TIM3, ENABLE);
    }

    如何动态配置PWM的占空比呢, 直接用调用一个函数:

    TIM_SetCompare1(TIM3,2700);  // 这个2700就是刚才设置的TimerPeriod, 即最大值为2700, 这个比较值要比2700小, 就是高电平, 也就是刚才的Pulse值其实就是相当于TIM_SetCompare1(TIM3,136); 即从0-136这段时间, 为高电平, 137-2700为低电平.

  • 相关阅读:
    C++ 并发编程 01 线程api
    C# CS1591 缺少对公共可见类型或成员的 XML 注释 问题解决
    Web Api HelpPage
    C++11新特性介绍 02
    C++11新特性介绍 01
    Autofac框架详解
    Linux gdb调试器用法全面解析
    BCM_SDK命令
    VLAN
    java_Observer Design Pattern
  • 原文地址:https://www.cnblogs.com/Montauk/p/6408655.html
Copyright © 2011-2022 走看看