Batch script to read/write data using COM port

后端 未结 2 1429
长情又很酷
长情又很酷 2021-01-06 16:34

I need to write a batch script that can read and write to a COM port (in my case, COM1).

I know that I can send data to a COM port using

echo hello &         


        
2条回答
  •  清酒与你
    2021-01-06 16:55

    The standard way to read data from the serial port is not:

    type COM1 > sample.txt
    

    nor:

    copy COM1 sample.txt
    

    It would be if that data would have a standard EndOfFile mark, like a Ctrl-Z character.

    If that data comes in lines that ends in CR+LF or just CR characters, then the standard way to read them would be:

    set /P "var=" < COM1
    

    If that data have not a delimiter, like CR or CR+LF, then you must specify the exact format of such data:

    • Do you want to read records of a fixed number of characters?
    • Do you want to read characters until a certain one appear? Which one?
    • May the input data contain control characters? Which ones?
    • Any other format of the input data?

    EDIT: Reply to the comments

    When set /P command is executed with redirected input, it does not wait for data. In this case, it returns immediately and the variable is not changed.

    We may try to wait for the next character received from the serial port and then execute the set /P command; this way, the set /P should correctly read an input line terminated in CR or CR+LF that does not contain control characters.

    This is the code:

    set "key="
    for /F "delims=" %%K in ('xcopy /W "%~F0" "%~F0" ^< COM1 2^> NUL') do (
       if not defined key set "key=%%K"
    )
    set /P "line=" < COM1
    set "line=%key:~-1%%line%"
    echo Line read from COM1: "%line%"
    

    Try it and report the result. Sorry, I can not try input read from COM1 in my computer.

提交回复
热议问题