0

I have a for loop that prints the iterator to a 16x2 LCD screen. It prints "000", waits 500 ms, and then prints "001" over and over (the LED on RB0 blinks) without incrementing. I tried it on another PIC with no results. How can I get it to increment? Code is in C for a PIC16F1789.

void main(void) {
    init();
    LCD_init();
    
    for(uint8_t i = 0; i <= 255; i++) {
        char str[3];
        sprintf(str, "%03u", i);

        LCD_cmd(LCD_CLEAR);
        LCD_string(str);
        
        LATB ^= 0x01;
        
        __delay_ms(500);
    }
}
  • 9
    I don’t know why it isn’t incrementing, but this is an infinite loop. uint8 can only take values between 0, and 255, so it will _always_ be <= 255. – Max Oct 29 '21 at 20:57
  • 9
    `char str[3];` should be `char str[4];` -- you need an extra byte for the null terminator. – Barmar Oct 29 '21 at 20:58
  • Not a day goes by that we don't see an error like this. Is there a good dupe? @Akx – Barmar Oct 29 '21 at 20:59
  • no need to declare str in the loop either – OldProgrammer Oct 30 '21 at 00:15
  • It looks like my LCD driver iterates through the string until it sees a null and was running endlessly. Thanks for the help! – Stonks3141 Oct 30 '21 at 13:32
  • @Barmar I just closed it with a self-answered community wiki we wrote in order to get a canonical dupe for missing null terminator. You can find the link to this one and many others from the [C tag wiki](https://stackoverflow.com/tags/c/info), scroll down to FAQ, then in this case Strings, then this link happened to be the first one in that list. – Lundin Nov 03 '21 at 13:47

0 Answers0