Hi All, How can I do this. x=x. Where I want 'x=' to be printed as characters on my serial monitor and where the other x is a variable. All this on the one line. You would think this would be simple but I can't find a proper answer anywhere. x is taking on multiple values in my program. I am also using a variable y.
I want my program to be more readable than it is now just printing out values for x and y. Not actually distinguishing between the x and y values.
int x = 42;
void setup()
{
Serial.begin(115200);
Serial.print("the value of the variable x = ");
Serial.println(x);
}
void loop()
{
}/code]
And here is another way using the sprintf() function (or the safer snprintf()) This method is more expensive in memory usage, but allows for flexible formatting. See here for formatting options.
int x = 42;
int y = 198;
void setup()
{
Serial.begin(115200);
char buffer[64]; // buffer must be big enough to hold all the message
sprintf(buffer, "the value of the variable x = %d and y = %d", x, y);
Serial.println(buffer);
}
void loop()
{
}
groundFungus:
int x = 42;
void setup()
{
Serial.begin(115200);
Serial.print("the value of the variable x = ");
Serial.println(x);
}
void loop()
{
}/code]
Better still: Serial.print(F("the value of the variable x = ")); Let's not waste precious RAM. ![]()
In another forum topic print instructions and getting new program on example list - Suggestions for the Arduino Project - Arduino Forum you refer to finding the answer to your query as an "accident", which it certainly wasn't
Don't you think that you should give credit to those who provided help in this topic ?
I think the OP wants to generate the printed name from the variable, without typing it directly.
It could be done with a macro.
int a = 123;
int b = 345;
float f = 678.98;
#define printNamedVariable(a) {Serial.print(F("var " #a " = ")); Serial.println(a);}
void setup() {
Serial.begin(250000);
printNamedVariable(a);
printNamedVariable(b);
printNamedVariable(f);
}
void loop() {}
var a = 123
var b = 345
var f = 678.98
I think the OP wants to generate the printed name from the variable, without typing it directly.
Not according to their other thread where they say they "accidentally" found this is an acceptable answer:
Do this;
Serial.print ("x=");
Serial.println(x);
x is a variable. If x happens to have the value 5 the print out in the serial monitor will be x=5 all on one line.
int a=4, b=5;
int verschil = a - b;
int product = a * b;
Serial.println((String)"a=" + a + " b=" + b + " som=" + som + " verschil=" + verschil + " product=" + product);
It will not win the code efficiency prize but for sure as far as readability is concerned it is in the top 10 ![]()
Best regards,
Johi.
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.