Win32API::CommPort - Raw Win32 system API calls for serial communications.


  use Win32;    ## not required under all circumstances
  require 5.006;
  use Win32API::CommPort qw( :PARAM :STAT 0.20 );

  ## when available ##  use Win32API::File 0.07 qw( :ALL );


  $PortObj = new Win32API::CommPort ($PortName, $quiet)
       || die "Can't open $PortName: $^E\n";    # $quiet is optional

  @required = qw( BAUD DATA STOP );
  $faults = $PortObj->initialize(@required);
  if ($faults) { die "Required parameters not set before initialize\n"; }

Configuration Utility Methods

  set_no_messages(1);                   # test suite use

      # exported by :PARAM
  nocarp || carp "Something fishy";
  $a = SHORTsize;                       # 0xffff
  $a = LONGsize;                        # 0xffffffff
  $answer = yes_true("choice");         # 1 or 0
  OS_Error unless ($API_Call_OK);       # prints error

  $PortObj->init_done  || die "Not done";

  $PortObj->fetch_DCB  || die "Not done";
  $PortObj->update_DCB || die "Not done";

  $milliseconds = $PortObj->get_tick_count;

Capability Methods (read only)

     # true/false capabilities
  $a = $PortObj->can_baud;      # else fixed
  $a = $PortObj->can_databits;
  $a = $PortObj->can_stopbits;
  $a = $PortObj->can_dtrdsr;
  $a = $PortObj->can_handshake;
  $a = $PortObj->can_parity_check;
  $a = $PortObj->can_parity_config;
  $a = $PortObj->can_parity_enable;
  $a = $PortObj->can_rlsd;       # receive line signal detect (carrier)
  $a = $PortObj->can_rlsd_config;
  $a = $PortObj->can_16bitmode;
  $a = $PortObj->can_ioctl;     # false, unix only
  $a = $PortObj->is_rs232;
  $a = $PortObj->is_modem;
  $a = $PortObj->can_rtscts;
  $a = $PortObj->can_xonxoff;
  $a = $PortObj->can_xon_char;
  $a = $PortObj->can_spec_char;
  $a = $PortObj->can_interval_timeout;
  $a = $PortObj->can_total_timeout;

     # list output capabilities
  ($rmax, $wmax) = $PortObj->buffer_max;
  ($rbuf, $wbuf) = $PortObj->are_buffers;       # current
  @choices = $PortObj->are_baudrate;            # legal values
  @choices = $PortObj->are_handshake;
  @choices = $PortObj->are_parity;
  @choices = $PortObj->are_databits;
  @choices = $PortObj->are_stopbits;

Configuration Methods

     # most methods can be called two ways:
  $PortObj->is_handshake("xoff");           # set parameter
  $flowcontrol = $PortObj->is_handshake;    # current value (scalar)

     # similar
  $PortObj->is_xon_limit(100);      # bytes left in buffer
  $PortObj->is_xoff_limit(100);     # space left in buffer
  $PortObj->is_error_char(0);       # for parity errors

  $rbuf = $PortObj->is_read_buf;    # read_only except internal use
  $wbuf = $PortObj->is_write_buf;
  $size = $PortObj->internal_buffer;

  $PortObj->is_buffers(4096, 4096);  # read, write
        # returns current in list context

  $PortObj->is_read_interval(100);    # max time between read char (millisec)
  $PortObj->is_read_char_time(5);     # avg time between read char
  $PortObj->is_read_const_time(100);  # total = (avg * bytes) + const

  $PortObj->is_binary(T);               # just say Yes (Win 3.x option)
  $PortObj->is_parity_enable(F);        # faults during input

