Scrolling text, Strings vs Char Array

Hi, I’m ashamed to admit how long I’ve spent on this and still can’t get it to work, I found a very elegant piece of code that will display a line of scrolling text, only issue is that it uses Strings rather than char arrays so I though I’d have a go at modifying it here’s the code.

void loop() {
stTest();
arrTest();
}



void arrTest()
{
  const int width = 18;// width of the marquee display (in characters)
  char text[100]= ". . Text scrolling on Adafruit TFT shield . .";  
  char output[100]="";

  for (unsigned int offset = 0; offset < strlen(text); offset++)
  {unsigned int i ;
  char c[2]="";
  for ( i = 0; i < width; i++)  c[0]=(text[(offset + i) % (strlen(text))]);
  Serial.println(strcat(output,c));
  delay(200);
  }
   
}

void stTest()
{ 
  const int width = 18; // width of the marquee display (in characters)
  String text = " . . Text scrolling on Adafruit TFT shield . ."; // sample text

  for (unsigned int offset = 0; offset < text.length(); offset++)
  {
  String t = "";
  unsigned int i;
  for (i = 0; i < width; i++) t += text.charAt((offset + i) % text.length());
  Serial.println(t);
  delay(200);
  }

}

If you run this code the stTest produces the desired output as it should, the arrTest does not, what on earth have I got wrong?

Many thanks

Here’s the output

StTest
. . Text scrollin
. . Text scrolling
. Text scrolling
. Text scrolling o
Text scrolling on
Text scrolling on
ext scrolling on A
xt scrolling on Ad
t scrolling on Ada
scrolling on Adaf
scrolling on Adafr
crolling on Adafru
etc

ArrTest
g
g o
g on
g on
g on A
g on Ad
g on Ada
g on Adaf
g on Adafr
g on Adafru
g on Adafrui
g on Adafruit
g on Adafruit
g on Adafruit T
g on Adafruit TF
g on Adafruit TFT
g on Adafruit TFT
g on Adafruit TFT s
g on Adafruit TFT sh
g on Adafruit TFT shi
g on Adafruit TFT shie

          Me
         Mer
        Merr
       Merry
      Merry
     Merry C
    Merry Ch
   Merry Chr
  Merry Chri
  erry Chris
  rry Christ
  ry Christm
  y Christma
   Christmas
  Christmas
  hristmas &
  ristmas &
  istmas & H
  stmas & Ha
  tmas & Hap
  mas & Happ
  as & Happy
  s & Happy
   & Happy N
  & Happy Ne
   Happy New
  Happy New
  appy New Y
  ppy New Ye
  py New Yea
  y New Year
   New Year
  New Year
  ew Year
  w Year
   Year
  Year
  ear
  ar
  r
          Me
         Mer
        Merr
       Merry
      Merry
     Merry C
    Merry Ch
   Merry Chr
  Merry Chri
  erry Chris
#include <stdio.h>
#include <string.h>


void
marquee (
    const char *s)
{
    static unsigned offset = 0;
    char            buf [90];

    sprintf (buf, "%.10s", &s [offset]);
    printf ("  %s\n", buf);

    if (strlen (s) <= ++offset)
        offset = 0;
}

int main ()
{
    for (int i = 0; i < 50; i++)
        marquee ("        Merry Christmas & Happy New Year");
    return 0;
}

Thanks, always more than one way to skin a cat, but I was hoping that someone could help with the code that I had got so far, at least I vaguely understand that!

void arrTest()
{
  const int width = 18;// width of the marquee display (in characters)
  char text[100] = ". . Text scrolling on Adafruit TFT shield . .";
  char output[100] = "";

  for (unsigned int offset = 0; offset < strlen(text); offset++)
  { unsigned int i ;
    char c[2] = "";
    for ( i = 0; i < width; i++)  c[0] = (text[(offset + i) % (strlen(text))]);
    Serial.println(strcat(output, c));
    delay(200);
  }

}

Your internal loop sets c[0] to a sequence of 'width' characters, but only concatenates the final character to output.
As you add characters to output, you are always printing from the first character of output, regardless of how many characters there are in output.

