ARM Cortex-M0单片机进Hardfault后串口如何打印输出错误信息

如果在程序运行时进hardfault想要打印出现问题前的错误信息,可按如下操作实现:

我们先找到系统启动文件中的HardFault_Handler汇编入口,将其整个替换为如下写法:

HardFault_Handler\
                PROC                
                MOVS r0, #4
                MOV r1, LR
                TST r0, r1
                BEQ stacking_used_MSP
                MRS R0, PSP
                B get_LR_and_branch
stacking_used_MSP
                MRS R0, MSP
get_LR_and_branch
                MOV R1, LR
                IMPORT  hard_fault_handler_c
                BL hard_fault_handler_c
                ENDP

在系统出错时,单片机内部会将出错前的信息记录下来并传送给Hardfault中断,将信息打印出来;

紧接着,我们到main.c中编写Hardfault中断处理函数:

void hard_fault_handler_c(unsigned int * hardfault_args,unsigned lr_value) 
{
    PRINT("HardFault_Handler\r\n");
    unsigned int stacked_r0;
    unsigned int stacked_r1;
    unsigned int stacked_r2;
    unsigned int stacked_r3;
    unsigned int stacked_r12;
    unsigned int stacked_lr;
    unsigned int stacked_pc;
    unsigned int stacked_psr;
    stacked_r0 = ((unsigned long)hardfault_args[0]);
    stacked_r1 = ((unsigned long)hardfault_args[1]);
    stacked_r2 = ((unsigned long)hardfault_args[2]);
    stacked_r3 = ((unsigned long)hardfault_args[3]);
    stacked_r12 = ((unsigned long)hardfault_args[4]);
    stacked_lr = ((unsigned long)hardfault_args[5]);
    stacked_pc = ((unsigned long)hardfault_args[6]);
    stacked_psr = ((unsigned long)hardfault_args[7]);
    PRINT("Enter HardFault_Handler\r\n");
    PRINT("R0 = %x\n",stacked_r0);
    PRINT("R1 = %x\n",stacked_r1);
    PRINT("R2 = %x\n",stacked_r2);
    PRINT("R3 = %x\n",stacked_r3);
    PRINT("R12 = %x\n",stacked_r12);
    PRINT("Stacked LR = %x\n",stacked_lr);
    PRINT("Stacked PC = %x\n",stacked_pc);
    PRINT("Stacked PSR = %x\n",stacked_psr);
    PRINT("Current LR = %x\n",lr_value);
    while(1);
}

 

 接着如何调试,可以参考这篇博客:https://blog.csdn.net/qq446252221/article/details/111359807

posted @ 2023-01-07 10:48  oTvTo  阅读(1183)  评论(0编辑  收藏  举报