cancel
Showing results for 
Search instead for 
Did you mean: 

How to come out of HardFault in STM32 program

Kavana shree
Associate II

I am getting signal trap at HardFault_Handler ​while I am running a program. How to debug and solve?

2 REPLIES 2

Well you can't return unless you solve the underlying error, or advance the program counter. Usually flagging some pretty fatal/gross issue.

Standard practice is to identify the registers and fault instruction and review the source to understand the mechanics of the failure. For illegal addresses one might want to sanity check pointers before using them, ie pay attention to NULL pointers passed or returned by malloc(), etc.

Instrument the Hard Fault Handler so it outputs useful diagnostics rather than die silently in a while(1) loop. Posted routines to do this dozens of times.

//*****************************************************************************
 
/* Add ASM code to startup.s and remove C Handler from stm32fxyz_it.c
 
HardFault_Handler\ 
                PROC
                EXPORT  HardFault_Handler
 
                TST     lr, #4          ; Determine correct stack
                ITE     EQ
                MRSEQ   R0, MSP         ; Read MSP (Main)
                MRSNE   R0, PSP         ; Read PSP (Process)
 
                MOV     R1, R4          ; Registers R4-R6
                MOV     R2, R5
                MOV     R3, R6          ;  sourcer32@gmail.com
 
                EXTERN  hard_fault_handler_c
                B       hard_fault_handler_c
                ENDP
*/
 
void hard_fault_handler_c(unsigned int * hardfault_args, unsigned int r4, unsigned int r5, unsigned int r6)
{
  printf ("[Hard Fault]\n"); // After Joseph Yiu
 
  printf ("r0 = %08X, r1 = %08X, r2 = %08X, r3 = %08X\n",
    hardfault_args[0], hardfault_args[1], hardfault_args[2], hardfault_args[3]);
  printf ("r4 = %08X, r5 = %08X, r6 = %08X, sp = %08X\n",
    r4, r5, r6, (unsigned int)&hardfault_args[8]);
  printf ("r12= %08X, lr = %08X, pc = %08X, psr= %08X\n",
    hardfault_args[4], hardfault_args[5], hardfault_args[6], hardfault_args[7]);
 
  printf ("bfar=%08X, cfsr=%08X, hfsr=%08X, dfsr=%08X, afsr=%08X\n",
    *((volatile unsigned int *)(0xE000ED38)),
    *((volatile unsigned int *)(0xE000ED28)),
    *((volatile unsigned int *)(0xE000ED2C)),
    *((volatile unsigned int *)(0xE000ED30)),
    *((volatile unsigned int *)(0xE000ED3C)) );
 
  while(1);
}
 
//****************************************************************************

Forum transition bastardized code formatting on other examples

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

I will try out this. Actually I got to know why I was getting hardware fault. The flash had some junk content. It showed me question mark. I was trying to compare the flash content with other. After I erased it, hardware fault didn't occur.