cancel
Showing results for 
Search instead for 
Did you mean: 

PWM pulse counter doesn't work properly

JJohn.3
Associate II

Hello,

Here is code:

Prescale=7;Periode=7999;Pulse=3998;

void PWMControl(unsigned int Freq){
TIM_TimeBaseInitTypeDef     TimeStructureure; 
TIM_OCInitTypeDef       TIMOCStructureure;  
        
        TimeStructure.TIM_Prescaler=Prescale;
        TimeStructure.TIM_CounterMode=TIM_CounterMode_Up;
        TimeStructure.TIM_Period=Period;
        TimeStructure.TIM_ClockDivision=TIM_CKD_DIV1;
        TimeStructure.TIM_RepetitionCounter=0;
        TIM_TimeBaseInit(TIM4, &TimeStructure);
        TIM_Cmd(TIM4, ENABLE);  
    
        TIMOCStructure.TIM_OCMode=TIM_OCMode_PWM2;
        TIMOCStructure.TIM_OutputState=TIM_OutputState_Enable;
        TIMOCStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
        TIMOCStructure.TIM_Pulse=Pulse;
        TIM_OC1Init(TIM4, &TIMOCStructure);
        //TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);     
        TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE);    
}
    
 
void TIM4_IRQHandler(){
 
    if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
    {   
        X=X+1;
        TIM_Cmd(TIM4, DISABLE);
        TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
    }       
}

The above code generates a 1Khz with 50% duty cycle with interrupt. However, by counting the X variable(TIM4_IRQHandler) each second I should have 1000 pulses but I get 100 pulses each second. I am curious to know what my problem is.

1 ACCEPTED SOLUTION

Accepted Solutions

How do you observe the X variable from the first program?

It's probably not a long program, can you please post it completely, in a compilable form, exactly as you've tested it (where you've found X to increment by 100 each second)?

JW

View solution in original post

4 REPLIES 4

Try to toggle a pin in the IRQHandler and observe together with the PWM pin on oscilloscope/logic analyzer.

JW

JJohn.3
Associate II

Thank you very much for your comment.

I changed my program to

void TIM4_IRQHandler(){
	
			if(X!=1){
					X=1;
					GPIO_SetBits(GPIOE,GPIO_Pin_13);
			}else
			{
					X=0;
					GPIO_ResetBits(GPIOE,GPIO_Pin_13);
			}	
 
	
					TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
					//TIM_Cmd(TIM4, ENABLE);	
}

and Here is my output:

0693W000007C47mQAC.jpgand Here is my PWM output

0693W000007C47wQAC.jpg They are the same( my PWM takes 1ms to make a Pulse , and my IRQ Toggle the output at 1ms,Am I right?) my variable is long volatile but it takes the wrong value.

How do you observe the X variable from the first program?

It's probably not a long program, can you please post it completely, in a compilable form, exactly as you've tested it (where you've found X to increment by 100 each second)?

JW

Thank you very much , it was related to showing the X variable.