stm32f103 pa15输出pwm波形的代码
时间: 2023-12-04 11:01:48 浏览: 126
以下是使用STM32F103的PA15输出PWM波形的示例代码:
```c
#include "stm32f10x.h"
void GPIO_Configuration(void);
void TIM_Configuration(void);
int main(void)
{
GPIO_Configuration();
TIM_Configuration();
while(1);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 999; // PWM周期为1000个计数器时钟周期
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 时钟预分频为72,计数器时钟频率为1MHz
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 500; // 占空比为50%
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_Cmd(TIM2, ENABLE);
}
```
在此代码中,我们使用PA15作为TIM2的通道1输出PWM波形。TIM2的计数器时钟频率为1MHz,PWM周期为1000个计数器时钟周期,并且占空比为50%。
阅读全文