Operating Methods

  ($BlockingFlags, $InBytes, $OutBytes, $LatchErrorFlags) = $PortObj->is_status
        || warn "could not get port status\n";

  $ClearedErrorFlags = $PortObj->reset_error;
        # The API resets errors when reading status, $LatchErrorFlags
        # is all $ErrorFlags since they were last explicitly cleared

  if ($BlockingFlags) { warn "Port is blocked"; }
  if ($BlockingFlags & BM_fCtsHold) { warn "Waiting for CTS"; }
  if ($LatchErrorFlags & CE_FRAME) { warn "Framing Error"; }

Additional useful constants may be exported eventually.

  $count_in = $PortObj->read_bg($InBytes);
  ($done, $count_in, $string_in) = $PortObj->read_done(1);
        # background read with wait until done

  $count_out = $PortObj->write_bg($output_string);      # background write
  ($done, $count_out) = $PortObj->write_done(0);

  $PortObj->suspend_tx;                 # output from write buffer
  $PortObj->xmit_imm_char(0x03);        # bypass buffer (and suspend)

  $PortObj->xoff_active;                # simulate received xoff
  $PortObj->xon_active;                 # simulate received xon


      # controlling outputs from the port
  $PortObj->dtr_active(T);              # sends outputs direct to hardware
  $PortObj->rts_active(Yes);            # returns status of API call
  $PortObj->break_active(N);            # NOT state of bit

  $PortObj->pulse_break_on($milliseconds); # off version is implausible
      # sets_bit, delays, resets_bit, delays

  $ModemStatus = $PortObj->is_modemlines;
  if ($ModemStatus & $PortObj->MS_RLSD_ON) { print "carrier detected"; }

  $PortObj->close || die;
      # "undef $PortObj" preferred unless reopening port
      # "close" should precede "undef" if both used


This provides fairly low-level access to the Win32 System API calls dealing with serial ports.

Uses features of the Win32 API to implement non-blocking I/O, serial parameter setting, event-loop operation, and enhanced error handling.

To pass in NULL as the pointer to an optional buffer, pass in $null=0. This is expected to change to an empty list reference, [], when Perl supports that form in this usage.

Beyond raw access to the API calls and related constants, this module will eventually handle smart buffer allocation and translation of return codes.


The constructor is new with a PortName (as the Registry knows it) specified. This will do a CreateFile, get the available options and capabilities via the Win32 API, and create the object. The port is not yet ready for read/write access. First, the desired parameter settings must be established. Since these are tuning constants for an underlying hardware driver in the Operating System, they should all checked for validity by the method calls that set them. The initialize method takes a list of required parameters and confirms they have been set. For others, it will attempt to deduce defaults from the hardware or from other parameters. The initialize method returns the number of faults (zero if the port is setup ok). The update_DCB method writes a new Device Control Block to complete the startup and allow the port to be used. Ports are opened for binary transfers. A separate binmode is not needed. The USER must release the object if initialize or update_DCB does not succeed.

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". 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.

The fault checking in initialize consists in verifying an _N_$item internal variable exists for each $item in the input list. The _N_$item is created for each parameter that is set either directly or by default. A derived class must create the _N_$items for any varibles it adds to the base class if it wants initialize to check them. Win32API::CommPort supports the following:

        $item           _N_$item            setting method
        ------          ---------           --------------
        BAUD            "_N_BAUD"           is_baudrate
        BINARY          "_N_BINARY"         is_binary
        DATA            "_N_DATA"           is_databits
        EOFCHAR         "_N_EOFCHAR"        is_eof_char
        ERRCHAR         "_N_ERRCHAR"        is_error_char
        EVTCHAR         "_N_EVTCHAR"        is_event_char
        HSHAKE          "_N_HSHAKE"         is_handshake
        PARITY          "_N_PARITY"         is_parity
        PARITY_EN       "_N_PARITY_EN"      is_parity_enable
        RCONST          "_N_RCONST"         is_read_const_time
        READBUF         "_N_READBUF"        is_read_buf
        RINT            "_N_RINT"           is_read_interval
        RTOT            "_N_RTOT"           is_read_char_time
        STOP            "_N_STOP"           is_stopbits
        WCONST          "_N_WCONST"         is_write_const_time
        WRITEBUF        "_N_WRITEBUF"       is_write_buf
        WTOT            "_N_WTOT"           is_write_char_time
        XOFFCHAR        "_N_XOFFCHAR"       is_xoff_char
        XOFFLIM         "_N_XOFFLIM"        is_xoff_limit
        XONCHAR         "_N_XONCHAR"        is_xon_char
        XONLIM          "_N_XONLIM"         is_xon_limit

