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?

asked Jul 19, 2016 at 23:37

1 Answer 1

5

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).

answered Jul 19, 2016 at 23:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.