Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I am using Win32::SerialPort to open a com port and send and receive commands. So, I say:

$portObj = new Win32::SerialPort ($PortName) || die "Oh no Can't open +$PortName: $^E\n"; # $quiet is optional

Sometimes, I connect with no problem, but many times, I get the following error when this line is executed:

can't open device: com1 at C:\perl\test.pm line 31
Oh no Can't open com1:

The die message does not give out any printout for $^E. I am not sure why the com port can not be opened sometimes...any advice?

Thank you in advance.

Replies are listed 'Best First'.
Re: using win32::serialport
by moot (Chaplain) on Apr 13, 2005 at 03:13 UTC
    Perhaps it's busy at those times. Is another process utilising the serial port? Does the code always work on other machines?
Re: using win32::serialport
by starbolin (Hermit) on Apr 13, 2005 at 16:06 UTC

    From Win32::SerialPort:

    Version 0.15 adds an optional $quiet parameter to new. Failure to open a port prints a error message to STDOUT by default. Since only one application at a time can "own" the port, one source of failure was "port in use". There was previously no way to check this without getting a "fail message".(italics added by starbolin) Setting $quiet disables this built-in message. It also returns 0 instead of undef if the port is unavailable (still FALSE, used for testing this condition - other faults may still return undef). Use of $quiet only applies to new.

    This would imply something like:

    { $|++;print "\rPort Busy ",$i++;sleep 1; die "Can't wait any longer\n" if ($i>=15); } while (($portObj = new Win32::SerialPort ($PortName, $quiet))==0); die "Other reason for not working: $!\n" if ($portObj==undef);
    I don't think $^E will have any information in either case as the port is not setup yet only the control block is being created and even that has failed, but that's an untested assumption.

    If you haven't already, you should fully explore the resources on Bill's page

    Good luck


    s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}
      many thanks for the responses...helps to understand these com ports better.