/*******************************************************************************
 * @file    hardfault_handler.c
 * @brief   HardFault Handler for debugging system crashes
 ******************************************************************************/

#include <stdint.h>
#include "debug_print.h"

void HardFault_Handler(void)
{
    volatile uint32_t *stack;
    __asm volatile ("mrs %0, msp" : "=r" (stack));

    DBG_PRINTF("\r\n!!! HARDFAULT !!!\r\n");
    DBG_PRINTF("R0  = %08lX\r\n", stack[0]);
    DBG_PRINTF("R1  = %08lX\r\n", stack[1]);
    DBG_PRINTF("R2  = %08lX\r\n", stack[2]);
    DBG_PRINTF("R3  = %08lX\r\n", stack[3]);
    DBG_PRINTF("R12 = %08lX\r\n", stack[4]);
    DBG_PRINTF("LR  = %08lX\r\n", stack[5]);
    DBG_PRINTF("PC  = %08lX\r\n", stack[6]);
    DBG_PRINTF("PSR = %08lX\r\n", stack[7]);

    while (1) {
        /* Blink LED to indicate fault */
        for (volatile uint32_t i = 0; i < 500000; i++);
        NRF_P0->OUTSET = (1 << 12);
        for (volatile uint32_t i = 0; i < 500000; i++);
        NRF_P0->OUTCLR = (1 << 12);
    }
}
