0

I use a 16x2 character lcd to display some text. What I want is first line will stay, but the second line should scroll text.

I wrote a program which works fine but the problem is after some time arduino does not respond. I suspect there might be a bug or memory leak in the code.

The relevant code is like this.

void scrollTextFromRight(int line, char text[])
{
    const char space[16] = "                ";
    char screen[16];
    char * longText;

    longText = malloc(sizeof(char) * (sizeof(text) + 17));

    memset(longText, '\0', sizeof(char) * (sizeof(text) + 17));
    memset(screen, '\0', sizeof(screen));

    for (int i = 0; i < 16; ++i)
    {
        longText[i] = space[i];
    }

    for (int j = 0; j < sizeof(text) + 17; ++j)
    {
        longText[16+j] = text[j];
    }


    for (int i = 0; i < sizeof(text) + 17; ++i)
    {

        lcd.setCursor(0, line);
        strncpy(screen, longText + i, 17 );
        lcd.print(screen);
        delay(350);
    }
}

I call this function from main program like this:

scrollTextFromRight(1, "Scrolling text");
  • 1
    you don't free the memory taken by malloc(). don't malloc() on Uno. even if you would free the memory the small heap gets fragmented fast. you can do the same with a buffer on stack – Juraj Jan 23 '19 at 13:27
3

You malloc but don't free. Of course it's going to leak. Also sizeof(text) doesn't work like that. Instead you can do strlen to get the number of characters in a null-terminated char array.

You can do this without the longText buffer by doing partial copies into screen.

const char space[16] = "                ";
char screen[16];

for (int i = 0; i < sizeof(text) + 17; ++i)
{
    lcd.setCursor(0, line);
    strncpy(screen, space, i); // copy i spaces
    strncpy(screen+i, text, min(17-i, strlen(text))); // copy the rest of the string up to the end whichever is shorter.
    screen[17] = '\0'; // force null termination
    lcd.print(screen);
    delay(350);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.