0

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!

2
  • Rather than calling ReadExisting immediately, setup an event for DataReceived then call it inside there, I suspect you're trying to read before the data is available. Commented May 24, 2022 at 7:22
  • @DavidMartin How do you do that? (I have not been able to find a single working example, using Powershell, for doing this.) Commented May 14, 2023 at 6:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, Thanks for replying! Is there anyway you could give me an example for the data received event please? I'm not finding alot for such a thing with serial communications. Thanks!

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.