Paragraph on Serial.print within a sequence

Hi, I am developing a program for a project of mine and I encountered an issue. How can I make a Serial.println (" "); when I have n numbers printed in the Serial Monitor. Per example: I have to print this sequence: ((i >> n & 1)) == 1) and I want to make a Serial.println when it's printed 25 numbers of that sequence.

You are expected to write in Portuguese in the Portuguese forum..
āžœ post moved to the general English forum


create a variable byte nbPrints=0; for counting the number of prints and each time you print, you do

if (++nbPrints >= 25) {
  Serial.println(); // no need for the empty string "" 
  nbPrints = 0;
}
1 Like

you might consider

  if (! (nbPrints % 25))
    Serial.println ();

yes you could do that too (if you don't forget to increase nbPrints) but a modulo is a costly operation on a small 8 bit processor.

is real time an issue? or readability?

I would say it's personal preference. As said, you can do that too (with the ++)

Also you need to think about that variable size. if you take a byte it will rollover and when it goes to 0 the modulo will be 0

You need to be careful with that, at some point nbPrints could overflow.

< edit >

Oops, didn't see that while I was typing.
With a byte, 250 % 25 will give you 0, then 6 lines later it overflows to 0.

i think for most on this forum seeing a variety of approaches is helpful.

i think your comment about performance is misleading and likely to cause OPs to walk away with the wrong impression.

of course may will have personal preferences, but the only thing that matters are requirements. there is no benefit to exceeding requirements (otherwise there would be a requirement.

isn't there an increment elsewhere? consider

int
dump (
    unsigned char *buf,
    int            size )
{
    for (unsigned n = 0; n < size; n++)  {
        if (! (n % 8))
            printf ("\n");
        printf (" %02x", buf [n]);
    }
    printf ("\n");
}

Fair. Given we run on small microcontrollers, my personal preference is to go to the fastest / least memory hungry solution.

Some might consider this early optimisation, but when complexity is similar then that's how I make my decision and alternatives are valid as well.

Yes that makes sense. Way easer than the way I was trying to go with. Thanks