2

I am trying to write a powershell script that sends a command to a serial device and then keeps reading data coming from the device.

[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()

The above script exits as soon as it receives 1st line from the device. I tried changing the sleep time in the while loop, but the behaviour is the same.

Compo
  • 36,585
  • 5
  • 27
  • 39
RishabhHardas
  • 495
  • 1
  • 5
  • 25
  • I just tried this the other day and had some weird issues as well. Are you sure the ``while ($x = $port.ReadExisting())`` is behaving as you're expecting? – Deetz Jan 20 '21 at 12:46
  • No, I believe that it takes a lot of time to read the bytes in the buffer. I am sure that the device I am talking to responds immediately. – RishabhHardas Jan 20 '21 at 14:42
  • 1
    I would suggest ``while ($port.IsOpen)`` from here: https://stackoverflow.com/a/48661245/3718361 – Deetz Jan 20 '21 at 16:06
  • `while ($port.IsOpen)` did not work, but checking it in an if statement and running the script in an infinite loop worked. – RishabhHardas Jan 21 '21 at 03:56
  • 1
    You can subscribe to the DataRecieved event which is exposed by the SerialPort class to do this. – bluuf Jan 21 '21 at 11:56

1 Answers1

1

Answering my own question here... The following code worked for me to read continuously from the serial port

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.Open()

Write-Output $port

for(;;)
{
    if ($port.IsOpen)
    {
        $data = $port.ReadLine()
        Write-Output $data
    }
}
RishabhHardas
  • 495
  • 1
  • 5
  • 25