AnsweredAssumed Answered

Quadratic Output using Output Compare

Question asked by stuk on Feb 1, 2016
Latest reply on Feb 2, 2016 by FTITI.Walid
Hi, i'm trying to use timer2 to generate two output shifted by 90 degree, like an encoder emulator. The idea is using the period of the timer2 to set the frequency, and set two output compare ch2,ch3 to set the output.
This is the code i'm using to set the timers:
01.static int numPackets;
02.static int currentPackets;
03. 
04.void setQuadraticOutputConfig(long frequency,long _numPackets,long direction)
05.{
06.    numPackets = (_numPackets*2)-1;
07.    currentPackets = 0;
08.    double tmp = 0;
09. 
10.    unsigned long period = (TIMER_FREQ/(frequency*2)-1);
11.    unsigned long pulseA = period/4;
12.    unsigned long pulseB = pulseA*3;
13. 
14.    TIM_ClockConfigTypeDef sClockSourceConfig;
15.    TIM_MasterConfigTypeDef sMasterConfig;
16.    TIM_OC_InitTypeDef sConfigOC;
17. 
18.    htim2.Instance = TIM2;
19.    htim2.Init.Prescaler = 0;
20.    htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
21.    htim2.Init.Period = period;
22.    htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
23. 
24.    HAL_TIM_Base_DeInit(&htim2);
25.    HAL_TIM_Base_Init(&htim2);
26. 
27.    sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
28.    HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig);
29.    HAL_TIM_OC_Init(&htim2);
30. 
31.    sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
32.    sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
33.    HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig);
34. 
35.    sConfigOC.OCMode = TIM_OCMODE_TOGGLE;
36.    if(direction)
37.        sConfigOC.Pulse = pulseA;
38.    else
39.        sConfigOC.Pulse = pulseB;
40.    sConfigOC.OCPolarity = TIM_OCPOLARITY_LOW;
41.    sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
42. 
43.    HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);
44.    if(direction)
45.            sConfigOC.Pulse = pulseB;
46.        else
47.            sConfigOC.Pulse = pulseA;
48.    HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3);
49. 
50.    TIM2->CNT = 0; //Force timer2 to 0
51.    HAL_TIM_OC_Start_IT(&htim2, TIM_CHANNEL_2);
52.    HAL_TIM_OC_Start_IT(&htim2, TIM_CHANNEL_3);
53. 
54.    HAL_TIM_Base_Start_IT(&htim2);
55.}

And this the interrupt:
01.void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
02.{
03.    if(htim == &htim2){
04.        if(currentPackets == numPackets)
05.        {
06.            HAL_TIM_OC_Stop(&htim2, TIM_CHANNEL_2);
07.            HAL_TIM_OC_Stop(&htim2, TIM_CHANNEL_3);
08.            HAL_TIM_Base_Stop(&htim2);
09.        }
10.        currentPackets++;
11.      }
12.}

Sometimes the first output is smaller then the others:
1.png
Or the last:
2.png

Why? Any idea?
Thanks
Stuk

Outcomes