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 18:57

You need send the commands CR (Carriage Return) and LF (Line Feed, or new line).

For this is just to send your command plus the the CR and LF like this:

string command = "myCommand";

port.write(string.format("{0}\r\n", command));

\r\n = CR + LF -> Used as a new line character in Windows

查看更多
神经病院院长
3楼-- · 2019-01-25 18:59

I appended "\r\n" in string and call Write() method and it works for me. For Example,

serial.Write("abcd\r\n");

查看更多
太酷不给撩
4楼-- · 2019-01-25 19:02

To send the enter key, you would have to use

serial.Write(new byte[]{13,10}, 0, 2);

Assuming your syntax for Control + E is correct. The enter key is interpreted and usually saved in a file as CR-LF. However, depending on your device, it may only require CR=13, or LF=10. You should try all 3 combinations with your device to see what it expects.

If you are looking for the actual scan code of the enter key, it's "43" on a PC 102/104 key keyboard. Depending on the actually computer you are using, it may be different. For instance on a Commodore 64 the scan code for the Return key is "1", which has the equivalent use of Enter on a PC keyboard.

查看更多
Viruses.
5楼-- · 2019-01-25 19:04

It depends on what is ENTER for your device. In Windows it is CRLF (13 and then 10), Linux is LF (only 10.) It's just a matter of what your device expects, because it can't see ENTER, just "byte 10, byte 13, byte whatever..."

查看更多
地球回转人心会变
6楼-- · 2019-01-25 19:05

What the previous answers have told you is how to send a NEWLINE character - this is not the same as "the enter key". If what you want to do is to actually indicate to the remote machine that the "enter key" on the keyboard has been pressed, that is entirely different, and may not be possible, depending on your operating system and hardware.

查看更多
迷人小祖宗
7楼-- · 2019-01-25 19:15

Thanks guys.

This works:

serial.Write("\r\n") 

Note: if you want to send a command through serial port, I use the line below works for me.

serial.Write("your_command\r\n");
查看更多
登录 后发表回答