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 &
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:
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.