1

I'm trying to make the program respond to certain words sent by a microcontroller, but when I compare the received word with a pre-defined word, it always returns false.

private void ReadData()
{
    if (serialPort1.IsOpen == true)
    {
        if (serialPort1.BytesToRead > 0)
        {
            string readBuffer = serialPort1.ReadLine(); 

            textBox2.Text = readBuffer;
            if (readBuffer.Equals("A")) //MY MAIN PROBLEM
            {
                textBox2.Text += "YEP";
            }
            else
            {
                textBox2.Text += "NOPE";
            }
        }
    }
}

Basically when the microcontroller sends letter "A", it reads it and stores it into the readBuffer string, and even prints it out in a textbox(textBox2). My result is always ANOPE in the textbox (A is what the microcontroller sent and NOPE is always there because the if failed). I started C# recently and lost several days trying to figure this one out, but I really can't seem to find a solution to an apparently simple issue.

7
  • 3
    Perhaps the new line is included in the readBuffer string? Commented Jan 9, 2016 at 23:16
  • 4
    Have you debugged this? Maybe there is a \n or some other byte after the A in the string. You did a ReadLine so there may be some new line character that your text box does not display. Commented Jan 9, 2016 at 23:18
  • 1
    Could be an "A" in a different encoding (Cyrillic?) Commented Jan 9, 2016 at 23:20
  • 1
    Also try readBuffer.StartsWith("A") Commented Jan 9, 2016 at 23:21
  • Thank you for the incredibly fast replies! And yes, it did add a carriage return (\r) after the A, which I couldn't see, but the debbuger caught it! Commented Jan 9, 2016 at 23:31

2 Answers 2

1

Thanks to Willem Van Onsem and René Vogt I figured out the problem. After it reads the data and stores it into the readBuffer, it also includes \r (carriage return), making the string actually "A\r", which is why it was always false compared to "A".

Sign up to request clarification or add additional context in comments.

1 Comment

set serialPort1.NewLine = "\r\n" and then ReadLine() will nolonger return the \r
0

Two things I submit to you:
1. Things are not always as they appear: use readBuffer.Trim().Equals("A") instead.

  1. readBuffer.Equals("A") performs an ordinal (case-sensitive and culture-insensitive) comparison.
    A = A but A ≠ a if you use .Equals to compare them.

So in final analysis, try this:
if (readBuffer.Trim().ToUpper().Equals("A"))

Comments

Your Answer

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.