pwm.c
#include "pwm.h"
//TIM3-CH3
//PB0
void PWM_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period=9999;
TIM_TimeBaseInitStruct.TIM_Prescaler=71;
TIM_TimeBaseInitStruct.TIM_ClockDivision=0;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_Low;
TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse=4999;
TIM_OC3Init(TIM3, &TIM_OCInitStruct);
TIM_Cmd(TIM3, ENABLE);
}
pwm.h
#ifndef __PWM_H
#define __PWM_H
#include "stm32f10x.h"
void PWM_Config(void);
#endif
main.c
#include "stm32f10x.h"
#include "pwm.h"
#include "delay.h"
uint16_t a = 0;
int main(void)
{
PWM_Config();
delay_init();
while(1)
{
for(a = 4999; a > 0; a--)
{
TIM_SetCompare3(TIM3, a);
delay_us(200);
}
for(a = 0; a < 5000; a++)
{
TIM_SetCompare3(TIM3, a);
delay_us(200);
}
}
}
- 用了重映射则需要
- 开启复用时钟
- 使能GPIO重映射GPIO_PinRemapConfig
- GPIO输出模式一定是复用推挽