简体   繁体   English

Windows 批次。 将串口数据放入变量中

[英]Windows batch. Put Serial port data in a variable

I have a hardware (battery controller) that send battery voltage over a serial port.我有一个通过串行端口发送电池电压的硬件(电池控制器)。 It's just 4-digit value ('1232') every 5 seconds.每 5 秒只有 4 位数值('1232')。 I need to read that value and if it's below a treshold shut PC down.我需要读取该值,如果它低于阈值,请关闭 PC。 It's old WinXP machine where I'm allowed to use CMD only without creating temporary files.这是旧的 WinXP 机器,我只允许在不创建临时文件的情况下使用 CMD。

On my home PC I created a test environment with two virtual ports (with com2com utility) and powershell script that emulates hardware:在我的家用 PC 上,我创建了一个测试环境,其中包含两个虚拟端口(使用 com2com 实用程序)和模拟硬件的 powershell 脚本:

cls
$port = New-Object System.IO.Ports.SerialPort
$port.PortName = "COM4"
$port.open()
while (1) {
$port.WriteLine("1000"+[char]13)
$port.close()
Start-Sleep -Seconds 5
$port.open()
}

Script below has to recieve data and shut down PC if value below treshold.如果值低于阈值,下面的脚本必须接收数据并关闭 PC。 But it doesn't work.但它不起作用。

@ ECHO OFF
MODE COM5 BAUD=9600 PARITY=n DATA=8 > nul
set tr=1100
FOR /F "usebackq" %%i IN (`TYPE COM5`) DO set x=%%i
IF %x% lss %tr% (ECHO System will shutdown
rem shutdown /s
)

When I run script It's just waits endlessly.当我运行脚本时,它只是无休止地等待。

The for /f loop does not output the results of the command line-by-line as received. for /f循环不会 output 逐行接收到的命令行结果。 It waits for the command to complete so, by using type COM5 you will have a running command that does not exit, unless it experiences EOF.它等待命令完成,因此,通过使用type COM5 ,您将拥有一个不会退出的正在运行的命令,除非它遇到 EOF。 To do this you can redirect its output as input to the for loop为此,您可以将其 output 作为输入重定向到for循环

<COM5 (for /L %%i in (0) do set x=%%i)

You have to note though that this will not run as a permanent loop and you'll have to create a permanent loop if you plan on running it continually.您必须注意,这不会作为永久循环运行,如果您打算连续运行它,则必须创建一个永久循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM