AnsweredAssumed Answered

Square wave generation with STM32 and timer

Question asked by paul sauv on Sep 6, 2017
Latest reply on Sep 7, 2017 by paul sauv

hi everyone,

I'm trying to generate a square wave / quadrature signal ( 2 square wave with 90 degrees offset). The board is a STM32F103C8

The goal of the project will be to send an exact number of pulse. Frequency will stay the same. I will have to be able to switch the direction of the signal such as a quadrature encoder.
Right now, I just want to have a clean quadrature signal. My code is not complicated at the moment and here are the 2 mains functions in order to initialize the timer:

void init_SW()
GPIO_InitTypeDef GPIO_InitStruct;
// Step 1: Initialize GPIO as input for rotary encoder
// PB7 (TIM4_CH2) (encoder pin A), PB6 (TIM4_CH1) (encoder pin B)
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_6;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
// Step 2: Setup TIM4 for encoder input

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructInit (&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 3;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseInit (TIM4, &TIM_TimeBaseStructure);

void timer_ccr_init (void)
TIM_OCInitTypeDef TIM_OCInitStructure;
/* always initialise local variables before use */
TIM_OCStructInit (&TIM_OCInitStructure);

/* Common settings for all channels */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;

/* Channel1 */
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OC1Init (TIM4, &TIM_OCInitStructure);

/* Channel2 - 90 degres after*/
TIM_OCInitStructure.TIM_Pulse = 1;
TIM_OC2Init (TIM4, &TIM_OCInitStructure);

Right now, my signal is absolutely not square. This is the first time I'm using a timer to generate a signal.

I tried to take what I needed from here  and adapt but without success right now


Thank you for your help