Search code examples
cwhile-loopembeddedvolatileboolean-logic

while loop stops when condition is still true


I have the following code:

void EXTI_Main(uint8_t mult)//range 1-4(inclusive)
{
    uint16_t minimum = 200 * mult;
    while(TMR3_GetTick() < minimum);
    printf("mult:%hhu\ttick:%hu\tminimum:%hu\r\n", mult, TMR3_GetTick(), minimum);
    //RF_Main();
    LCD_Read();
    
}

with the following output: (don't know how to make blockquote work with line breaks)

mult:0  tick:0  minimum:0
mult:1  tick:414        minimum:200
mult:2  tick:453        minimum:400
mult:3  tick:600        minimum:600
mult:4  tick:800        minimum:800
mult:0  tick:0  minimum:0
mult:1  tick:414        minimum:200
mult:2  tick:453        minimum:400
mult:3  tick:600        minimum:600
mult:4  tick:768        minimum:800
mult:0  tick:0  minimum:0
mult:1  tick:414        minimum:200
mult:2  tick:453        minimum:400
mult:3  tick:512        minimum:600
mult:4  tick:768        minimum:800
mult:0  tick:0  minimum:0

relevant code in tmr3.c:

static volatile uint16_t msTick;//incremented using ISR
uint16_t TMR3_GetTick(void)
{
    return msTick;
}

Why is this causing problems when mult == 3 | 4? is volatile the problem?? I've been reading on how to work with volatile vars and haven't been able to work out if this is part of the problem.

Please ask if more info is required. Thanks.

EDIT: idk if it's helpful but when they fail, 3 and 4 are always 512(256 * 2) and 768(256*3)

EDIT2: the solution turned out to be:

uint16_t tock; while((tock = TMR3_GetTick()) < minimum);

Solution

  • shoutout to my man Weather Vane in the comments for this one.

    replaced:

     while(TMR3_GetTick() < minimum);
    

    with:

    uint16_t tock; while((tock = TMR3_GetTick()) < minimum);