Home > Software engineering >  Sending command on serial port using c#
Sending command on serial port using c#

Time:07-19

I have a little application that sends a command over a serial port and write the response in a label. If I send a ENTER character

inputData = "\r\n\";
port.Write(Encoding.ASCII.GetBytes(inputData), 0, 1);

the response is the last string that was generated by the device I communicate with. If I send something like

inputData = "S1\r\n";
port.Write(Encoding.ASCII.GetBytes(inputData), 0, 1);

the label stays empty. The second command is the one that I need to send and in Putty terminal works well. Is there a way to send the same thing via port.Write?

CodePudding user response:

The Write method definition is

void Write(byte[] buffer, int offset, int count);

In your second example you are only sending the character 'S' - you are not sending the remainder of the string. The third parameter is the number of characters in the string to send (the second is the start offset).

Maybe modify your code allong the lines of

var buffer = Encoding.ASCII.GetBytes(inputData);
port.Write(buffer, 0, buffer.Length);

The fact the first example worked probably indicates that all you need to send is '\r' & the '\n' is not required.

  • Related