stm32 timers HAL_TIM_PerioidElapsedCallback() not triggering - timer

I'm just starting to learn how to program ARM microcontrollers using ST's HAL. So I have this code which generates a 1khz and 20khz signal using a timer in output compare mode. That all works well and I tested it with a scope and it's as expected. The issue is with HAL_TIM_PeriodElapsedCallback() which should get called when whenever the timer has overflown and toggle an LED. The LED's configuration is correct.HAL_TIM_PeriodElapsedCallback() gets called by HAL_TIM_IRQHandler(&htim3); which is called whenever an interrupt for timer3 is fired such as when the timer overflows. HAL_TIM_IRQHandler(&htim3); also gets called often when the output compare register matches that of the timers 'count' register and it calls HAL_TIM_OC_DelayElapsedCallback(). This all works, so I know the timer3 interrupt is configured properly but I just cant figure out why when the timer overflows the correct callback doesn't get called. What I'm guessing is that the interrputs fired by the Output Compare somehow mess with the overflow interrupt. I've also tried using a debugger and following the code, but HAL_TIM_OC_DelayElapsedCallback() is just skipped. I've included my main() as well as the relevant code from the HAL_Timer library which handles all interrupts.
Please help me debug this!
PS. Nucleo_BSP_Init(); simply configures the clock and the GPIO so I won't put this code, since I know the LED works and the clock is configured using CubeMX so that should also be fine.
----------------MAIN CODE --------------------
#include "stm32f4xx_hal.h"
#include <nucleo_hal_bsp.h>
#include <string.h>
/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim3;
void MX_TIM3_Init(void);
uint16_t computePulse(TIM_HandleTypeDef *htim, uint32_t chFrequency) {
uint32_t timFrequency= HAL_RCC_GetPCLK1Freq() / (htim->Instance->PSC + 1);
return (uint16_t)(timFrequency / chFrequency);
}
volatile uint16_t CH1_FREQ = 0;
volatile uint16_t CH2_FREQ = 0;
int main(void) {
HAL_Init();
Nucleo_BSP_Init();
MX_TIM3_Init();
HAL_TIM_OC_Start_IT(&htim3, TIM_CHANNEL_1);
HAL_TIM_OC_Start_IT(&htim3, TIM_CHANNEL_2);
while (1);
}
/* TIM3 init function */
void MX_TIM3_Init(void) {
TIM_OC_InitTypeDef sConfigOC;
htim3.Instance = TIM3;
htim3.Init.Prescaler = 2;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 65535;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_OC_Init(&htim3);
CH1_FREQ = computePulse(&htim3, 1000);
CH2_FREQ = computePulse(&htim3, 20000);
sConfigOC.OCMode = TIM_OCMODE_TOGGLE;
sConfigOC.Pulse = CH1_FREQ;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
sConfigOC.OCMode = TIM_OCMODE_TOGGLE;
sConfigOC.Pulse = CH2_FREQ;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2);
}
void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) {
uint32_t pulse;
/* TIMx_CH1 toggling with frequency = 1KHz */
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
pulse = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
/* Set the Capture Compare Register value */
__HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_1, (pulse + CH1_FREQ));
}
/* TIM2_CH2 toggling with frequency = 20KHz */
if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
{
pulse = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
/* Set the Capture Compare Register value */
__HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_2, (pulse + CH2_FREQ));
}
}
void HAL_TIM_OC_MspInit(TIM_HandleTypeDef* htim_base) {
GPIO_InitTypeDef GPIO_InitStruct;
if(htim_base->Instance==TIM3) {
__TIM3_CLK_ENABLE();
/**TIM3 GPIO Configuration
PA6 ------> TIM3_CH1
PA7 ------> TIM3_CH2
*/
GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM3;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_NVIC_SetPriority(TIM3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM3_IRQn);
}
}
void TIM3_IRQHandler(void) {
HAL_TIM_IRQHandler(&htim3);
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
if(htim->Instance == TIM3){
// HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);
HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
}
}
IRQ Handler code which gets callled whenever an interupt is fired.
void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
{
/* Capture compare 1 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) !=RESET)
{
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
/* Input capture event */
if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
}
/* Capture compare 2 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
/* Input capture event */
if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 3 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
/* Input capture event */
if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 4 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
/* Input capture event */
if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* TIM Update event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
HAL_TIM_PeriodElapsedCallback(htim);
}
}
/* TIM Break input event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK);
HAL_TIMEx_BreakCallback(htim);
}
}
/* TIM Trigger detection event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER);
HAL_TIM_TriggerCallback(htim);
}
}
/* TIM commutation event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM);
HAL_TIMEx_CommutationCallback(htim);
}
}
}

I had a similar situations and after a bit of digging traced it down to this statement in the ST drivers IRQ Handler, the same that you have included in the question:
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) !=RESET)
Confusingly named, this line is actually checking whether the Update callback is enabled.
I therefore was able to trigger the callback once I enabled the TIM_IT_UPDATE feature...
This can be done in two ways (links are referencing the G4 HAL drivers):
Using the HAL_TIM_Base_Start_IT() (Not Recommended)
Which enables this feature as a consequence
HAL_TIM_Base_Start_IT(htim)
Note: This is only "not recommended" as you are using the OC mode
Using __HAL_TIM_ENABLE_IT()
Running this in an initializing section (e.g. HAL_TIM_OC_MspInit()) :
__HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE);
Notes
I would probably suggest the second option if it works for you, as the ST docstring suggests the former is for setting the timer as a Timer base, which may have unintended consequences for this use case.

Related

Callback in STM32 isn't called

Trying to make simple PWM transmitter i faced with a problem. I have TIM2 with Channel2 (in PWM Generation mode) on board NUCLEO F042K6 and USART1 connected to the board in Async mode (USART works in DMA).
I wanted to make a PWM transmitter that uses a circular buffer that can be filled with one character or several characters at once. The plan was that when the user enters a character (or several characters), the idle line callback is processed, in which a function is called that stores the data in a cyclic buffer. After saving, the data transferred to the buffer is passed to the function PWM_SendChar(...) to convert the data into bits and transfer them over the PWM line. But the problem is when the program goes into PWM_SendChar(...) the callback HAL_TIM_PWM_PulseFinishedCallback(...) isn't called and program stucks in infinite while loop because variable used as a flag for detecting the end of single pulse (PWM_data_sent_flag) wasn't set to value 1.
However, if I use HAL_UART_Recieve(...) func in while(1) loop (located in main(void)) to recieve a char from user program works fine without stucking in while loop in TIM callback. Ofc, for this method I don't use HAL_UARTEx_RxEventCallback(...) and cycle buffer.
Thats's why I think the problem is in USART idle line detection and please help me solve it.
Code Example
Global variable used for waiting the end of pulse:
volatile uint16_t PWM_data_sent_flag = 0;
PWM timer callback:
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) {
if (htim->Instance == TIM2) {
HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_2);
PWM_data_sent_flag = 1;
}
}
Callback for USART idle line:
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) {
if (huart == &huart1) {
// Function_to_save_input_char_in_cycle_buffer() is called
}
}
Function used to send char as a PWM signal (emited after Function_to_save_input_char_in_cycle_buffer() completed):
void PWM_SendChar(char ch) {
for (int i = 0, mv = 7; i <= 7; ++i, --mv) {
uint8_t bit = (ch & (1 << mv)) ? 1 : 0;
// PWM_LOW_PERCENT encodes bit with zero value, PWM_HIGH_PERCENT encodes bit with value one
uint16_t duty_cycle = bit == 0 ? PWM_LOW_PERCENT : PWM_HIGH_PERCENT;
// Change TIM2 CCR2 value according to bit's value
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2,
GET_PERCENT_VALUE(TIM2->ARR, duty_cycle));
HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_2);
// Program comes to this cycle and doesn't leave it
while (!PWM_data_sent_flag)
;
PWM_data_sent_flag = 0;
}
}
USART receive to idle launch (half data transmitted callback disabled):
int main(void) {
// Init code
// ...
if (HAL_UARTEx_ReceiveToIdle_DMA(&huart1, (uint8_t*) ring_buf.buff,
ARRAY_LEN(ring_buf.buff)) != HAL_OK) {
Error_Handler();
}
// Disable half word transmitted callback
__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
while(1) {
}
}
TIM2 settings:
static void MX_TIM2_Init(void) {
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = { 0 };
TIM_MasterConfigTypeDef sMasterConfig = { 0 };
TIM_OC_InitTypeDef sConfigOC = { 0 };
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 48000 - 1;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 100 - 1;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK) {
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig)
!= HAL_OK) {
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2)
!= HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
USART1 settings:
static void MX_USART1_UART_Init(void) {
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK) {
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
DMA settings:
static void MX_DMA_Init(void) {
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel4_5_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel4_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel4_5_IRQn);
}

stm32f103 internal interrupt can not reach the wanted frequency (350ns) (lowest reached is 4us)

i am trying to generate a PWM signal by turning a GPIO pin high and low using an interrupt generated by TIMER1, why i am doing it this way is a whole different story, so i need to generate an interrupt every 350ns, i calculated prescaler and the ARR for 72MHz and i found out that i need a prescaler of 1 and an ARR of 25 so i set the parameters according to these values, now i have 25 clock cycle to do what i want before the next interrupt triggers, so at each interrupt the specified pin has to change state (High to Low or Low to High), i am looking at the output signal using an oscilloscope and i am stuck with an output of 8us (which means an interrupt every 4 us), how can i fix this? where am i failing? what am i possibly doing wrong?
Here is what i am doing in the interrupt function:
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if ((GPIOC->ODR & GPIO_PIN_13) != 0x00u)
{
GPIOC-> ODR = 0x0000;
}
else
{
GPIOC-> ODR = 0x2000;
}
}
Here is a photo of the output signal :
Oscilloscope output
is it possible that the code inside the interrupt exceeds 25 clock cycle? if so how can i do it without exceeding ? thanks
is it possible that the code inside the interrupt exceeds 25 clock
cycle? if so how can i do it without exceeding ? thanks
If you use HAL stop counting clocks :)
So firstly we have the original handler: interrupt entry takes about 12 clocks + FLASH wait states
void TIMx_IRQHandler(void)
{
HAL_TIM_IRQHandler(&TimHandle);
}
Then we call HAL handler + min 3 clocks + waitstates as the pipeline is flushed.
Then we have HAL function - a lots of clock cycles:
void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
{
/* Capture compare 1 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) !=RESET)
{
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
/* Input capture event */
if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
}
/* Capture compare 2 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
/* Input capture event */
if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 3 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
/* Input capture event */
if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 4 event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
/* Input capture event */
if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U)
{
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
else
{
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* TIM Update event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
HAL_TIM_PeriodElapsedCallback(htim);
}
}
/* TIM Break input event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK);
HAL_TIMEx_BreakCallback(htim);
}
}
/* TIM Trigger detection event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER);
HAL_TIM_TriggerCallback(htim);
}
}
/* TIM commutation event */
if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
{
if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) !=RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM);
HAL_TIMEx_CommutationCallback(htim);
}
}
}
and eventually call to your function which execution will take between 8 and 15 clocks.
So if you have 25clocks in total you are a really lucky man.

