1.主函数代码部分:
#include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "PWM.h" uint8_t i; int main(void) { OLED_Init(); PWM_Init(); while(1) { for(i=0;i<=100;i++) { PWM_SetCompare(i); Delay_ms(10); } for(i=0;i<=100;i++) { PWM_SetCompare(100-i); Delay_ms(10); } } }
2.PWM.c代码部分:
#include "stm32f10x.h" // Device header void PWM_Init(void) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_Period=100-1; TIM_TimeBaseInitStruct.TIM_Prescaler=720-1; TIM_TimeBaseInitStruct.TIM_RepetitionCounter=0; TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct); TIM_InternalClockConfig(TIM2); TIM_OCInitTypeDef TIM_OCInitStruct; TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1; TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High; TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable; TIM_OCInitStruct.TIM_Pulse=50; TIM_OC1Init(TIM2,&TIM_OCInitStruct); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP; GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0; GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); TIM_Cmd(TIM2,ENABLE); } void PWM_SetCompare(uint8_t Compare) { TIM_SetCompare1(TIM2,Compare); }
3.PWM.h代码部分:
#ifndef __PWM_H #define __PWM_H void PWM_SetCompare(uint8_t Compare); void PWM_Init(void); #endif