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.

5
  • 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? Commented Jan 20, 2021 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. Commented Jan 20, 2021 at 14:42
  • 1
    I would suggest while ($port.IsOpen) from here: stackoverflow.com/a/48661245/3718361 Commented Jan 20, 2021 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. Commented Jan 21, 2021 at 3:56
  • 1
    You can subscribe to the DataRecieved event which is exposed by the SerialPort class to do this. Commented Jan 21, 2021 at 11:56

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.