0

I am using a flame sensor. I am reading the state and then printing it. Here is my code:

void loop(){
 flameState = digitalRead(flamePin);//variables already defined and are global
existsFire();//calls the void
delay(1000);
}

void existsFire(){

Serial.println("Flame: " + flameState);

}

Before, this printed out the right thing. Today, it was printing out "lame:". The "F" and the flameState were missing. I changed it to:

void existsFire(){

Serial.print("Flame: ");
Serial.println(flameState);

}

Everything worked fine. Is there a problem with my Arduino Mega. What do I need to do to fix this?

4

You've stumbled across the difference in the C++ language between a String and an "array of characters". What you gave Serial.println() was an array of characters:

Serial.println("Flame: "...);

and then tried to add a number to it.

Serial.println("Flame: " + flameState);

If it had have been a String, then what you typed would have been fine:

String flame = "Flame: ";
Serial.println(flame + flameState);

Adding (literally +) a number to a String adds characters to the String to represent the number. Unfortunately you didn't start with a String, you started with an array of characters:

"Flame: "

Adding a number to THAT changes where the array starts. flameState must have been 1, and "Flame: " + 1 would have been "lame :" - as you found out!

The version that worked did so through a little bit of magic:

Serial.print("Flame: ");
Serial.println(flameState);

The first line called a version of print() that accepted an array of characters and printed each of them out. The second line called a different version of println() that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the ln part of the name).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.