I have some simple firmware written for an ATmega328 (not Arduino) and I'm converting to STM32.
I have more than one STM32 development board, so for now I'm searching a generic config and generic code.
The original firmware generates PWM (duty cycle 50%) and every 8 cycles inverts the signal with register TCCR1A and set bits COM1A1 and COM1A0.
Here is the source code:
uint8_t var = 0;
ISR(TIMER2_COMPA_vect)
{
if (var)
TCCR1A = _BV(COM1A1) | _BV(WGM11);
else
TCCR1A = _BV(COM1A1) | _BV(COM1A0) | _BV(WGM11);
var != var;
PORTC = var & 1;
}
int main(void)
{
//Set OC1A as output
DDRB = (1 << PB1);
//Set PC0 as output
DDRC = (1 << PC0);
//Halt timers
GTCCR = (1 << TSM)|(1 << PSRASY)|(1 << PSRSYNC);
//Set timer one to Fast PWM (ICR1 = TOP)
ICR1 = 23;
OCR1A = 11;
TCCR1A = (1 << COM1A1) | (1 << WGM11);
TCCR1B = (1 << CS10) | (1 << WGM12) | (1 << WGM13);
//Set timer two to CTC mode (OCR2A = TOP)
OCR2A = (23*8)+11;
TIMSK2 = (1 << OCIE2A);
TCCR2A = (1 << WGM21);
TCCR2B = (1 << CS20);
//Reset all timer
TCNT0 = 0;
TCNT1 = 0;
TCNT2 = 0;
//Restart all timers
GTCCR = 0;
//Enable interrupts
sei();
while (1);
}
Timer1 is used for generating PWM, while TIMER2 is used for inverting the signal.
The output on oscilloscope:
In my configuration of the STM32 I have used two synchronized timers, master and slave. The master generates the PWM (channel 1) TRGO update event, and the slave is configured as external clock 1, trigger timer master, output compare no output channel 1.
I tested many values for the counter period and pulse, but none is working very well. For inverting the initial state of PWM I used ch polarity, but is not very good as a solution.
When there is an interrupt for the timer with output compare, I execute this code (TIM2 in my case generates PWM):
void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
{
static uint8_t tx = 0;
while(TIM2->CNT);
if (tx == 0) {
TIM2->CCER = 1;
} else {
TIM2->CCER = 3;
}
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_0, tx == 1 ? GPIO_PIN_SET : GPIO_PIN_RESET);
tx = !tx;
}
This is the output of oscilloscope for the STM32:
There are wrong glitches. This is execution in release mode; when executed with debug, the glitches are less "pronounced".
Is there a better way for generating this signal? The STM32 has many configurations, but I can't find a way.