Reputation: 21
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.
Upvotes: 1
Views: 703
Reputation: 21
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".
Upvotes: 1
Reputation: 72
Two things I submit to you:
1. Things are not always as they appear:
use readBuffer.Trim().Equals("A") instead.
So in final analysis, try this:
if (readBuffer.Trim().ToUpper().Equals("A"))
Upvotes: 0