EEVblog Electronics Community Forum

Electronics => Beginners => Topic started by: abdullahseba on June 10, 2015, 05:05:09 pm

Title: C# program not working
Post by: abdullahseba on June 10, 2015, 05:05:09 pm
Can any one help?

I have an Arduino Mega sending the word "hello" to the computer via COM3.

The C# program I wrote is supposed to display "The variable is set to true." if it received "hello".

If it did not receive hello it will display what it received.

The problem is when I run it, it displays "hello" which means it should have displayed "The variable is set to true."

Thanks

Here is the code:
Code: [Select]
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace SerialTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = SerialPort.GetPortNames();
            SerialPort p = new SerialPort("COM3");
            p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
            p.Open();
            string line;
            do
            {
                line = Console.ReadLine();
            } while (line != "quit");
            p.Close();
        }

        static void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string data = ((sender as SerialPort).ReadLine());
            string data2 = "hello";

            if (data == data2)
            {
                Console.WriteLine("The variable is set to true.");
            }
            else
            {
                Console.WriteLine((data));
            }

        }
    }
}
Title: Re: C# program not working
Post by: Wilksey on June 10, 2015, 05:15:13 pm
Try changing:
Code: [Select]
if (data == data2)
to
Code: [Select]
if(data.Contains(data2))
There might be some characters you are not seeing.
Title: Re: C# program not working
Post by: abdullahseba on June 10, 2015, 05:22:02 pm
Try changing:
Code: [Select]
if (data == data2)
to
Code: [Select]
if(data.Contains(data2))
There might be some characters you are not seeing.
Thanks it worked!
how can I see hidden  characters?
Title: Re: C# program not working
Post by: Wilksey on June 10, 2015, 08:13:52 pm
print out the ASCII number value and look at the ASCII chart, if you go into debug and put a breakpoint you should be able to see the extra characters or the number value of them in any case, it is probably including the \r\n chars or one of them.
Title: Re: C# program not working
Post by: sacherjj on June 10, 2015, 08:38:48 pm
You can also look at the appropriate Trim command to clean various white spaces from each end.  I could tell you in Python, but it has now been years since I've been in the C# word.