Some individual parameters (eg. baudrate) can be changed after the initialization is completed. These will automatically update the Device Control Block as required. The init_done method indicates when initialize has completed successfully.

  $PortObj = new Win32API::CommPort ($PortName, $quiet)
       || die "Can't open $PortName: $^E\n";    # $quiet is optional

  if $PortObj->can_databits { $PortObj->is_databits(8) };
  $PortObj->is_buffers(4096, 4096);

  @required = qw( BAUD DATA STOP PARITY );
  $PortObj->initialize(@required) || undef $PortObj;


  $PortObj->close || die;
      # "undef $PortObj" preferred unless reopening port
      # "close" should precede "undef" if both used

  undef $PortObj;  # closes port AND frees memory in perl

The PortName maps to both the Registry Device Name and the Properties associated with that device. A single Physical port can be accessed using two or more Device Names. But the options and setup data will differ significantly in the two cases. A typical example is a Modem on port "COM2". Both of these PortNames open the same Physical hardware:

  $P1 = new Win32API::CommPort ("COM2");

  $P2 = new Win32API::CommPort ("\\\\.\\Nanohertz Modem model K-9");

$P1 is a "generic" serial port. $P2 includes all of $P1 plus a variety of modem-specific added options and features. The "raw" API calls return different size configuration structures in the two cases. Win32 uses the "\\.\" prefix to identify "named" devices. Since both names use the same Physical hardware, they can not both be used at the same time. The OS will complain. Consider this A Good Thing.

Version 0.16 adds pulse methods for the RTS, BREAK, and DTR bits. The pulse methods assume the bit is in the opposite state when the method is called. They set the requested state, delay the specified number of milliseconds, set the opposite state, and again delay the specified time. These methods are designed to support devices, such as the X10 "FireCracker" control and some modems, which require pulses on these lines to signal specific events or data.


Version 0.16 also adds experimental support for the rest of the option bits available through the Device Control Block. They have not been extensively tested and these settings are NOT saved in the configuration file by Win32::SerialPort. Please let me know if one does not work as advertised. [Win32 API bit designation]

  $PortObj->ignore_null(0);     # discard \000 bytes on input [fNull]

  $PortObj->ignore_no_dsr(0);   # discard input bytes unless DSR
                                # [fDsrSensitivity]

  $PortObj->subst_pe_char(0);   # replace parity errors with B<is_error_char>
                                # when B<is_parity_enable> [fErrorChar]

  $PortObj->abort_on_error(0);  # cancel read/write [fAbortOnError]

      # next one set by $PortObj->is_handshake("dtr");
  $PortObj->output_dsr(0);      # use DSR handshake on output [fOutxDsrFlow]

      # next one set by $PortObj->is_handshake("rts");
  $PortObj->output_cts(0);      # use CTS handshake on output [fOutxCtsFlow]

      # next two set by $PortObj->is_handshake("xoff");
  $PortObj->input_xoff(0);      # use Xon/Xoff handshake on input [fInX]
  $PortObj->output_xoff(0);     # use Xon/Xoff handshake on output [fOutX]

  $PortObj->tx_on_xoff(0);      # continue output even after input xoff sent
                                # [fTXContinueOnXoff]

The get_tick_count method is a wrapper around the Win32::GetTickCount() function. It matches a corresponding method in Device::SerialPort which does not have access to the Win32:: namespace. It still returns time in milliseconds - but can be used in cross-platform scripts.

Configuration and Capability Methods

