How to print Integer alongside String Arduino?

半城伤御伤魂 提交于 2019-12-02 02:10:52

问题


I am trying to print an integer alongside a string but it's not really working out and am getting confused.

int cmdSeries = 3;

Serial.println("Series : " + cmdSeries);// That's where the problem occur

In visual basic we used to do it this way:

Dim cmdSeries As Integer
Console.Writeline(""Series : {0}", cmdSeries)

So i've tried it with Serial.println but it returns this error : call of overloaded 'println(const char [14], int&)' is ambiguous

Can anyone help my out, I want to achieve this without using any libraries and in a clean way.


回答1:


There is a huge difference between Arduino String class and regular C-string. The first one overloads addition operator, but there is almost excessive usage of dynamic memory. Mainly if you use something like:

String sth = String("blabla") + intVar + "something else" + floatVar;

Much better is just using:

Serial.print("Series : ");
Serial.println(cmdSeries);

Btw, this string literal resides in Flash and RAM memory, so if you want to force using flash only:

Serial.print(F("Series : "));

But it's for AVR based Arduinos only. This macro can save a lots of RAM, if you are using lots of literals.

EDIT: Sometimes I use this:

template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

Serial << F("Text ") << intVar << F("...") << "\n";

It prints each part separately, no concatenations or so.




回答2:


Try this

int cmdSeries = 3;
Serial.println(String("Series : ") + cmdSeries);


来源:https://stackoverflow.com/questions/43325379/how-to-print-integer-alongside-string-arduino

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!