serial output error

I download a serial port testing program using pin 0 and pin 1 as rx and tx pins. Under arduino IDE using serial monitor I send 1.23 and see what happens , pin 13 cannot switch off , can anyone help me ?

simple_code.ino (331 Bytes)

Using eqjuality with the float data type is problematic. Floats often cannot be accurately represented in binary. Load the following code and run it and you can see why your LED does not turn off.

int led = 13; // the pin the LED is connected to

void setup()
{
   pinMode(led, OUTPUT); // Declare the LED as an output
   digitalWrite(led, HIGH);
   Serial.begin(9600);   
}

void loop()
{
   if (Serial.available())
   {
      float x = Serial.parseFloat();
      Serial.println(x,10);
      if (x == 1.23)
      {
         digitalWrite(led, LOW);
      }
   }
}

1.2300000000 is not equal to 1.2300001382.

Since the serial input from serial monitor is ASCII text in the form of a string we can use the string comparison function strcmp() to test for equality without worrying about the lack of accuracy of floats. The following example uses the lesson from the serial input basics tutorial to read a string from serial monitor and the strcmp() function to test for the string (number) "1.23". Make sure that the line endings are enabled in serial monitor. The code uses the line feed (\n or 0x0a) as an end marker for the string.

const byte led = 13; // the pin the LED is connected to

const byte numChars = 12;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup()
{
   Serial.begin(9600);
   Serial.println("<Arduino is ready, Enter a number>");
   pinMode(led, OUTPUT); // Declare the LED as an output
   digitalWrite(led, HIGH);
}

void loop()
{
   recvWithEndMarker();
   showNewData();
}

void recvWithEndMarker()
{
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

   while (Serial.available() > 0 && newData == false)
   {
      rc = Serial.read();

      if (rc != endMarker)
      {
         receivedChars[ndx] = rc;
         if (rc == '\r')
         {
            return;
         }
         ndx++;
         if (ndx >= numChars)
         {
            ndx = numChars - 1;
         }
      }
      else
      {
         receivedChars[ndx] = '\0'; // terminate the string
         ndx = 0;
         newData = true;
      }
   }
}

void showNewData()
{
   if (newData == true)
   {
      Serial.print("This just in ... ");
      Serial.print("<");
      Serial.print(receivedChars);
      Serial.println(">");
      if (strcmp(receivedChars, "1.23") == 0) // compare serial input to 1.23
      {
         digitalWrite(led, LOW);
      }
      newData = false;
   }
}