请用stm32f103c8t6单片机的高级定时器pa0口配置pwm波输出,写出标准库代码并附上注释
时间: 2023-09-07 22:11:26 浏览: 75
STM32-控制PA3TIM2-CH4输出PWM值,stm32的pwm输出,C,C++
好的,下面是标准库代码和注释:
```c
#include "stm32f10x.h"
void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
//使能TIM3和GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//设置GPIOA口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//设置TIM3
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(TIM3, &TIM_TimeBaseStructure);
//设置TIM3通道1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
//启动TIM3
TIM_Cmd(TIM3, ENABLE);
}
int main(void)
{
TIM3_PWM_Init(999, 71); //初始化PWM波,设置周期为1000,预分频为72
while (1)
{
}
}
```
注释中会详细介绍每段代码的功能:
```c
#include "stm32f10x.h" //包含STM32F10x系列单片机的头文件
void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
//使能TIM3和GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//设置GPIOA口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//设置TIM3
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(TIM3, &TIM_TimeBaseStructure); //初始化TIM3
//设置TIM3通道1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //设置PWM模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //使能TIM3的输出通道1
TIM_OCInitStructure.TIM_Pulse = 0; //设置占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //设置输出极性为高电平
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable); //使能TIM3的输出通道1的预装载功能
//启动TIM3
TIM_Cmd(TIM3, ENABLE); //使能TIM3
}
int main(void)
{
TIM3_PWM_Init(999, 71); //初始化PWM波,设置周期为1000,预分频为72
while (1)
{
}
}
```
以上是使用STM32F103C8T6单片机的高级定时器PA0口配置PWM波输出的标准库代码和注释。
阅读全文