STM32 HAL shared resource confusion

Hi

I've beed reading some examples from stm32f1xx_hal. I don't quite understand what is going on in TIM2 interrupt:
1 Since you have to populate gpio pin from main(), why mutex has a Option instead of a LEDPIN.
2. Is this some kind of context manager like in python ?
3. Why wait() since this interrupt fires when timer overflows ?

If someone can explain it, I will be grateful.

@luqasz, I don't really know stm32 chips, but you haven't gotten any other answers, so I thought I would chime in. I think I can answer questions 1 and 2.

You need an Option, because you can't create an instance of the LED pin at compile time. It needs to be initialized first. It's a "lazy initialization" or a "late resource" in the language of RTIC. The easiest way to do that is with an Option. It starts as None until it is initialized with Some value.

The initialization happens in main, but the interrupt handler actually uses the LED. The G_LED static is a way to share the LED struct between main and the interrupt handler. But sharing between execution contexts can cause race conditions without some sort of lock, which is what Mutex provides.

However, once initialized, main never needs to access G_LED again, so the Mutex would be wasted overhead for most of the program. The example solves this by defining a local static variable and moving the LED from G_LED to there. Now, the interrupt handler can access the LED without locking a Mutex every time.

Unfortunately, I don't understand the call to .wait(), because I don't know your chip at all.

Edit: You also might check out the stm32-rs Matrix channel. You might have better luck getting an answer there.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.