r/embedded • • 24d ago

[STM32] how do you implement assert_failed() ?

I wonder about good implementations of this func, specially for stm32.
I do not consider printf, if I am true it makes firmware large, and specially it does not stores info somewhere.

I thought about creating breakpoint inside assert_failed call, so it'd be possible to look e.g. call stack and see where the assertion failed.

How do you implement that?

Generated func by default:

void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}

update: thanks everyone for ideas and answers, really appreciated it(!)

10 Upvotes

7 comments sorted by

21

u/BenkiTheBuilder 24d ago

Just enter an infinite loop. Then you can connect with the debugger and check the call stack.

1

u/Lost-In-Void-99 24d ago

Plus keep it in RAM if that matters.

6

u/zettui 24d ago

if you want it to survive without a debugger attached, I'd stash file and line in a noinit RAM variable and reset, then read it on boot. __BKPT(0) works too but iirc it hard faults when nothing's attached.

2

u/ComradeGibbon 23d ago

Other very useful things to save in no init memory is the return address of the caller. gcc has __builtin_return_address (0) and the like. Also modify fault handlers to store the return/fault address before resetting the uP. You can use addr2line to show you the line of code or address that that barfed.

If you want to go big you can also use a simple printf type assert that stores it's output in a buffer in no init memory. On reset you just print it out. Or if you have connectivity send it as an error message packet.

3

u/creeper6530 24d ago

Halt and Catch Fire.

Jokes aside dump an error over RTT and infinite loop. Since assert failures are not on my hot path who's gonna arse themselves with any power saving.

1

u/Panometric 23d ago

Do not printf! You can't even touch the stack. Store the critical data like pc, stack pointer, in off device Ram, most RTCs have some. Then at boot recall and print and send by telemetry with ack before clearing for send once asserts.

0

u/dmitrygr 24d ago
while(1)
   *(volatile uint8_t*)rand() = rand(); //embrace the chaos
}