Before I enter a value into the serial port it prints 29.92. When I send a value through the serial port it prints my value however resets it to 0.00 until it reads in another value. How do I make it retain the latest value instead of going to 0.00? Below is my code as well as my output example.
I have read the serial input basics tutorial as well. Thanks!
float Alt_Setting;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello!");
Alt_Setting=29.92;
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0)
{
// read the incoming byte:
Alt_Setting = Serial.parseFloat();
// say what you got:
Serial.print("New Altimeter Setting: ");
Serial.println(Alt_Setting);
}
Serial.print("Altimeter Setting: ");
Serial.println(Alt_Setting);
delay(2500);
}
I also tried putting a delay after it read the serial input just in case it was picking up a 0 but that did not work. If I press "Enter" with nothing typed in the line it also yields a value of 0.00.
This happens very likely because in the Serial Monitor window you have not selected "No line ending" in the lower right corner.
When you hit enter you will send the number and some invisible characters (e.g. new line). When the parseFloat function hits the first invisible character it will convert the value it has, to a float number and you print it out. In the next loop you will just read the next invisible character. Because you did not send any number the parseFloat function will return 0.
Note, the same will happend when you send any letter or symbol other than 0..9 and "."
Using the Serial.parseFloat and Serial.parseInt function seems easy at first, but in the long run will kick you when you do not expect it. The functions have long timeouts, causing delays. I would try to avoid them or experiment with them a lot until you understand them.
Have a look at the examples in Serial Input Basics - simple reliable, non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.