g 
g o
g on
g on 
g on A
g on Ad
g on Ada
g on Adaf
g on Adafr
g on Adafru
g on Adafrui
g on Adafruit
g on Adafruit 
g on Adafruit T
g on Adafruit TF
g on Adafruit TFT
g on Adafruit TFT 
g on Adafruit TFT s
g on Adafruit TFT sh
g on Adafruit TFT shi
g on Adafruit TFT shie
g on Adafruit TFT shiel
g on Adafruit TFT shield
g on Adafruit TFT shield 
g on Adafruit TFT shield .
g on Adafruit TFT shield . 
g on Adafruit TFT shield . .
g on Adafruit TFT shield . ..
g on Adafruit TFT shield . .. 
g on Adafruit TFT shield . .. .
g on Adafruit TFT shield . .. . 
g on Adafruit TFT shield . .. . T
g on Adafruit TFT shield . .. . Te
g on Adafruit TFT shield . .. . Tex
g on Adafruit TFT shield . .. . Text
g on Adafruit TFT shield . .. . Text 
g on Adafruit TFT shield . .. . Text s
g on Adafruit TFT shield . .. . Text sc
g on Adafruit TFT shield . .. . Text scr
g on Adafruit TFT shield . .. . Text scro
g on Adafruit TFT shield . .. . Text scrol
g on Adafruit TFT shield . .. . Text scroll
g on Adafruit TFT shield . .. . Text scrolli
g on Adafruit TFT shield . .. . Text scrollin

You seem to want to copy 'width' number of characters to output, then print output. This can be done by altering your internal loop to copy from text to output, or you could just print each individual character and eliminate the output array entirely.

void arrTest()
{
  const int width = 18;// width of the marquee display (in characters)
  char text[] = " . . Text scrolling on Adafruit TFT shield . .";

  char output[width + 1];
  output[width] = '\0'; //terminating null
  
  for (size_t offset = 0; offset < strlen(text); offset++)
  {
    for (size_t i = 0; i < width; i++)
    {
      output[i] = text[(offset + i) % strlen(text)];
      //Serial.print(text[(offset + i) % strlen(text)]);
    }
    Serial.println(output);
    delay(200);
  }
}

Thanks, yes that is the aim, I’m just working my through your code, the output is being passed to an oled so the array would probably be a better option that sending individual characters. I have a few questions if you don’t mind, any particular reason why you have used size_t, it’s not something I’ve seen before, I had used unsigned purely because the compiler moaned at me because of srtlen returns unsigned int. I thought the line

 c[0] = (text[(offset + i) % (strlen(text))]);

would set c as the a single character selected from text by the offset and strlen calcs that would then be added to the last character in the output array, as the array starts empty it would populate it until it reached 18 characters and the whole process would move on to the next iteration advancing the offset by 1. Despite you explanation I still don’t see why

c[0] = (text[(offset + i) % (strlen(text))]);

strcat(output, c));

doesn’t work? Is it not doing the same function as

t += text.charAt((offset + i) % text.length());?

your string code is concatenating N characters, one at a time, from the String to a character buffer.
The code i posted simply formats a specified # of characters from a specified offset

Right, think I’ve got it, I think for some reason I couldn’t get something like

output[i] = text[(offset + i) % strlen(text)];

to compile so I added

char c[2] = "";

as a “work around” but it obviously it caused the problem I was having.

Thanks again.

Yes, I can see that now and I will look into it in detail, Thanks.

Sometimes forcing bad code to work is harder than re-writing. Nothing is lost by re-writing.

My two pfennig...

const int width = 19;// width of the marquee display (in characters)
char text[] = {"Never gonna give you up, never gonna let you down."}; // add "width" spaces to complete text scroll
int textSize = sizeof(text) / sizeof(text[0]);
int offset, step = 1; // move text faster using step

void setup() {
  Serial.begin(115200);
}

void loop() {
  arrTest();
}

void arrTest() {
  for (int index = offset; index < width + offset; index++) {
    Serial.print(text[index]);
    delay(200);
  }
  Serial.println(); // exceeded width, start new line
  offset += step; // step into text array
  if (offset > width) // constrain offset to size of width
    offset = 0; // reset starting offset into text array
}

Thanks for your input, I hope by “bad code” you mean it just doesn’t do what you thought it should do rather than just poorly thought out and executed? I thought the original code was quite elegant it was just that it used Strings and I wanted to avoid that and the complications that would occur adapting it into code that had already been written, however as I have already noted there is always more than one way to skin a cat and there are now 3 ways! Which is best? I suppose that depends on what we mean by best? I suspect that gcjr’s code gets the job done most efficiently, but david_2018’s code fixed the code that I had already adapted which is what I asked. Your code is another way of doing the same thing however I’m not keen on using global variables if I can get the job done without them, I’ll have a run through on your code tomorrow.

One requirement for elegance is proper indentation :slight_smile:

void setup() {
  Serial.begin(115200);
}

