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");
VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Jan 23, 2019 at 13:15
1
  • 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 Commented Jan 23, 2019 at 13:27

1 Answer 1

1

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);
}
answered Jan 23, 2019 at 13:38
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.