Why wouldn't my HAL_UART IT capture callback routine trigger?

I'm trying to establish communication between two STM32F103 MCU's via UART. I'm using STMCubeMX to build peripheral initalization. I've logicaly named the MCU's as MASTER and SLAVE. Slave UART is configured as Transmit only, while MASTER uart is recieve only. I'm using HAL drivers to program the MCU in AtollicTRUEstudio IDE. I want to send uint32_t value, buffer_USART1_rx is declared as volatile uint8_t buffer_USART1_rx[10]. Basicly SLAVE UART transmit is being triggered by Systick timer every 1 second, while MASTER UART is defined in IT mode, and soon as the interrupt happens it read the transmited value.
I connected the osciloscope probe to the PA10 RX pin of MASTER and i noticed the UART signal is fine and transmiting over the wires. But the value being transmitted is always 0 and breakpoint in HAL_UART_RxCpltCallback is never activated. Since the osciloscope signal is correct, i'm thinking it's a software issue.
Image of RX PA10 pin of MASTER stm32
This is from MASTER STM (code is located in main file)
UART initialization:
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
static void MX_NVIC_Init(void)
{
/* USART1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
__NOP();
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/*UART1 water level from SLAVE */
if(huart->Instance==USART1)
{
water_level=getUSART1();
/* Water level change triggers LCD refresh */
if(water_level_prev!=water_level)
{
lcd_screen_refresh=true;
}
water_level_prev=water_level;
}
else
{
__NOP();
}
/*UART2 target level from NANOPI */
if(huart->Instance==USART2)
{
target_level_pi=getUSART2();
/* Target level change triggers LCD refresh */
if(target_level_pi!=target_level_prev)
{
lcd_screen_refresh=true;
}
}
else
{
__NOP();
}
}
UART deserialize function:
uint32_t getUSART1()
{
uint32_t num=0;
num |= buffer_USART1_rx[0] << 24;
num |= buffer_USART1_rx[1] << 16;
num |= buffer_USART1_rx[2] << 8;
num |= buffer_USART1_rx[3];
return num;
}
In main file initialization of UART in IT mode:
/* Initialize TIM/UART interrupts */
HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_2);
HAL_UART_Receive_IT(&huart1, buffer_USART1_rx, 4);
SLAVE MCU configuration :
// This is in while loop
if(send_USART==true)
{
buffer[0] = test ;
buffer[1] = test >>8;
buffer[2] = test >> 16;
buffer[3] = test >> 24;
HAL_UART_Transmit(&huart1,buffer,4,2000);
}
else
{
__NOP();
}
// Callback
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
send_USART=false;
}
//Systick timer triggers UART transmit every 1 second
void HAL_SYSTICK_Callback()
{
sys_timer++;
if(sys_timer>=1000)
{
sys_timer=0;
send_USART=true;
}
else
{
__NOP();
}
}
//Global declaration of variables used
/* Timer variables */
uint8_t buffer[10];
volatile uint32_t sys_timer=0;
uint32_t test=10;
/* Boolean variables */
bool send_USART=false;
// UART initialization
/* USART1 init function */
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
static void MX_NVIC_Init(void)
{
/* USART1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(USART1_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
}
I expect the recieved value to be 10. (since i'm serializing "test" variable on SLAVE stm, and sending it on MASTER stm while deserializing it)
Nevermind, i've found the issue and what was causing it
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
if(huart1.RxState==HAL_UART_STATE_READY)
{
HAL_UART_Receive_IT(&huart1,buffer_USART1_rx,4);
uart1_received=4; //flag da je primljen podatak
__HAL_UART_FLUSH_DRREGISTER(&huart1);
__HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_RXNE);
}
else
{
__NOP();
}
/* USER CODE END USART1_IRQn 1 */
}
The code for handling was above the HAL_UART_IRQHandler(&huart1); . That's why it only recieved data once. When I copied it below like on the code above, everything works fine.

