Pann Phyu Phway
Pann Phyu Phway

Reputation: 129

How to use HAL delay to generate another frequency

The code show that both reading and printing of accelerometer and temperature sensor are done every one second. But I need to read and print temperature value once every 1.5 seconds which is different from accelerometer

int main(void) { initialise_monitor_handles();

HAL_Init();


BSP_ACCELERO_Init();
BSP_TSENSOR_Init();

while (1)
{
    float accel_data[3];
    int16_t accel_data_i16[3] = { 0 };          // array to store the x, y and z readings.
    BSP_ACCELERO_AccGetXYZ(accel_data_i16);     // read accelerometer
    // the function above returns 16 bit integers which are 100 * acceleration_in_m/s2. Converting to float to print the actual acceleration.
    accel_data[0] = (float)accel_data_i16[0] / 100.0f;
    accel_data[1] = (float)accel_data_i16[1] / 100.0f;
    accel_data[2] = (float)accel_data_i16[2] / 100.0f;

    float temp_data;
    temp_data = BSP_TSENSOR_ReadTemp();         // read temperature sensor

    printf("Accel X : %f; Accel Y : %f; Accel Z : %f; Temperature : %f\n", accel_data[0], accel_data[1], accel_data[2], temp_data);

    HAL_Delay(1000);    // read once a ~second.

}

}

Upvotes: 0

Views: 282

Answers (1)

pmacfarlane
pmacfarlane

Reputation: 4297

There are lots of ways to do this. Here's a simple one:

uint32_t tick = 0u;
while (1)
{
    if ((tick % 2u) == 0u)
    {
        // Do accelerometer stuff
    }

    if ((tick % 3u) == 0u)
    {
        // Do temperature stuff
    }

    ++tick;
    HAL_Delay(500u); // Half a second
}

The modulo 3 is a bick icky, but you get the idea. You could have two tickers and wrap them, instead of using modulo arithmetic.

Upvotes: 2

Related Questions