Sending “ENTER” key through serial port

2019-01-25 18:48发布

Hi I want to send some command to my device which is connected via serial port. How to send it?

For example i found this on google search but for me it's useless.

Control + E is a keyboard shortcut for 5, so:

serial.Write(new byte[]{ 5 }, 0, 1);

8条回答
我命由我不由天
2楼-- · 2019-01-25 19:16

To send the enter key, you would have to use SerialPort.NewLine Property - A value that represents the end of a line

_serialPort = new SerialPort();
// ... this COM port parameters
_serialPort.NewLine = "\r"; // "\r" - CR (0x0D); "\r\n" - CRLF (0x0D 0x0A)
try
{
    _serialPort.Open();
}
catch (Exception ex)
{
  Console.Write(ex.Message);
  return;
}
_serialPort.WriteLine("Send string"); // Writes `Send string` string and the `NewLine` value to serial port
 // or
_serialPort.WriteLine((char)2 + "VWD:040" + (char)3); // Writes `<HEX 0x02>VWD:040<HEX 0x03>` string and the `NewLine` value to serial port

For a full example of working with serial port, see here.

查看更多
疯言疯语
3楼-- · 2019-01-25 19:16

The microsoft version of enter or new line is \r\n which is 0x0d 0x0a in hex.

  • \r is the carriage return

    In a shell or a printer this would put the cursor back to the beginning of the line.

  • \n is the line feed

    Puts the cursor one line below, in some shells this also puts the cursor to the beginning of the next line. a printer would simply scroll the paper a bit.

So much for the history lesson. Current windows systems still use these characters to indicate a line ending. Dos generated this code when pressing enter.

The key code is a bit different. Beginning with the esc key being the 1. Enter is 28.

Source: linux hlkeycodes from www.comptechdoc.org

查看更多
登录 后发表回答