gccbare-metalm4arm-none-eabi-gccimx7

Why does clock() returns -1 in C


I'm trying to implement an error handler using the clock() function from the "time.h" library. The code runs inside an embeeded system (Colibri IMX7 - M4 Processor). The function is used to monitor a current value within a specific range, if the value of the current isn't correct the function should return an error message.

The function will see if the error is ocurring and in the first run it will save the first appearance of the error in a clock_t as reference, and then in the next runs if the error is still there, it will compare the current time using clock() with the previous reference and see if it will be longer than a specific time.

The problem is that the function clock() is always returning -1. What should I do to avoid that? Also, why can't I declare a clock_t variable as static (e.g. static clock_t start_t = clock()?

Please see below the function:

bool CrossLink_check_error_LED_UV_current_clock(int current_state, int current_at_LED_UV)
{
    bool has_LED_UV_current_deviated = false;
    static int current_number_of_errors_Current_LED_CANNON = 0;
    clock_t startTimeError = clock();

    const int maximum_operational_current_when_on = 2000;
    const int minimum_turned_on_LED_UV_current = 45;     
    
    if( (current_at_LED_UV > maximum_operational_current_when_on)
      ||(current_state!=STATE_EMITTING && (current_at_LED_UV > minimum_turned_on_LED_UV_current))
      ||(current_state==STATE_EMITTING && (current_at_LED_UV < minimum_turned_on_LED_UV_current)) ){
        current_number_of_errors_Current_LED_CANNON++;
        if(current_number_of_errors_Current_LED_CANNON > 1) {
            if (clock() - startTimeError > 50000){ // 50ms
                has_LED_UV_current_deviated = true;
                PRINTF("current_at_LED_UV: %d", current_at_LED_UV);
                if(current_state==STATE_EMITTING){
                    PRINTF(" at state emitting");
                }
                PRINTF("\n\r");
            }
        }else{
            if(startTimeError == -1){
                startTimeError = clock();
            }
        }
    }else{
        startTimeError = 0;
        current_number_of_errors_Current_LED_CANNON = 0;
    }
    return has_LED_UV_current_deviated;
}

Edit: I forgot to mention before, but we are using GCC 9.3.1 arm-none-eabi compiler with CMake to build the executable file. We have an embedeed system (Colibri IMX7 made by Toradex) that consists in 2 A7 Processors that runs our Linux (more visual interface) and the program that is used to control our device runs in a M4 Processor without an OS, just pure bare-metal.


Solution

  • in the end the problem was that since we are running our code on bare metal, the clock() function wasn't working. We ended up using an internal timer on the M4 Processor that we found, so now everything is fine. Thanks for the answers.