본문 바로가기

컴퓨터/Cortex-M3(STM32F103)

STM32F103 PWM

#include <stm32f10x.h>


void RCC_Configuration() {

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);

}


void GPIO_Configuration() {

GPIO_InitTypeDef GPIO_InitStructure;

    /* GPIOB Configuration:Pin6, 7, 8 and 9 as alternate function push-pull */

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init(GPIOB, &GPIO_InitStructure);

}


void TIM_Configuration() {

TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

TIM_OCInitTypeDef TIM_OCInitStructure;

TIM_TimeBaseStructure.TIM_Period = 999;

TIM_TimeBaseStructure.TIM_Prescaler = 0;

TIM_TimeBaseStructure.TIM_ClockDivision = 0;

TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

/* PWM1 Mode configuration: Channel1 */

TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; // 0x60, "110"

TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;

TIM_OCInitStructure.TIM_Pulse = 0; //0~1000

TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

TIM_OC1Init(TIM4, &TIM_OCInitStructure);

TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);

TIM_ARRPreloadConfig(TIM4, ENABLE);

/* TIM4 enable counter */

TIM_Cmd(TIM4, ENABLE);

}


void delay_us(vu32 delay) {

while(delay--);

}


int main()

{

u16 pwmval;

RCC_Configuration();

GPIO_Configuration();

TIM_Configuration();

  while(1){

for(pwmval=0;pwmval<=1000;pwmval++) {

TIM4->CCR1 = pwmval;

delay_us(10000);

}

}

}