EX.
NO : 8
PULSE WIDTH MODULATION(PWM) USING
ARM PROCESSOR
AIM :
TO WRITE AN EMBEDDED C CODE AND VERIFY THE FUNCTION OF PWM OF USING
IAR WORKBENCH AND VERIFY THE OUTPUT USING ARM CORTEX M4 STM32F407
MICROCONTROLLER KIT.
Pins used :
PC6 PWM OUTPUT ( 50%
DELAY )
PC7 PWM OUTPUT ( 25%
DELAY )
Formulas used :
PRESCALAR FREQ. =
Theory :
1) Using Prescalar, scale down the clock frequency 2) ARR resets the counter once it
reaches the ARR value
3) Counter output and CCR value 4) When counter value is lower than CCR,
gets compared to produce PWM of then the output will be high. If it is higher or
different duty cycle equal to CCR, then the output will be low
5) By varying the CCR value we can produce a
signal of different duty cycles
PROGRAM :
#include "STM32F4XX.H"
#include "STM32F4XX_RCC.H"
#include "STM32F4XX_GPIO.H“ // Header file for GPIO related predefined functions and structures
#include "STM32F4XX_TIM.H“ // Header file for TIMER related predefined functions and structures
void pin()
RCC_AHB1PeriphClockCmd(RCC_AHB1PERIPH_GPIOC,ENABLE); // Enable portc
RCC_APB1PeriphClockCmd(RCC_APB1PERIPH_TIM3,ENABLE); // Enable timer3
}
void gpio_initialize(){
GPIO_InitTypeDef s; // Declare a structure ‘s’
s.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7; // Initialize gpio pin 6 and 7
s.GPIO_Mode=GPIO_Mode_AF; // pin 6 and 7 will be in AF ( Alternative function ) mode
s.GPIO_Speed=GPIO_Speed_100MHZ;
GPIO_Init(GPIOC,&s); // Initialize the gpio structure ‘s’
GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_TIM3); // config the pin6 with timer3
GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_TIM3); // config the pin7 with timer3
}
void tim_initialize(){
// Initialize the timer with period , prescalar , up counter mode , clock division
TIM_TimeBaseInitTypeDef a;
a.TIM_Period=693;
a.TIM_Prescaler=5;
a.TIM_ClockDivision=0;
A.TIM_CounterMode=TIM_CounterMode_UP;
TIM_TimeBaseInit (TIM3,&a);
int CCR1=347; // for 50% duty cycle
int CCR2=174; // for 25% duty cycle
// OC1 for 50% duty cycle
TIM_OCInitTypeDef b;
b.TIM_OCMode=TIM_OCMode_PWM1;
b.TIM_OutputState=TIM_OutputState_Enable;
b.TIM_Pulse=CCR1;
b.TIM_OCPolarity=TIM_OCPolarity_HIGH;
TIM_OC1Init(TIM3,&b);
TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_ENABLE);
// OC2 for 25% duty cycle
b.TIM_OCMode=TIM_OCMode_PWM1;
b.TIM_OutputState=TIM_OutputState_Enable;
b.TIM_Pulse=CCR2;
b.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OC2Init(TIM3,&b);
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
// Enable ARR and Timer3
TIM_ARRPreloadConfig(TIM3,ENABLE);
TIM_Cmd(TIM3,ENABLE);
}
void main()
{
pin(); // Enable pins
gpio_initialize(); // Initialize the GPIO pins
tim_initialize(); // Initialize the timer
while(1); // Continuously produce the signal in oscilloscope
}