I would like to ask some help here for the troubles occurred in PWM generation on timer output channel.
I am debugging STM32F103C8T6 and I want to realize to generate PWM with duty cycle=50%,Frequency=50Hz using General Purpose Timer2 in output channel 2 which is at PA1 or pin number 11. My target system is STM32 BluePill development board.
The datasheet of STM32F103C8T6
My code is as following:
Code: Select all
/**************************** Header file *******************************/#include<stm32f10x.h>
/*************************** user defined function **********************/
/************************************************************************
Name : PWM_Init()
Description : Initializes PWM hardware and associated GPIO ports
Enables clocks for peripherals and configure modes
Parameters : None
Return_val : None
************************************************************************/void PWM_Init(){
/****configure clocks for PORTA & TIMER2********/
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; // enable port a clock
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; // enable clock for timer 2
/***** configure GPIOA mode *******************/
/* Porta Pin 1 &2 as alternate function output Push pull 50 MHz */
GPIOA->CRL = 0x000000bb;
/*******Set timer 2 Period for PWM**************
Timer Clock = 72MHz = 72000000 Hz
Time Period Required = (1/50Hz) = 0.02 Seconds
Let ARR value be 65535 then,
Prescalar + 1 = 72000000/((ARR+1)*50Hz)
Prescalar = 21 (approx)
***********************************************/
TIM2->ARR = 65535; // Set Auto reload value
TIM2->PSC = 21; // Set Prescalar value
/* Output Compare Mode, ENABLE Preload,PWM mode:2*/
TIM2->CCMR1 = 0x00007800;
TIM2->EGR |= TIM_EGR_UG; // ENABLE update generation
/*CC2E : channel 2 enabled; polarity : active high*/
TIM2->CCER = 0x00000010;
TIM2->CR1 |= TIM_CR1_ARPE; // Auto preload ENABLE
TIM2->CR1 |= TIM_CR1_CEN; // ENABLE Timer counter
}/**************Main Function**********************************/int main()
{
PWM_Init(); // initialize PWM
while(1)
{
TIM2->CCR2 = 32768; // SET duty cycle to 50%
}
}
Please kindly give me some suggestions if there are any corrections that need to be done.
Thanks a lot !