Electronic – Unusual or Strange Behavior: uint8_t in for loop in avr MCU

atmegaatmel-studioavravrdudec

I am learning programming MCU with c

I am using atmel studio 7, averdude, USBasp and Atmega16a

this is my code

#define F_CPU 1000000
#include <avr/io.h>
#include <util/delay.h>


int main(void) {

DDRA = 0xff;
DDRC = 0xff;

while (1) {
    for (uint8_t i = 8; i >= 0; i--) {
        PORTA = (1 << i);
        _delay_ms(100);
    }

    PORTC = 1;
    _delay_ms(1500);
}

return (0);
}

the for loop never finished and when it reaches i=0 the first LED in PORTA stays on for about 14 seconds and turn off after that for about the same time and after that the for loop starts again without reaching

PORTC =1;
_delay_ms(1500);

when I use int instead of uint8_t it works fine

can someone explain why is this happening ?

Best Answer

You arrive to the point where the value of i is o.
i >= 0 is true.
You try to decrement with i--. Perhaps, you are expecting a negative number. But i is unsigned, so you get 255.
It keep decrementing until you get to zero. Then everything repeats again.

If i were signed, then the loop would make 9 iterations.

The following code does not have this ill effect. Notice the strict inequality. This loop will iterate 8 times.

for (uint8_t i = 8;  i > 0;  i--) { // strictly greater
    // [...]
}