【发布时间】:2021-01-21 12:02:38
【问题描述】:
我正在尝试编写一个 powershell 脚本,将命令发送到串行设备,然后继续读取来自设备的数据。
[System.IO.Ports.SerialPort]::GetPortNames()
Write-Host "Select Serial Port"
$portName = Read-Host -Prompt 'Input Serial Device Name'
Write-Host "Using $portName..."
$port= new-Object System.IO.Ports.SerialPort $portName, 115200, None, 8, one
$port.ReadTimeout = 1000
$port.Open()
$port.WriteLine("start\n\r")
Start-Sleep -Milliseconds 1000
while ($x = $port.ReadExisting())
{
Write-Host $x
Start-Sleep -Milliseconds 300
}
$port.Close()
上述脚本从设备接收到第一行后立即退出。我尝试在 while 循环中更改睡眠时间,但行为是相同的。
【问题讨论】:
-
前几天我刚刚尝试过,但也遇到了一些奇怪的问题。您确定
while ($x = $port.ReadExisting())的行为符合您的预期吗? -
不,我相信读取缓冲区中的字节需要很长时间。我确信我正在与之交谈的设备会立即响应。
-
我建议从这里
while ($port.IsOpen):stackoverflow.com/a/48661245/3718361 -
while ($port.IsOpen)不起作用,但在 if 语句中检查它并在无限循环中运行脚本是有效的。 -
您可以订阅 SerialPort 类公开的 DataRecieved 事件来执行此操作。
标签: windows powershell serial-port