The Win32 Serial Comm API provides extensive information concerning the capabilities and options available for a specific port (and instance). "Modem" ports have different capabilties than "RS-232" ports - even if they share the same Hardware. Many traditional modem actions are handled via TAPI. "Fax" ports have another set of options - and are accessed via MAPI. Yet many of the same low-level API commands and data structures are "common" to each type ("Modem" is implemented as an "RS-232" superset). In addition, Win95 supports a variety of legacy hardware (e.g fixed 134.5 baud) while WinNT has hooks for ISDN, 16-data-bit paths, and 256Kbaud.

    Binary selections will accept as true any of the following: ("YES", "Y", "ON", "TRUE", "T", "1", 1) (upper/lower/mixed case) Anything else is false.

    There are a large number of possible configuration and option parameters. To facilitate checking option validity in scripts, most configuration methods can be used in two different ways:

    method called with an argument

    The parameter is set to the argument, if valid. An invalid argument returns false (undef) and the parameter is unchanged. After init_done, the port will be updated immediately if allowed. Otherwise, the value will be applied when update_DCB is called.

    method called with no argument in scalar context

    The current value is returned. If the value is not initialized either directly or by default, return "undef" which will parse to false. For binary selections (true/false), return the current value. All current values from "multivalue" selections will parse to true. Current values may differ from requested values until init_done. There is no way to see requests which have not yet been applied. Setting the same parameter again overwrites the first request. Test the return value of the setting method to check "success".

    Asynchronous (Background) I/O

    This version now handles Polling (do if Ready), Synchronous (block until Ready), and Asynchronous Modes (begin and test if Ready) with the timeout choices provided by the API. No effort has yet been made to interact with Windows events. But background I/O has been used successfully with the Perl Tk modules and callbacks from the event loop.


    The API provides two timing models. The first applies only to reading and essentially determines Read Not Ready by checking the time between consecutive characters. The ReadFile operation returns if that time exceeds the value set by is_read_interval. It does this by timestamping each character. It appears that at least one character must by received in every read call to the API to initialize the mechanism. The timer is then reset by each succeeding character. If no characters are received, the read will block indefinitely.

    Setting is_read_interval to 0xffffffff will do a non-blocking read. The ReadFile returns immediately whether or not any characters are actually read. This replicates the behavior of the API.

    The other model defines the total time allowed to complete the operation. A fixed overhead time is added to the product of bytes and per_byte_time. A wide variety of timeout options can be defined by selecting the three parameters: fixed, each, and size.

    Read_Total = is_read_const_time + (is_read_char_time * bytes_to_read)

    Write_Total = is_write_const_time + (is_write_char_time * bytes_to_write)

    When reading a known number of characters, the Read_Total mechanism is recommended. This mechanism MUST be used with Win32::SerialPort tied FileHandles because the tie methods can make multiple internal API calls. The Read_Interval mechanism is suitable for a read_bg method that expects a response of variable or unknown size. You should then also set a long Read_Total timeout as a "backup" in case no bytes are received.


Nothing is exported by default. The following tags can be used to have large sets of symbols exported:


Utility subroutines and constants for parameter setting and test:

        LONGsize        SHORTsize       nocarp          yes_true
        OS_Error        internal_buffer

Serial communications status constants. Included are the constants for ascertaining why a transmission is blocked:

        BM_fCtsHold     BM_fDsrHold     BM_fRlsdHold    BM_fXoffHold
        BM_fXoffSent    BM_fEof         BM_fTxim        BM_AllBits

Which incoming bits are active:

        MS_CTS_ON       MS_DSR_ON       MS_RING_ON      MS_RLSD_ON

What hardware errors have been detected:

        CE_BREAK        CE_TXFULL       CE_MODE

Offsets into the array returned by status:

        ST_BLOCK        ST_INPUT        ST_OUTPUT       ST_ERROR