STM32 Blinking LEDs with a Timer

I'm trying to blink 4 LEDs with a Timer Interrupt, at different frequencies.
I came up with this code
/*********** Includes ****************/
#include "stm32f4xx.h"
#include "stm32f4_discovery.h"
/*********** Defines *****************/
#define TIM3_CK_CNT 50000
/*********** Declarations *************/
/*------ Function prototypes ---------*/
void TimerConfiguration(void);
/* ----- Global variables ----------- */
volatile uint16_t CCR1_Val = 50000;
volatile uint16_t CCR2_Val = 40000;
volatile uint16_t CCR3_Val = 30000;
volatile uint16_t CCR4_Val = 20000;
/************ Main *********************/
int main(void)
{
// LED initialization
STM_EVAL_LEDInit(LED3); // Orange
STM_EVAL_LEDInit(LED4); // Green
STM_EVAL_LEDInit(LED5); // Red
STM_EVAL_LEDInit(LED6); // Blue
/* TIM3 Configuration */
TimerConfiguration();
while (1);
}
/*********** Functions *****************/
/**
* #brief Configure the TIM3 TIMER.
* #param None
* #retval None
*/
void TimerConfiguration(void)
{
uint16_t PrescalerValue = 0;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* TIM3 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
/* Prescaler configuration */
PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / TIM3_CK_CNT) - 1;
TIM_PrescalerConfig(TIM3, PrescalerValue, TIM_PSCReloadMode_Immediate);
/* Output Compare Timing Mode configuration: Channel1 */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);
/*Channel2 */
TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
/*Channel3 */
TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
/*Channel4 */
TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
/* Configure the TIM3 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* TIM Interrupts enable */
TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC2, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC3, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC4, ENABLE);
/* TIM3 counter enable */
TIM_Cmd(TIM3, ENABLE);
}
int LedCount6 = 0;
int LedCount5 = 0;
int LedCount4 = 0;
int LedCount3 = 0;
/************ Interrupt Handlers *************/
/**
* #brief This function handles TIM3 global interrupt request.
* #param None
* #retval None
*/
void TIM3_IRQHandler(void)
{
uint16_t capture = 0;
LedCount6++;
LedCount5++;
LedCount4++;
LedCount3++;
if ((TIM_GetITStatus(TIM3, TIM_IT_CC2) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC3) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC4) != RESET))
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC3);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4);
int val6 = 100000;
int val5 = 70000;
int val4 = 60000;
int val3 = 50000;
if (LedCount6 >= val6 ) {
/* LED6 toggling */
STM_EVAL_LEDToggle(LED6);
LedCount6 = 0;
/* Update CH1 OCR */
capture = TIM_GetCapture1(TIM3);
TIM_SetCompare1(TIM3, capture + CCR1_Val);}
if (LedCount5 >= val5) {
/* LED5 toggling */
STM_EVAL_LEDToggle(LED5);
LedCount5 = 0;
/* Update CH2 OCR */
capture = TIM_GetCapture2(TIM3);
TIM_SetCompare2(TIM3, capture + CCR2_Val);}
if (LedCount4 >= val4) {
/* LED4 toggling */
STM_EVAL_LEDToggle(LED4);
LedCount4 = 0;
/* Update CH3 OCR */
capture = TIM_GetCapture3(TIM3);
TIM_SetCompare3(TIM3, capture + CCR3_Val);}
if (LedCount3 >= val3 ) {
/* LED3 toggling */
STM_EVAL_LEDToggle(LED3);
LedCount3 = 0;
/* Update CH4 OCR */
capture = TIM_GetCapture4(TIM3);
TIM_SetCompare4(TIM3, capture + CCR4_Val);}
}
}
Now, all the code that blinks the 4 leds is inside the interrupt handler (void TIM3_IRQHandler(void)).
The 4 LEDs blink, but blink all at the same time, how can i change their frequencies to be all different?
Changing the TIM3_CK_CNT value will change the frequency of all 4, but because it's a define i cannot manipulate it through the code to change for each led.
The TIMER (TIM3) has 4 channels which all can cause an interrupt, but the interrupt handler will be the same one for all channels.
Replace your IRQ handler like this (Change the LED toggle as you wish):
void TIM3_IRQHandler(void)
{
uint16_t capture = 0;
if (TIM_GetITStatus(TIM3, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
/* LED6 toggling */
STM_EVAL_LEDToggle(LED6);
/* Update CH1 OCR */
capture = TIM_GetCapture1(TIM3);
TIM_SetCompare1(TIM3, capture + CCR1_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
/* LED5 toggling */
STM_EVAL_LEDToggle(LED5);
/* Update CH2 OCR */
capture = TIM_GetCapture2(TIM3);
TIM_SetCompare2(TIM3, capture + CCR2_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC3) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC3);
/* LED4 toggling */
STM_EVAL_LEDToggle(LED4);
/* Update CH3 OCR */
capture = TIM_GetCapture3(TIM3);
TIM_SetCompare3(TIM3, capture + CCR3_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC4) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4);
/* LED3 toggling */
STM_EVAL_LEDToggle(LED3);
/* Update CH4 OCR */
capture = TIM_GetCapture4(TIM3);
TIM_SetCompare4(TIM3, capture + CCR4_Val);
}
}
With this change, LED will toggle with respect to each channel interrupt. i.e Only one LED blinks at each interrupt. In order to Blink with different frequencies, you need to check the datasheet, how configure different frequency for different LED channel.
The code is too large to place it here.
Here is my solution:
https://www.diymat.co.uk/arm-blinking-led-driver/
Any number of LEDs, any frequencies (off and on time can be different) any number of blinks (+continous) and the callbacks at the end of the sequence.

