Wen
Wen

Reputation: 1

Powershell Serial communication

I have written a script in powershell to send hex and recieve from a COMS port, the main issue I have found, is that I am not getting all of the data back from the device, I only know this as my boss is saying there is missing data. I can't tell you the exact device as it is a company project, but it's an I/O board that once a proper command is sent (e.g. 0x1b, 0x02, 0x43, 0x20, 0xff, 0x1b, 0x03) an answer is sent back (e.g. P or A). The answer I'm able to get at the moment is 'P' when I send the command '0x1b, 0x02, 0x50, 0x1b, 0x03' but apparently there is a bunch of other information missing.

Also to add to my issue, the command readexisting works, but readline freezes the program, which the only cure is to disconnect the I/O board to disconnect the I/O board from the Laptop. Is there something I am missing? Are there other commands for this? Does readexisting only give me 1 character or something? TL;DR I wanna read the full answer it apparently has.

Here is my code:

#[byte[]] $request = 0x1b,0x02,0x43,0x0C,0xff,0x1b,0x03
#[byte[]] $request2 = 0x1b,0x02,0x43,0x0C,0x00,0x1b,0x03
[byte[]] $request = 0x1b,0x02,0x50,0x1b,0x03
[byte[]] $request2 = 0x1b,0x02,0x50,0x1b,0x03

$counter = 0
$howmany? = 0
$port = new-Object System.IO.Ports.SerialPort COM3,115200,None,8,one
$port.Open()
timeout 1

function read-com {
  try{
    $line = $port.ReadExisting()
    if($line)
    {
        Write-Host $line
    }
  }
  catch [System.Exception]
  {
  }
}


while ($counter++ -lt 6) {

$port.Write($request, 0, $request.Count)
timeout 3
read-com

$port.Write($request2, 0, $request.Count)
timeout 3
read-com

}

$port.Close()

Let me know if you think of anything Thanks!

Upvotes: 0

Views: 939

Answers (1)

SnobbyWombat
SnobbyWombat

Reputation: 36

Readline returns the contents of the input buffer up to the first occurrence of a NewLine value. If there is no NewLine, it wil seem like it has stopped working.

And you can use DataReceived event on the port object with the Register-ObjectEvent cmdlet to read data asynchronously.

Upvotes: 1

Related Questions