[Solved]Weird printf behavior when using timer and interrupt



  • The code never reaches to line 36 if the printf statement at line 30-33 is commented in the while loop().
    Can anyone test on other platforms to check whether anything goes wrong?

    #include <bsp.h>
    #include <sysctl.h>
    #include <timer.h>
    #include <plic.h>
    
    unsigned long cur_ms = 0;
    
    void irq_time(void) {
        cur_ms += 1;
    }
    
    
    int main(void) {
        sysctl_pll_set_freq(SYSCTL_PLL0, 800000000);
        uint32_t freq = sysctl_cpu_set_freq(600 * 1e6) / 1e6;
        printf("CPU Freq=%d Mhz\n", freq); //returns a doubled frequency but fine
        unsigned  long start_ms = 0;
        unsigned  long cnt = 0;
    
        plic_init();
        timer_init(TIMER_DEVICE_0);
        timer_set_interval(TIMER_DEVICE_0, TIMER_CHANNEL_0, 1e6); //1ms
        timer_set_irq(TIMER_DEVICE_0, TIMER_CHANNEL_0, irq_time, 1);
        timer_set_enable(TIMER_DEVICE_0, TIMER_CHANNEL_0, 1);
        sysctl_enable_irq();
        printf("Start Benchmark\n");
        start_ms = cur_ms;
        uint32_t pp = 0;
        while (cur_ms - start_ms <= 1000) {
    //        if (cur_ms / 200 >= pp) { //become normal if uncomment this if statement
    //            printf("cur_ms=%lu\n", cur_ms);
    //            pp += 2;
    //        }
            cnt += 1;
        }
        printf("Cnt in 1000ms=%lu\n\n", cnt); // Never reach
        while (1) {
            continue;
        }
    }
    

    Build on Mac OS 10.15.2 using kendryte-standalone-sdk-0.5.6



  • It turns out that we should add volatile before cur_ms to prevent it from being optimized out.