Stm32L151RCxxx USART Hang issue, Interrupt Based TX/RX simultaneously

I am running USART3, on 921600 BaudRate, using RTS CTS, I am always facing system hang when I try to do RX and TX simultaneously. I have pasted the main and IRQ code. IRQ is designed to Transmit a char 'A' while dropping all received data. Hangs happens when we disable USART_ITConfig(USART3, USART_IT_TXE, DISABLE);
Uart_Configuration()...
USART_ClockInitStructure.USART_Clock = USART_Clock_Disable;
USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;
USART_ClockInitStructure.USART_LastBit = USART_LastBit_Disable;
USART_ClockInit(USART3, &USART_ClockInitStructure);
USART_InitStructure.USART_Mode = (USART_Mode_Tx|USART_Mode_Rx);
USART_InitStructure.USART_BaudRate = u32BaudRate;
USART_OverSampling8Cmd(USART3, DISABLE);
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS_CTS;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_Init(USART3, &USART_InitStructure);
USART_ITConfig(USART3,USART_IT_TXE, DISABLE);
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
USART_Cmd(USART3, ENABLE);
Main.c ...
uint8_t UART_TransmitData(void)
{
if(u8IntTxFlag==1)
{
u8IntTxFlag=0;
USART_ITConfig(USART3, USART_IT_TXE, ENABLE);
return TRUE;
}
return FALSE;
}
void USART3_IRQHandler(void)
{
/* Implemented full duplex serial communication */
/* UART RX */
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
{
USART_ReceiveData(USART3);
}
/* UART TX */
if(USART_GetITStatus(USART3, USART_IT_TXE) != RESET)
{
if(USART_GetFlagStatus(USART3, USART_FLAG_CTS) == RESET)
{
while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
USART_SendData(USART3, 'A');
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
USART_ClearFlag(USART3, USART_FLAG_TC);
USART_ITConfig(USART3, USART_IT_TXE, DISABLE);
u8IntTxFlag=1;
}
else
{
USART_ClearFlag(USART3, USART_FLAG_CTS);
}
}
}
int main(void)
{
RCC_ClocksTypeDef RCC_Clocks;
RCC_Configuration();
RCC_GetClocksFreq(&RCC_Clocks);
SysTick_Config(RCC_Clocks.HCLK_Frequency / 2000);
NVIC_Configuration();
Init_GPIOs();
SerialUARTConfig(921600, 0, 1, 8, 1);
while(1)
{
UART_TransmitData();
f_SleepMs(5);
}
return 0;
}
Maybe the USART_IT_TXE interrupt happens before you disable it? So the "Tx empty" interrupt pending flag is already set and there is no procedure inside your IRQHandler to clear that flag.

Resources