I want to have a line like this
Serial.println(count*"B");
So if count=6
, it would print BBBBBB
, etc.
Is there anything like this for arduino?
A more simple "noob" way could also be:
int count = 6
for(int i=0; i<count; i++)
{
Serial.print("b");
}
Serial.println();
string * int
syntax
Commented
Oct 12, 2016 at 1:08
You can write a helper function to do it, like this:
void printRepeat (Stream & device, const char * str, unsigned int count)
{
while (count-- > 0)
device.print (str);
} // end of printRepeat
void setup()
{
Serial.begin (115200);
printRepeat (Serial, "-", 20);
Serial.println ();
} // end of setup
void loop()
{
printRepeat (Serial, "Hello, World! ", 5);
Serial.println ();
delay (500);
} // end of loop
The function printRepeat
is passed a Stream
argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.
Just for fun, here is a version of Nick Gammon's answer reformulated with some C++ magic:
// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
RepeatedString(const char * str, unsigned int count)
: _str(str), _count(count) {}
size_t printTo(Print& p) const
{
size_t sz = 0;
for (unsigned int i = 0; i < _count; i++)
sz += p.print(_str);
return sz;
}
private:
const char * _str;
unsigned int _count;
};
void setup()
{
Serial.begin(115200);
Serial.println(RepeatedString("-", 20));
}
void loop()
{
Serial.println(RepeatedString("Hello, World! ", 5));
delay(500);
}
You can .print()
and .println()
the RepeatedString
s on anything
that can print.
count
has a reasonable limit.