The constants and wrapper methods for low-level API calls. Details of these methods may change with testing. Some may be inherited from Win32API::File when that becomes available.

  $result=ClearCommError($handle, $Error_BitMask_p, $CommStatus);
  $result=GetCommModemStatus($handle, $ModemStatus);
  $result=GetCommProperties($handle, $CommProperties);
  $result=GetCommState($handle, $DCB_Buffer);
  $result=SetCommState($handle, $DCB_Buffer);
  $result=SetupComm($handle, $in_buf_size, $out_buf_size);
  $result=ReadFile($handle, $buffer, $wanted, $got, $template);
  $result=WriteFile($handle, $buffer, $size, $count, $template);

  $result=GetCommTimeouts($handle, $CommTimeOuts);
  $result=SetCommTimeouts($handle, $CommTimeOuts);
  $result=EscapeCommFunction($handle, $Func_ID);
  $result=GetCommConfig($handle, $CommConfig, $Size);
  $result=SetCommConfig($handle, $CommConfig, $Size);
  $result=PurgeComm($handle, $flags);

  $result=GetCommMask($handle, $Event_Bitmask);
  $result=SetCommMask($handle, $Event_Bitmask);
  $hEvent=CreateEvent($security, $reset_req, $initial, $name);
  $handle=CreateFile($file, $access, $share, $security,
                     $creation, $flags, $template);
  $result=TransmitCommChar($handle, $char);
  $result=WaitCommEvent($handle, $Event_Bitmask, $lpOverlapped);
  $result=GetOverlappedResult($handle, $lpOverlapped, $count, $bool);

Flags used by PurgeComm:


Function IDs used by EscapeCommFunction:

        SETXOFF         SETXON          SETRTS          CLRRTS
        SETDTR          CLRDTR          SETBREAK        CLRBREAK

Events used by WaitCommEvent:

        EV_RXCHAR       EV_RXFLAG       EV_TXEMPTY      EV_CTS
        EV_DSR          EV_RLSD         EV_BREAK        EV_ERR
        EV_RING         EV_PERR         EV_RX80FULL     EV_EVENT1

Errors specific to GetOverlappedResult:


The constants for the CommProperties structure returned by GetCommProperties. Included mostly for completeness.

        BAUD_USER       BAUD_075        BAUD_110        BAUD_134_5
        BAUD_150        BAUD_300        BAUD_600        BAUD_1200
        BAUD_1800       BAUD_2400       BAUD_4800       BAUD_7200
        BAUD_9600       BAUD_14400      BAUD_19200      BAUD_38400
        BAUD_56K        BAUD_57600      BAUD_115200     BAUD_128K

        PST_FAX         PST_LAT         PST_MODEM       PST_PARALLELPORT
        PST_RS232       PST_RS422       PST_X25         PST_NETWORK_BRIDGE
        PST_RS423       PST_RS449       PST_SCANNER     PST_TCPIP_TELNET

        PCF_DTRDSR              PCF_SPECIALCHARS        PCF_RLSD
        PCF_RTSCTS              PCF_SETXCHAR            PCF_TOTALTIMEOUTS


        DATABITS_5      DATABITS_6      DATABITS_7      DATABITS_8
        DATABITS_16     DATABITS_16X

        STOPBITS_10     STOPBITS_15     STOPBITS_20



The constants for the Device Control Block returned by GetCommState and updated by SetCommState. Again, included mostly for completeness. But there are some combinations of "FM_f" settings which are not currently supported by high-level commands. If you need one of those, please report the lack as a bug.

        CBR_110         CBR_300         CBR_600         CBR_1200
        CBR_2400        CBR_4800        CBR_9600        CBR_14400
        CBR_19200       CBR_38400       CBR_56000       CBR_57600
        CBR_115200      CBR_128000      CBR_256000




        FM_fBinary              FM_fParity              FM_fOutxCtsFlow
        FM_fOutxDsrFlow         FM_fDtrControl          FM_fDsrSensitivity
        FM_fTXContinueOnXoff    FM_fOutX                FM_fInX
        FM_fErrorChar           FM_fNull                FM_fRtsControl
        FM_fAbortOnError        FM_fDummy2

