-4

I am sending data from Arduino to console. After receiving the data trigger event. But I am facing this error right now "cannot implicitly convert type 'char' to 'string'"

enter image description here

3 Answers3

5

Change your single quotes to double quotes. Single quotes are for characters and double quotes are for strings.

Terry Tyson
  • 629
  • 8
  • 18
  • now I am getting the error - cannot implicitly convert string to bool – Subham Samir May 10 '19 at 05:28
  • @SubhamSamir Here's the logic: when you write `if (data_rx = "1\r")` what you are doing is essentially assigning the value `1\r` to data_rx but you are not doing any equality comparison. That means that you are doing `if(string type)` while the `if` statement expects a `bool`. Always take not of `=` versus `==` when doing comparison; I cannot stress that enough times. – Wilbur Omae May 10 '19 at 05:54
1

Cannot implicitly convert type 'char' to 'string'

You may want to check out casting and type conventions. See docs. You may also want to check out the reasons given for the C# design team not implementing char to string implicit conversion in this other question on SO (particularly check Eric Lippert's answer).

Another flow that is evident in your code is the confusion between the assignment operator = and the equality check ==. It's a common source of bugs. Always check it out when doing conditionals.

I also notice you have an infinite loop i.e. while (true). Just ensure it does not become an infinite loop (if you know what I mean :D).

Wilbur Omae
  • 184
  • 2
  • 11
  • actually, I am working with Arduino and accelerometer and unity. I want unity to take data from the serial port to generate an event but I failed. I just want that if last data fetched is 1,2,3,4 then it should generate a result – Subham Samir May 10 '19 at 05:25
  • @SubhamSamir I know it's easy to look for a quick fix to your problem, but if you do not take time to understand the underlying issues, you'll repeat the same issues in your future projects. One of the issues is this: understand casting and the difference between char and string in c#. Another issue is: know the difference between `=` and `==` in c# (it's actually common among programming languages). – Wilbur Omae May 10 '19 at 05:29
0
        SerialPort myport = new SerialPort();
        myport.BaudRate = 115200;
        myport.PortName = "COM14";
        myport.Open();

        while (true)
        {
            string data_rx = myport.ReadLine();
            Console.WriteLine(data_rx);
            if (data_rx == "1\r")
            {
                Console.WriteLine("up");
            }
            else if(data_rx == "2\r")
            {
                Console.WriteLine("Down");
            }
            else if (data_rx == "3\r")
            {
                Console.WriteLine("Left");
            }
            else if (data_rx == "4\r")
            {
                Console.WriteLine("right");
            }