Search code examples
c#stringcharacter-encodingcharserial-port

Send command via serial port in C#


I have to handle a chain of four motors using a serial port. The user manual indicates that during initialization I need to send (for example) the strings

Z
1ECHO
2ECHO
3ECHO
4ECHO

And tells me to do that, in a code I do not recognize, with commands

PRINT(#128, "Z", #13)
PRINT(#129, "ECHO", #13)
PRINT(#130, "ECHO", #13)
PRINT(#131, "ECHO", #13)
PRINT(#132, "ECHO", #13)

To explain this, the manual also adds a sentence I do not understand:

with the strings above you can initialize the motors via the motors software but a host program have to send the same commands with different prefix: 0, 1, 2, 3 and 4 are in fact 0x80, 0x81, 0x82, 0x83 and 0x84, respectively. The decimal equivalents of hexadecimal values ​​are 128, 129, 130, 131 and 132.

A colleague wrote a working code in Visual Basic as follows:

SerialPort.Output(chr(128) & "Z" & chr(13))
SerialPort.Output(chr(129) & "ECHO" & chr(13))
SerialPort.Output(chr(130) & "ECHO" & chr(13))
SerialPort.Output(chr(131) & "ECHO" & chr(13))
SerialPort.Output(chr(132) & "ECHO" & chr(13))

I've translated into .NET with:

SerialPort.Write((char)128 + "Z" + (char)13);
SerialPort.Write((char)129 + "ECHO" + (char)13);
SerialPort.Write((char)130 + "ECHO" + (char)13);
SerialPort.Write((char)131 + "ECHO" + (char)13);
SerialPort.Write((char)132 + "ECHO" + (char)13);

But it does not work.

Now I can not try but I wonder if it can work to rewrite my code like this:

SerialPort.Write("Z" + (char)13);
SerialPort.Write("1ECHO" + (char)13);
SerialPort.Write("2ECHO" + (char)13);
SerialPort.Write("3ECHO" + (char)13);
SerialPort.Write("4ECHO" + (char)13);

If it will work, why does it work? And if it does not work, how do I correctly translate my colleague's code?


Solution

  • You can't use SerialPort.Write(string) with default encoding for sending bytes >128 (0x80), for more info see this. If you need to be sure your data match any binary protocol, you should send data as array of bytes:

    var data = new byte[] { 129, (byte)'E', (byte)'C', (byte)'H', (byte)'O', 13 };
    SerialPort.Write(data, 0, data.Length);
    

    Then you will be sure no unwanted conversion is performed before sending.