All of the above. Except for the test suite, there is not really a good reason to do this.


The object returned by new is NOT a Filehandle. You will be disappointed if you try to use it as one.

e.g. the following is WRONG!!____print $PortObj "some text";

Win32::SerialPort supports accessing ports via Tied Filehandles.

An important note about Win32 filenames. The reserved device names such as COM1, AUX, LPT1, CON, PRN can NOT be used as filenames. Hence "COM2.cfg" would not be usable for $Configuration_File_Name.

This module uses Win32::API extensively. The raw API calls are very unforgiving. You will certainly want to start perl with the -w switch. If you can, use strict as well. Try to ferret out all the syntax and usage problems BEFORE issuing the API calls (many of which modify tuning constants in hardware device drivers....not where you want to look for bugs).

Thanks to Ken White for testing on NT.


The current version of the module has been designed for testing using the ActiveState and Core (GS 5.004_02) ports of Perl for Win32 without requiring a compiler or using XS. In every case, compatibility has been selected over performance. Since everything is (sometimes convoluted but still pure) Perl, you can fix flaws and change limits if required. But please file a bug report if you do. This module has been tested with each of the binary perl versions for which Win32::API is supported: AS builds 315, 316, and 500-509 and GS 5.004_02. It has only been tested on Intel hardware.


With all the options, this module needs a good tutorial. It doesn't have a complete one yet. A "How to get started" tutorial appeared The Perl Journal #13 (March 1999). The demo programs are a good starting point for additional examples.


The size of the Win32 buffers are selectable with is_buffers. But each read method currently uses a fixed internal buffer of 4096 bytes. This can be changed in the module source. The read-only internal_buffer method will give the current size. There are other fixed internal buffers as well. But no one has needed to change those. The XS version will support dynamic buffer sizing.


Lots of modem-specific options are not supported. The same is true of TAPI, MAPI. API Wizards are welcome to contribute.

API Options

Lots of options are just "passed through from the API". Some probably shouldn't be used together. The module validates the obvious choices when possible. For something really fancy, you may need additional API documentation. Available from Micro$oft Pre$$.


ActiveState ports of Perl for Win32 before build 500 do not support the tools for building extensions and so will not support later versions of this extension. In particular, the automated install and test scripts in this distribution work differently with ActiveState builds 3xx.

There is no parameter checking on the "raw" API calls. You probably should be familiar with using the calls in "C" before doing much experimenting.

On Win32, a port must close before it can be reopened again by the same process. If a physical port can be accessed using more than one name (see above), all names are treated as one. The perl script can also be run multiple times within a single batch file or shell script. The Makefile.PL spawns subshells with backticks to run the test suite on Perl 5.003 - ugly, but it works.

On NT, a read_done or write_done returns False if a background operation is aborted by a purge. Win95 returns True.

A few NT systems seem to set can_parity_enable true, but do not actually support setting is_parity_enable. This may be a characteristic of certain third-party serial drivers. Or a Microsoft bug. I have been able to reproduce it on my system, but not identify a specific cause.

__Please send comments and bug reports to


Bill Birthisel,,

Tye McQueen contributed but no longer supports these modules.


Wi32::SerialPort - High-level user interface/front-end for this module

Win32API::File when available

Win32::API - Aldo Calpini's "Magic", - Tom (Christiansen)'s Object-Oriented Tutorial


Copyright (C) 2010, Bill Birthisel. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


Most of the code in this module has been stable since version 0.12. Version 0.20 adds explicit support for COM10++ and USB - although the functionality existed before. Perl ports before 5.6.0 are no longer supported for test or install. The modules themselves work with 5.003. 1 April 2010.

1 POD Error

The following errors were encountered while parsing the POD:

Around line 2748:

You can't have =items (as at line 2758) unless the first thing after the =over is an =item