constexpr int width = 18;  // width of the marquee display (in characters)
#define sample_text ". . Text scrolling on Adafruit TFT shield . ."

void arrTest() {
  char text[] = sample_text;

  for (unsigned offset = 0; offset < strlen(text); offset++) {
    char t[100] = "";
    char c[] = "X";
    for (unsigned i = 0; i < width; i++) {
      c[0] = text[(offset + i) % strlen(text)];
      strlcat(t, c, sizeof(t));
    }
    Serial.print("arr\t");
    Serial.println(t);
    delay(200);
  }
}

void stTest() {
  String text = sample_text;

  for (unsigned offset = 0; offset < text.length(); offset++) {
    String t = "";
    for (unsigned i = 0; i < width; i++) {
      t += text.charAt((offset + i) % text.length());
    } 
    Serial.print("str\t");
    Serial.println(t);
    delay(200);
  }
}

void loop() {
  stTest();
  arrTest();
}

The two are nearly equivalent. First some minor points. unsigned by itself implies unsigned int. size_t is an unsigned type "sized for the biggest thing that will fit in memory", and could be the same as unsigned. The sample text is a macro, because C++ is picky about how arrays are initialized. Some superfluous parentheses have been removed.

In the code for char, you pick an arbitrary max size of 100. This is of course one of the main limitations for using plain arrays. String will grow as needed, which is also how it gets in trouble. The helper variable c is also an array; sized automatically with a single placeholder 'X', and will be NUL-terminated, so it is 2 bytes.

The equivalent of concatenating charAt is to then grab a single char from the array, overwrite the placeholder, and then use strlcat; which is safer than just using plain strcat because it won't write past the end of the array.

I’m afraid that I spent too much time with Delphi(Pascal) and VB so I find curly brackets seemingly randomly distributed throughout the code difficult to follow, especially in nested loops, I forget that other people don’t have this limitation :sweat_smile: I want to use C++ in all my projects, not just Arduino so I better get used to it! My definition of elegance in code is code that is self contained, concise, easy to read and efficient but I stress that is just my view. The use of size_t threw me because I’d not seen it before, are there any downsides to using it? If not, why use unsigned int at all? Also why use strcat instead of strlcat? again, are there downsides to using it? I noticed that you have used a global constant in width, any particular reason for that? As it is only used in the arrTest procedure. Why use define when

char text[] = " . . Text scrolling on Adafruit TFT shield . .";

works just as well? I’m not criticising your code just want to understand why you choose to do it this way, I find this fascinating, 4 different ways of accomplishing the same result, 3 variations on a theme and one completely different, I wonder if there are any other ways?

Nothing random about braces. They carry meaning.

Yes.

Seven liines is not efficient? Aren't you asking for help because you can not make it work?

Why use either?

Yes, I am aware of that but when you have spent a lot of time with code that looks more like this

Procedure dosomething()
var
int some_varible
begin

  for i=0 to 10 step 1
  begin
  end

end

then c++ looks a little messy, as for the rest of your post, how about some answers instead of questions? I can see that you have not used strcat or strlcat and I shall work though it and see how it works, in the meantime do you think that your code is better than the other examples? and if so why? Again I’m not criticising just interested. If you’re not counting declarations then the shortest code seems to be 5 lines

What other kinds of projects? There may be better languages than C++; some of them also have lots of curly braces.

It's meant to convey the size of a thing in memory. More than other languages, C/C++ is very concerned about that exact detail. There are other kinds of things that are also unsigned, so you use unsigned or one of a specific size (there it is again), like uint8_t or uint32_t

There is probably no reason to use the less-safe strcat. It is older, and strlcat is not always available. There's strncat, which is also intended to be safer, with slightly different behavior when you "go too far".

Look again. It is used in both.

To remove duplication. By using a constant or a macro, the compiler does the work of using the exact same thing -- like an arbitrary text message -- in more than one place, preventing you from "accidentally" changing one but not others.

Thanks for taking the time to reply.

What other kinds of projects? There may be better languages than C++; some of them also have lots of curly braces.

I occasionally write windows apps, written a few large call centre and scheduling apps in the past and you never know what the next project is going to be, however C and it’s variants seem to be pretty universal and I don’t want to spending time learning another language, I’m getting to that stage in life where you definitely get a feeling of limited time left!

Look again. It is used in both.

Ah yes, I was only looking at arrTest and not stTest, stTest was never going to be used it was there for comparison.

Thanks again for taking the time, it’s much appreciated.

No. If it works, it is good (enough). I had forgotten about Pascal (sorry for that, Blaise), and now understand your reference to braces and line "end"ings.