Vous êtes sur la page 1sur 61

Introduction

A few days ago I said to myself that I wanted to know more about how to communicate via the
serial port. When I first started searching the internet about this subject I found out that it�s not
many articles that are discussing this subject and those examples that I found was mostly about
the earlier VB6 MSComm control and wrappers for this control. Those matters concerning the
MSComm control were not very interesting because I had read that in .NET 2.0 Microsoft had
come up with a new serial port control.

As a newbie I have been spending some hours of my time to come up with what I now share with
you, but as you all know it�s worth every hour when you succeed. It�s actually not a big deal
to do it; it�s just a few lines of code.

Fore those of you who are familiar with the serial port communication I want to recommend this
article on the Code Project. It is an excellent article about communicating with mobile phones
via the serial port, and it is very clear when you fist know the basic.

The task of this example is very simple. We want to send a text string from one computer via the
serial port to another computer. First of all you have to bee in the position that you have 2
computers and second you got to have a �null modem cable�. Another option is that you have
2 serial ports on the computer and connecting them with a �null modem cable�

If you don�t know what a �null modem cable� is then search the internet to see how it is
configured.

First of all we want to write to the serial port, and here is the basic.

If you have 2 computers have this one on the first computer. If you have one computer make this
a separate project.

In this example you got to have a Button control called btnSendText and a textBox control
called txtSendText on your form on computer nr1. Just type in some text in the btnSendText
control and Click Button send to send it to COM1.

Imports System
Imports System.IO.Ports

Public Class Form1


Dim WithEvents Port As SerialPort = _
New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
Private Sub btnSendText_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSendText.Click
Port.Open()
Port.Write(txtSendText.Text & "!%")
Port.Close()
End Sub
End Class
This is just how simple it is to send a text string to the serial port.

And now how to receive the text string on the other computer.

If you have 2 computers have the next example one on the second computer. If you have one
computer make this a separate project, and then run both projects at the same time.

In this example you got to have a Text control called TextBox1 and a listbox control called
ListBox1 on your form on computer nr2. When clicking send on computer nr1 you will receive
it in the textbox1 control on computer nr 2. When the buffer is 0 it will be added to the Listbox1
control, and ListBox1 is empty to receive the next incoming text string.

Imports System
Imports System.IO.Ports

Public Class Form1


Dim WithEvents port As SerialPort = New _
System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As _


System.EventArgs) Handles Me.Load
CheckForIllegalCrossThreadCalls = False
If port.IsOpen = False Then port.Open()
End Sub

Private Sub port_DataReceived(ByVal sender As Object, ByVal e As _


System.IO.Ports.SerialDataReceivedEventArgs) Handles port.DataReceived
TextBox1.Text = (port.ReadTo("!%"))
If port.ReadExisting.Length = 0 Then
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Text = ""
End If
End Sub
End Class

The important thing to notice is that you have to declare the port like this �Dim WithEvents
port ...�

You also got to have a �CheckForIllegalCrossThreadCalls = False� declaration in the in


the form load procedure to prevent it from raising an error when a thread other than the creating
thread of a control tries to access one of that control's methods or properties. You also have to
check if the port is open, and if it�s not open you have to open it.

As you may see that I have some special characters in both the write and the read statement.

port.Write(txtSendText.Text & "!%") and port.ReadTo("!%").

This is because if I put some special characters in the write statement stream I can ask the
readTo statement to read everything until the special character and that is quiet convenient. Just
test it.
There are many other options to the serial port communication, and this is only one of them.

I hope it can be of any help to somebody.


Serial Port Communication in C#

Posted 20 October 2007 - 07:09 PM

Welcome to my tutorial on Serial Port Communication in C#. Lately Ive seen a lot of questions on how to
send and receive data through a serial port, so I thought it was time to write on the topic. Back in the
days of Visual Basic 6.0, you had to use the MSComm Control that was shipped with VB6, the only
problem with this method was you needed to make sure you included that control in your installation
package, not really that big of a deal. The control did exactly what was needed for the task.

We were then introduced to .Net 1.1, VB programmers loved the fact that Visual Basic had finally
evolved to an OO language. It was soon discovered that, with all it's OO abilities, the ability to
communicate via a serial port wasn't available, so once again VB developers were forced to rely on the
MSComm Control from previous versions of Visual Basic, still not that big of a deal, but some were upset
that an intrinsic way of serial port communication wasn't offered with the .net Framework. Worse yet,
C# developers had to rely on a Visual Basic control and Namespace if they wanted to communicate via
serial port.

Then along comes .Net 2.0, and this time Microsoft added the System.IO.Ports Namespace, and within
that was the SerialPort Class. DotNet developers finally had an intrinsic way of serial port
communication, without having to deal with the complexities of interoping with an old legacy ActiveX
OCX control. One of the most useful methods in the SerialPort class is the GetPortNames Method. This
allows you to retrieve a list of available ports (COM1,COM2,etc.) available for the computer the
application is running on.

Now that we have that out of the way, lets move on to programming our application. As with all
application I create, I keep functionality separated from presentation, I do this by creating Manager
classes that manage the functionality for a given process. What we will be looking at is the code in my
CommunicationManager class. As with anything you write in .Net you need to add the references to the
Namespace's you'll be using:

using System;
using System.Text;
using System.Drawing;
using System.IO.Ports;

In this application I wanted to give the user the option of what format they wanted to send the message
in, either string or binary, so we have an enumeration for that, and an enumerations for the type of
message i.e; Incoming, Outgoing, Error, etc. The main purpose of this enumeration is for changing the
color of the text displayed to the user according to message type. Here are the enumerations:

#region Manager Enums


/// <summary>
/// enumeration to hold our transmission types
/// </summary>
public enum TransmissionType { Text, Hex }

/// <summary>
/// enumeration to hold our message types
/// </summary>
public enum MessageType { Incoming, Outgoing, Normal, Warning, Error };
#endregion

Next we have our variable list, 6 of them are for populating our class Properties, the other 2 are access
throughout the class so they needed to be made global:

#region Manager Variables


//property variables
private string _baudRate = string.Empty;
private string _parity = string.Empty;
private string _stopBits = string.Empty;
private string _dataBits = string.Empty;
private string _portName = string.Empty;
private TransmissionType _transType;
private RichTextBox _displayWindow;
//global manager variables
private Color[] MessageColor = { Color.Blue, Color.Green, Color.Black,
Color.Orange, Color.Red };
private SerialPort comPort = new SerialPort();
#endregion

NOTE:I always separate my code into sections using the #region ... #endregion to make it easier when
scanning my code. It is a design choice so it's not necessary if you don't want to do it.

Now we need to create our class properties. All the properties in this class are public read/write
properties. We have properties for the following items of the Serial Port:

 Baud Rate: A measure of the speed of serial communication, roughly equivalent to bits per
second.
 Parity: The even or odd quality of the number of 1's or 0's in a binary code, often used to
determine the integrity of data especially after transmission.
 Stop Bits: A bit that signals the end of a transmission unit
 Data Bits: The number of bits used to represent one character of data.
 Port Name: The port with which we're communicating through, i.e; COM1, COM2, etc.

We also have 2 properties that aren't related to the port itself, but with where the data will be
displayed, and what transmission type to use:
#region Manager Properties
/// <summary>
/// Property to hold the BaudRate
/// of our manager class
/// </summary>
public string BaudRate
{
get { return _baudRate; }
set { _baudRate = value; }
}

/// <summary>
/// property to hold the Parity
/// of our manager class
/// </summary>
public string Parity
{
get { return _parity; }
set { _parity = value; }
}

/// <summary>
/// property to hold the StopBits
/// of our manager class
/// </summary>
public string StopBits
{
get { return _stopBits; }
set { _stopBits = value; }
}

/// <summary>
/// property to hold the DataBits
/// of our manager class
/// </summary>
public string DataBits
{
get { return _dataBits; }
set { _dataBits = value; }
}

/// <summary>
/// property to hold the PortName
/// of our manager class
/// </summary>
public string PortName
{
get { return _portName; }
set { _portName = value; }
}

/// <summary>
/// property to hold our TransmissionType
/// of our manager class
/// </summary>
public TransmissionType CurrentTransmissionType
{
get{ return _transType;}
set{ _transType = value;}
}

/// <summary>
/// property to hold our display window
/// value
/// </summary>
public RichTextBox DisplayWindow
{
get { return _displayWindow; }
set { _displayWindow = value; }
}
#endregion

To be able to instantiate any class object we create we need Constructors. Constructors are the entry
point to your class, and is the first code executed when instantiating a class object. We have 2
constructors for our manager class, one that sets our properties to a specified value, and one that sets
our properties to an empty value, thus initializing the variables preventing a NullReferenceException
from occurring. We also add an EventHandler in the constructor, the event will be executed whenever
there's data waiting in the buffer:

#region Manager Constructors


/// <summary>
/// Constructor to set the properties of our Manager Class
/// </summary>
/// <param name="baud">Desired BaudRate</param>
/// <param name="par">Desired Parity</param>
/// <param name="sBits">Desired StopBits</param>
/// <param name="dBits">Desired DataBits</param>
/// <param name="name">Desired PortName</param>
public CommunicationManager(string baud, string par, string sBits, string
dBits, string name, RichTextBox rtb)
{
_baudRate = baud;
_parity = par;
_stopBits = sBits;
_dataBits = dBits;
_portName = name;
_displayWindow = rtb;
//now add an event handler
comPort.DataReceived += new
SerialDataReceivedEventHandler(comPort_DataReceived);
}

/// <summary>
/// Comstructor to set the properties of our
/// serial port communicator to nothing
/// </summary>
public CommunicationManager()
{
_baudRate = string.Empty;
_parity = string.Empty;
_stopBits = string.Empty;
_dataBits = string.Empty;
_portName = "COM1";
_displayWindow = null;
//add event handler
comPort.DataReceived+=new
SerialDataReceivedEventHandler(comPort_DataReceived);
}
#endregion

The first think you need to know about serial port communication is writing data to the port. The first
thing we do in our WriteData method is to check what transmission mode the user has selected, since
binary data needs to be converted into binary, then back to string for displaying to the user. Next we
need to make sure the port is open, for this we use the IsOpen Property of the SerialPort Class. If the
port isn't open we open it by calling the Open Method of the SerialPort Class. For writing to the port we
use the Write Method:

#region WriteData
public void WriteData(string msg)
{
switch (CurrentTransmissionType)
{
case TransmissionType.Text:
//first make sure the port is open
//if its not open then open it
if (!(comPort.IsOpen == true)) comPort.Open();
//send the message to the port
comPort.Write(msg);
//display the message
DisplayData(MessageType.Outgoing, msg + "\n");
break;
case TransmissionType.Hex:
try
{
//convert the message to byte array
byte[] newMsg = HexToByte(msg);
//send the message to the port
comPort.Write(newMsg,0,newMsg.Length);
//convert back to hex and display
DisplayData(MessageType.Outgoing,
ByteToHex(newMsg) + "\n");
}
catch (FormatException ex)
{
//display error message
DisplayData(MessageType.Error, ex.Message);
}
finally
{
_displaywindow.SelectAll();
}
break;
default:
//first make sure the port is open
//if its not open then open it
if (!(comPort.IsOpen == true)) comPort.Open();
//send the message to the port
comPort.Write(msg);
//display the message
DisplayData(MessageType.Outgoing, msg + "\n");
break;
break;
}
}
#endregion

You will notice in this method we call three methods:

 HexToByte
 ByteToHex
 DisplayData

These methods are required for this manager. The HexToByte method converts the data provided to
binary format, then the ByteToHex converts it back to hex format for displaying. The last one,
DisplayData is where we marshal a call to the thread that created the control for displaying the data,
since UI controls can only be accessed by the thread that created them. First we'll look at converting the
string provided to binary format:

#region HexToByte
/// <summary>
/// method to convert hex string into a byte array
/// </summary>
/// <param name="msg">string to convert</param>
/// <returns>a byte array</returns>
private byte[] HexToByte(string msg)
{
//remove any spaces from the string
msg = msg.Replace(" ", "");
//create a byte array the length of the
//string divided by 2
byte[] comBuffer = new byte[msg.Length / 2];
//loop through the length of the provided string
for (int i = 0; i < msg.Length; i += 2)
//convert each set of 2 characters to a byte
//and add to the array
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2),
16);
//return the array
return comBuffer;
}
#endregion
Here we convert the provided string to a byte array, then the WriteData method sends it out the port.
For displaying we need to convert it back into string format, so we use the ByteToHex method we
created:

#region ByteToHex
/// <summary>
/// method to convert a byte array into a hex string
/// </summary>
/// <param name="comByte">byte array to convert</param>
/// <returns>a hex string</returns>
private string ByteToHex(byte[] comByte)
{
//create a new StringBuilder object
StringBuilder builder = new StringBuilder(comByte.Length * 3);
//loop through each byte in the array
foreach (byte data in comByte)
//convert the byte to a string and add to the stringbuilder
builder.Append(Convert.ToString(data, 16).PadLeft(2,
'0').PadRight(3, ' '));
//return the converted value
return builder.ToString().ToUpper();
}
#endregion

The last method that WriteData depends on is the DisplayData method. Here we use the Invoke
Method of our RichTextBox, the control used to display the data, to create a new EventHandler which
creates a new Delegate for setting the properties we wish for our message, then appending it to the
value already displayed:

#region DisplayData
/// <summary>
/// method to display the data to & from the port
/// on the screen
/// </summary>
/// <param name="type">MessageType of the message</param>
/// <param name="msg">Message to display</param>
[STAThread]
private void DisplayData(MessageType type, string msg)
{
_displaywindow.Invoke(new EventHandler(delegate
{
_displaywindow.SelectedText = string.Empty;
_displaywindow.SelectionFont = new Font(_displaywindow.SelectionFont,
FontStyle.Bold);
_displaywindow.SelectionColor = MessageColor[(int)type];
_displaywindow.AppendText(msg);
_displaywindow.ScrollToCaret();
}));
}
#endregion

NOTE: You will notice that we hyave added the STAThread Attribute to our method. This is used when a
single thread apartment is required by a control, like the RichTextBox.

The next method we will look at it used when we need to open the port initially. Here we set the
BaudRate, Parity, StopBits, DataBits and PortName Properties of the SerialPort Class:

#region OpenPort
public bool OpenPort()
{
try
{
//first check if the port is already open
//if its open then close it
if (comPort.IsOpen == true) comPort.Close();

//set the properties of our SerialPort Object


comPort.BaudRate = int.Parse(_baudRate); //BaudRate
comPort.DataBits = int.Parse(_dataBits); //DataBits
comPort.StopBits =
(StopBits)Enum.Parse(typeof(StopBits),_stopBits); //StopBits
comPort.Parity = (Parity)Enum.Parse(typeof(Parity),_parity);
//Parity
comPort.PortName = _portName; //PortName
//now open the port
comPort.Open();
//display message
DisplayData(MessageType.Normal, "Port opened at " +
DateTime.Now + "\n");
//return true
return true;
}
catch (Exception ex)
{
DisplayData(MessageType.Error, ex.Message);
return false;
}
}
#endregion

Next lets take a look at our event handler. This event will be executed whenever there's data waiting in
the buffer. This method looks identical to our WriteData method, because it has to do the same exact
work:

#region comPort_DataReceived
/// <summary>
/// method that will be called when theres data waiting in the buffer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//determine the mode the user selected (binary/string)
switch (CurrentTransmissionType)
{
//user chose string
case TransmissionType.Text:
//read data waiting in the buffer
string msg = comPort.ReadExisting();
//display the data to the user
DisplayData(MessageType.Incoming, msg + "\n");
break;
//user chose binary
case TransmissionType.Hex:
//retrieve number of bytes in the buffer
int bytes = comPort.BytesToRead;
//create a byte array to hold the awaiting data
byte[] comBuffer = new byte[bytes];
//read the data and store it
comPort.Read(comBuffer, 0, bytes);
//display the data to the user
DisplayData(MessageType.Incoming, ByteToHex(comBuffer)
+ "\n");
break;
default:
//read data waiting in the buffer
string str = comPort.ReadExisting();
//display the data to the user
DisplayData(MessageType.Incoming, str + "\n");
break;
}
}
#endregion

We have 3 small methods left, and these are actually optional, for the lack of a better word. These
methods are used to populate my ComboBox's on my UI with the port names available on the computer,
Parity values and Stop Bit values. The Parity and Stop Bits are available in enumerations included with
the .Net Framework 2.0:

 Parity Enumeration
 StopBits Enumeration

#region SetParityValues
public void SetParityValues(object obj)
{
foreach (string str in Enum.GetNames(typeof(Parity)))
{
((ComboBox)obj).Items.Add(str);
}
}
#endregion

#region SetStopBitValues
public void SetStopBitValues(object obj)
{
foreach (string str in Enum.GetNames(typeof(StopBits)))
{
((ComboBox)obj).Items.Add(str);
}
}
#endregion

#region SetPortNameValues
public void SetPortNameValues(object obj)
{

foreach (string str in SerialPort.GetPortNames())


{
((ComboBox)obj).Items.Add(str);
}
}
#endregion

That is how you do Serial Port Communication in C#. Microsoft finally gave us intrinsic tools to perform
this task, no more relying on legacy objects. I am providing this class and a sample application to show
how to implement what we just learned. What I am providing is under the GNU General Public License
meaning you can modify and distribute how you see fit, but the license header must stay in tact. I hope
you found this tutorial useful and informative, thank you for reading.

Happy Coding
Serial Port SDK by ActiveXperts Software

[ ACTIVECOMPORT - INSTALLATION ]
Q3000010 - When I run Setup, I get the following error message: "Error installing iKernel.exe (0xa00)".
What's wrong?

A:

Most probably, you don't have administrative privileges on the machine where you install the
product. You must have local administrator rights to install ActiveComport on the computer.

Q3000012 - When trying to register your component (acomport.dll), REGSVR32 returns


the following error: 0x80070005

A:

This is not a problem of the toolkit itself, but has something to do with security settings on
Windows 7, Windows Vista, Windows 2008 and higher.

Please try the following:

When starting the command prompt, start it from the start menu by locating the "Command
Prompt" in the start menu, now right click on this item and select "Run as Administrator". When
you try to register the component from the command prompt it should work okay.

You can also try to turn of UAC (User Account Control)

Q3000015 - Can ActiveComport be installed manually?

A:

Yes it can. To install the ActiveComport COM component on another machine, simply copy the
Acomport.dll (or AComport64.dll) to another machine and issue the following command from
the command prompt:

REGSVR32 <destination-path>\Acomport.dll.
Q3000016 - Can I use REGSVR32 to register your 64-bit component?

A:

Yes, you can use REGSVR32 to register the 64-bit component (AComportX64.dll), e.g.:

REGSVR32 AComportX64.dll

You can also register the 32-bit component (AComport.dll) on a 64-bit system in the same way,
e.g.:

REGSVR32 AComport.dll

To make use of the 64-bit DLL, you should use a 64-bit application or 64-bit interpreter, e.g.:

CSCRIPT.EXE QueryDevice.vbs

To make use of the 32-bit DLL, you should use a 32-bit application or 32-bit interpreter, e.g.:

C:\Windows\SysWow64\CSCRIPT.EXE QueryDevice.vbs

NOTE: The module property tells you which component (32-bit or 64-bit) you are actually
using. The following VBScript program will tell you:

Set o = CreateObject( "ActiveXperts.ComPort" )


WScript.Echo o.Module

Q3000017 - I want to re-install ActiveComport. I uninstalled first, but now the installation tells me that
I cannot install it in the same destination directory as before. Am I doing something wrong?

A:

You are right: you cannot install the product in an existing directory.

Upon un-installation, the original directory (default: C:\Program


Files\ActiveXperts\ActiveComport) is NOT deleted in case there are files created/modified after
the previous installation. You must delete these files/directories manually.

Once the directory (C:\Program Files\ActiveXperts\ActiveComport) is deleted, you can re-install


it in that directory.

In previous versions of the product, it was possible to install in an existing directory, but this
often lead to interference with previous installations.
Q3000020 - I manually registered the ActiveComport COM component on another machine, and now I
want to unregister. How can I do this?

A:

Issue the following command from the command prompt:

REGSVR32 -u <path>\Acomport.dll.

Q3000025 - How can I uninstall ActiveComport?

A:

If you used the regular ActiveComport Setup program to install the software, you can simple
uninstall the software by using the 'Add/Remove' applet in the control panel.

If you copied the ACOMPORT.DLL file manually to your system and registered manually, you
should first de-register the component by running REGSVR32 -u ACOMPORT.DLL, and then
delete the ACOMPORT.DLL file.

Q3000030 - I want to uninstall the ActiveComport software manually. How can I do this?

A:

You can do it in the following way:

 Start the registry editor (REGEDIT.EXE);


 Open the HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ key;
 Delete the 8717338B-361B-433B-998E-F7FEA8D966A4 key.
 Delete the C:\PROGRAM FILES\ACTIVEXPERTS\ACTIVECOMPORT directory and all it sub-
directories.
 Delete the 'ActiveXperts:ActiveComport' program group from the Start menu.
[ ACTIVECOMPORT - PORTS AND DEVICES ]
Q3100010 - What is Flow control?

A:

In many cases, it is necessary for the transmitting device to know whether the receiving device is
ready to receive information. You might, for example, be sending data to a printer, and the speed
of communication may be faster than the speed of the printer. The printer will need to be able to
stop the computer from sending any more chatacters until it is ready to receive them. Similary,
you may be sending data from one computer to another, and the second computer cannot process
the data as fast as it is coming in.

In both cases, information must be sent back from receiving device to the sending device to
indicate whether it is ready. This is known as 'Flow Control'. There are two types of Flow
Control: Hardware Flow Control and Software Flow Control.

Q3100015 - What is the difference between Hardware Flow control and Software Flow control?

A:

Both are used for handshaking (see also FAQ item 3100010).

With Hardware Flow Control, the receiving device sends a positive voltage along a dedicated
handshaking circuit as long as it is ready to receive. When the transmitting computer receives a
negative voltage, it knows to stop sending data.

With Software Flow Control, the handshaking signals consist of special characters transmitted
along the data circuits rather than along the hardware flow control circuits.

Q3100020 - Do I need Hardware Flow control?

A:

This depends on the the DCE (Data Carrier Equipment), the device to which you are connected.
If this device requires hardware flow control, you'll need it too. In most cases, hardware flow
control is required; that's why it is enabled by default.

For more details, please read FAQ item 3100010 and FAQ item Q3100015.
Q3100025 - Do I need Software Flow control?

A:

Software flow control is only used for data transfer. By default, flow control is switched off.
Many serial printers and modems need software flow as soon as data transfer begins.

For more details, please read FAQ item 3100010 and FAQ item Q3100015.

Q3100030 - Can I change the Baud Rate for a port when it is already opened?

A:

Yes. First change the DeviceSpeed property, and the call the Update function to apply the
property change.

Q3100035 - What does the ComTimeout property mean?

A:

The ComTimeout property tells you how long ReadString function waits for data before it
returns. By default, ComTimeout is set to 1000msec, but you can change this value.

Q3100040 - Can I change flow control for an open port?

A:

Hardware flow control you can't change for an open port; you must specify the hardware flow
control before you call the Open method.

Software flow control can be changed for an open port. First change the XOnXoff property, and
the call the Update function to apply the property change.

Q3100045 - Are USB devices supported?

A:
Only when these USB devices ship with a serial port driver. For instance, most modem
manufacturers ship their USB modems with a serial port driver, so that the modem can be
accessed through a virtual COM port. These modems can be used by ActiveComport.

Q3100050 - When I open a port, I get the following error: 30102. What does it mean?

A:

This means that the COM port does not exist. You only get this error if you use a COM port (like
COM1) rather than a Windows Telephony device (like 'Standard 9600 bps Modem'). Error
30102 does NOT mean that the port is already in use. If the port would already be in use, you
would get another error: 30103.

Q3100055 - When I open a port, I get the following error: 30103. What does it mean?

A:

This means that the port you are attempting to open is already in use by another application. You
only get this error if you use a COM port (like COM1) rather than a Windows Telephony device
(like 'Standard 9600 bps Modem').

Check if there's another application that is already using the COM port. In some situations, you
may want to benefit from a thing called 'port sharing', where one port can be shared by multiple
applications. To benefit from 'port sharing', you must use Windows Telephony devices (like
'Standard 9600 bps Modem').

Q3100060 - When I open a port, I get the following error: 30201. What does it mean?

A:

This means that the Windows Telephony Device you are using, is NOT defined on the computer.
You may have made a typing mistake. Error 30201 does NOT mean that the port is already in
use (you would get error 30202).

You will never get this error when using direct COM ports (like 'COM1'), but only when using
Windows Telephony devices.
Q3100065 - When I open a port, I get the following error: 30202. What does it mean?

A:

This error only occurs when using Windows Telephony devices (like 'Standard 9600 bps
Modem'). The error implies that the Windows Telephony device is valid, but that the associated
COM port is either already in use, or does not exist.

The error does NOT imply that the Windows Telephony device is invalid (that would give error
30201); it neither implies that the Windows Telephony device is already used (that would give
error 30204).

Q3100070 - When I open a port, I get the following error: 30203. What does it mean?

A:

This error only occurs when using Windows Telephony devices (like 'Standard 9600 bps
Modem'). The Windows Telephony device name is valid,. There can be two reasons for this
error:

 The Windows Telephony device is already in use by another application;


 The port speed is wrong; Windows is able to open the port, but is not able to initialize the device
properly because of the wrong speed. Make sure that the port speed of the device and the port
settings of the Telephony device in the Control Panel both match.

Q3100080 - I'm using a GSM modem (WaveCom Fastrack). The following error comes up:
"Error#30351: Unexpected response from modem". In the log file, I see some undisplayable characters
beinig received from the modem. What could be the problem?

A:

Most probably, the baud rate causes the problem: COM port and modem are not
sending/receving at the same speed. We stronly recommend to use 9600bps. Two things you
need to do:

1. Make sure that your COM port is configred to use 9600bps. To do so, open the Windows
Device manager and click on COM1-properties. There you can set it to 9600bps.
2. Set the modem to 9600bps. The following FAQ items describes how to set your modem to a
different speed: FAQ#Q4200075.

Q3100100 - I'm communicating with a slow devices. What I need is a small delay between the
characters transmitted when using your WriteString function. How can I achieve this?

A:

It is pretty simply to achieve, using the InterCharDelay property. This propery specifies a delay
(in milliseconds) used in WriteString between each character transmitted.

Please note there's also another property that can be used for slower devices: PreCommandDelay.
It specifies a delay (in milliseconds) used before WriteString actually starts writing the command
string.

Q3100110 - Can I play a sound file using ActiveComport?

A:

Yes, as long as your modem has a voice command set. It is easy to find out if your modem
supports voice or not: issue the 'AT+FCLASS=?'. A modem supporting voice will respond with a
list of numbers that includes the number 8.

To enter voice mode, issue the following command: 'AT+FCLASS=8' (or 'AT#CLS=8'). In voice
mode, you can answer voice calls, playback sound files and record audio.

For a complete list of voice modems commands, check your modem manual.

Q3100120 - When using your ActiveComport product, we sometimes receive incomplete strings, what
is wrong?

A:

Most probably it takes to long to read the string from the device. To fix this problem, you should
increase the value of the CommTimeout property.
Q3100130 - Does the ActiveComport toolkit fire an event when new data has arrived?

A:

No, the toolkit does not fire events. All received data is buffered in the memory, you have to poll
for new data using a timer, or using a separate thread.

Q3100140 - I need to sense when the DSR signal is raised and lowered. How can I do this?

A:

ActiveComport does not support events (so it can be used in any programming language
including scripts). You need to use the QueryDSR function to check the state of the DSR signal.
If you need to check the state continuously, you need to call this function regularly, probably in a
separate thread.

To monitor CTS (Clear-To-Send), use the QueryCTS function; to monitor DCD (Data-Carrier-
Detect), use the QueryDCD function; to monitor RI (Ring-Indicator), use the QueryRI function.

[ ACTIVECOMPORT - VISUAL BASIC, VBA AND VBSCRIPT ]


Q3200010 - How do I use the ActiveComport Toolkit object in my Visual Basic project?

A:

Please read the following document: Using ActiveComport with Visual Basic 5.x/6.x. This
document describes how to refer to the ActiveComport library, and how to declare, create and
use the object.

Q3200020 - How do I use the ActiveComport object in my VBScript program?

A:

Please read the following document: Using ActiveComport with VBScript. This document
describes how to refer to the ActiveComport Toolkit library, and how to declare, create and use
the object.
Q3200025 - How do I use the ActiveComport object in an Office Document (Excel, Access or Word)
using VBA?

A:

Please read the following document: Using ActiveComport with VBA (Visual Basic for
Applications). This document describes how to refer to the ActiveComport Toolkit library, and
how to declare, create and use the object.

Q3200030 - When running the Visual Basic sample project, I get an error: "User-defined type not
defined". What's wrong?

A:

The problem is, that you must refer to the object before you can declare and create it. Go to the
'Project' menu, choose 'References...' and put the checkbox near 'ActiveComport Type Library'.

Q3200040 - Why am I getting the following error message when running a VBScript including the
ActiveComport component:
        "Microsoft VBScript runtime error: ActiveX component can't create object: 'ActiveXperts.ComPort'"

A:

You haven't installed and registered the ActiveComport ActiveX component. This component
can be installed and registered automatically by running the ActiveComport installation, or can
be downloaded from our website and registered manually by running the command:

REGSVR32 ACOMPORT.DLL

Q3200050 - I'm using Windows 64bit and I'm getting the following error when using your VBScript
sample:
        "Microsoft VBScript runtime error: ActiveX component can't create object: 'ActiveXperts.ComPort'".
This applies to both CSCRIPT.EXE (command-line VBScript interpreter) and WSCRIPT.EXE (GUI VBScript
interpreter)

A:
This is due to the fact that Windows uses the 64bit VBScript intepreter
(C:\WINDOWS\SYSTEM32\CSCRIPT.EXE or C:\WINDOWS\SYSTEM32\WSCRIPT.EXE)
by default. Since the ActiveComport control is a 32bit control, you should invoke the WOW64
subsystem. This means C:\WINDOWS\SYSTEM32\WOW64\CSCRIPT.EXE or
C:\WINDOWS\SYSTEM32\WOW64\WSCRIPT.EXE.

[ ACTIVECOMPORT - HTML AND JAVASCRIPT ]


Q3250010 - How do I use the ActiveComport Toolkit object in my HTML form on a PC?

A:

Please read the following document: Using ActiveComport Toolkit with HTML. This document
describes how to refer to the ActiveComport library, and how to declare, create and use the
object.

Q3250020 - Is it possible to use the component in an HTML page on a PC? Do you have an HTML
sample available?

A:

Yes it is possible. There is an online sample that shows how to use the component inside an
HTML page.

In this sample, the ActiveComport ActiveX component is downloaded and installed


automatically from the following location:
www.activexperts.com/files/activcomport/acomport.dll. You get prompted to trust the
activexperts.com site. You can customize this HTML sample, and let the ActiveX source point to
another location by changing the 'codebase' reference inside this HTML file.

To avoid prompting, please read article FAQ Article 3250025.

Q3250025 - We are using the component within HTML/JavaScript code. The browser is Internet
Explorer 6. Each time the ActiveX control is loaded by the browser, a security warning is displayed.
Have you any suggestion to avoid this message?
A:

There are basically three ways to avoid prompting:

1. Add the website that hosts the ActiveX component to the trusted sites of all Internet Explorers.
This would need some automatic configuration on your LAN's Internet Explorers, for instance
through Group Policy (recommended) or through logon script. This way you only decrease
Internet Explorer security for that particular site. Security for all other sites remains the same.
This solution only works as long as the ActiveComport users are part of your network.

2. You can sign the component (the actual AComport.dll). If you only use the component for
internal use (i.e. in your network), you can use the standard Windows Certificate Server (part of
Win2000 and higher). If the component is used outside your network, you should use a public
Certificate Authority, for instance Verisign.
ActiveXperts Software does not offer facilities to sign ActiveX COM/OLE components.

3. From the Internet Explorer menu, select "Tools" -> "Internet Options"; dlick the security tab, and
click the 'Custom level...' button.
In the list of options, change the 'Initialize and script ActiveX controls not marked as safe for
scripting' setting from disable to prompt. When you restart Internet explorer and run the page
again, Internet Explorer will ask you whether to run the control or not. When asked click 'Yes'
and the page should work correctly.

Q3250030 - I want to sign the ActiveComport module so it can be used by any browser in our network
without any security alerts. How can I digitally sign the module?

A:

Please read the following article: How to digitally sign an ActiveXperts software component.

Q3250040 - Is it possible to use the component in an HTML page using a Mozilla FireFox browser?

A:

By default, the Mozilla FireFox browser is not configured to display sites that contain ActiveX
controls. Using a plugin it is possible to run the ActiveComport control. Click here to learn how
to enable ActiveComport for your Mozilla browser.
[ ACTIVECOMPORT - VISUAL C++ ]
Q3300010 - How do I use the ActiveComport Toolkit objects in my Visual Studio C++ 6.0 project?

A:

Please read the following document: Using ActiveComport Toolkit with Visual C++. This
document describes how to refer to the ActiveComport Toolkit library, and how to declare,
create and use the object.

Q3300020 - I want the create a new project in Visual C++ 6.x. What kind of project should I create so I
can include ActiveComport inside my code?

A:

In the 'New' dialog, start the MFC AppWizard. When you are asked for compound document
support, select 'Container', and choose for 'Automation' support. Don't forget to include
AComport.h and AComport_i.c (see manual)

Q3300030 - Can I use Visual Studio .NET to build the Visual C++ samples?

A:

Yes you can. Visual Studio .NET supports Visual C++ projects. When you open a Visual C++
project for the first time, Visual Studio .NET will first convert the project to the current project
format. After conversion, you'll be able to use the project.

NOTE: Visual Studio Express Edition does NOT support MFC Visual C++ projects. See also
FAQ#Q3300040.

Q3300040 - Can I use Visual Studio Express Edition to build the Visual C++ samples?

A:

Yes you can, but it should be a win32 api or console application, the use of the MFC framework
is not supported.
[ ACTIVECOMPORT - VISUAL BASIC .NET AND VISUAL C# .NET ]
Q3350003 - What .NET framework is required to run the .NET ActiveComport Toolkit sample projects?

A:

ActiveComport Toolkit is compatible with .NET Framework 1.0, 1.1, 2.0 and 3.5. The .NET
samples are created with Visual Studio 2005, and can be used with Visual Studio 2002, 2003,
2005 and 2008.

Q3350005 - How do I use the ActiveComport Toolkit objects in my Visual Basic .NET project?

A:

Please read the following document: Using ActiveComport Toolkit with Visual Basic .NET. This
document describes how to refer to the ActiveComport Toolkit library, and how to declare,
create and use the object.

Q3350007 - How do I use the ActiveComport Toolkit objects in my Visual C# .NET project?

A:

Please read the following document: Using ActiveComport Toolkit with Visual C# .NET. This
document describes how to refer to the ActiveComport Toolkit library, and how to declare,
create and use the object.

Q3350010 - Is it possible to use the ActiveComport component in a Visual Studio .NET environment?

A:

Yes, the ActiveComport component can be used in .NET development environments like Visual
C# .NET, Visual Basic .NET and ASP .NET. During installation, samples for Visual Basic .NET
and Visual C# .NET are installed (together with samples for VBScript, Visual C++, Visual Basic
and ASP).
Q3350015 - Why am I getting the following error message when compiling your Visual Basic .NET
sample:
        "Namespace or type 'ACOMPORTLib' for the Imports 'ACOMPORTLib' cannot be found."

A:

You haven't installed and registered the ActiveComport ActiveX component properly. This
component can be installed and registered automatically by running the ActiveComport
installation, or can be downloaded from our website and registered manually by running the
command:

REGSVR32 ACOMPORT.DLL.

Q3350020 - Why am I getting the following error message when compiling the Visual C# .NET sample:
        "The type or namespace name 'ACOMPORTLib' could not be found (are you missing a using
directive or an assembly reference?)"

A:

You haven't installed and registered the ActiveComport ActiveX component. This component
can be installed and registered automatically by running the ActiveComport installation, or can
be downloaded fron our website and registered manually by running the command:

REGSVR32 ACOMPORT.DLL

Q3350025 - When running my own .net application I receive the following error:
System.Runtime.InteropServices.COMException (0x80040154). What is wrong?

A:

Check if the component is correctly registered on this computer. When using Visual Studio
.NET, set the target platform to 32 bit or make sure you have registered the 64 bit version of the
ActiveComport component when the solution is running on a x64 operating system.
[ ACTIVECOMPORT - ASP .NET ]
Q3340005 - What .NET framework is required to run the .NET ActiveComport Toolkit sample projects?

A:

ActiveComport Toolkit is compatible with .NET Framework 1.0, 1.1, 2.0 and 3.5. The .NET
samples are created with Visual Studio 2005, and can be used with Visual Studio 2002, 2003,
2005 and 2008.

Q3400010 - How do I use the ActiveComport Toolkit objects in my ASP .NET project?

A:

Users of ASP .NET (Visual Basic) should read the following document: Using ActiveComport
Toolkit with ASP .NET (VB). This document describes how to refer to the ActiveComport
Toolkit library, and how to declare, create and use the objects.

Users of ASP .NET (C#) should read the following doucment: Using ActiveComport Toolkit
with ASP .NET (VB)

Q3400020 - How can I use the standard ASP .NET samples?

A:

You need to setup IIS first to be able to use the ASP .NET samples. This applies to both the
AsP .Net VB samples as well as the ASP .NET C# samples:

 Open the Control Panel, and select the 'IIS Manager' from the 'Administrative Tools' Folder;
 Righ-click on the 'Default Website' in the tree-view, and choose New->Virtual Directory from the
context-menu;
 Click 'Next'; in the 'Alias field', type: 'WebApplication' (other names won't work);
 Click Next and select the path to your ASP.NET sample directory ( i.e. "C:\Program
Files\ActiveXperts\ActiveComport\Examples\ASP.NET C#\wwwroot\WebApplication" );
 Click 'Next' and check the 'Read' and 'Run Scripts' boxes;
 Click 'Next' and 'Finish', your ASP.Net application has been setup now;
 Type http://localhost/WebApplication/Webform1.aspx in the explorer's address bar to start the
application;

Q3400030 - When using the ASP .NET sample on a remote PC's browser, which port will be accessed:
the one on the ASP .NET Web Server, or the one on the client's PC?

A:

The ASP .NET sample opens the port on the ASP .NET Web Server's machine. This is because
the object is instantiated on the web server. However, it is also possible to use the component on
the client's PC with the browser. You must then create the object from within the client's HTML
code using Javascript. Please check FAQ item 3250020 for details.

[ ACTIVECOMPORT - ASP ]
Q3500005 - How do I use the ActiveComport Toolkit objects in my ASP project?

A:

Please read the following document: Using ActiveComport Toolkit with ASP. This document
describes how to refer to the ActiveComport Toolkit library, and how to declare, create and use
the objects.

Q3500010 - When using the ASP sample on a remote PC's browser, which port will be accessed: the
one on the ASP Web Server, or the one on the client's PC?

A:

The ASP sample opens the port on the ASP Web Server's machine. This is because the object is
instantiated on the web server. However, it is also possible to use the component on the client's
PC with the browser. You must then create the object from within the client's HTML code using
Javascript. Please check FAQ item 3250020 for details.

Q3500015 - In your ASP sample I can't see my Windows' Telephony Devices (for instance, my
'Standard 9600 bps Modem'). In all other samples, they are listed. Please advise.

A:

On the webserver, the IUSR_<computername> credentials are used for all SMS operations. The
IUSR_<computername> is only member of the Guests group by default; it doesn't have
sufficient permissions to query the Windows Telephony Devices. By making the
IUSR_<computername> account member of the Local Administrators group, you will be able to
see all Windows Telephony Devices.

[ ACTIVECOMPORT - DELPHI ]
Q3600010 - How do I use the ActiveComport Toolkit objects in my Delphi project?

A:

Please read the following document: Using ActiveComport Toolkit with Borland Delphi. This
document describes how to refer to the ActiveComport Toolkit library, and how to declare,
create and use the objects.

[ ACTIVECOMPORT - PHP ]
Q3650010 - How do I use the ActiveComport Toolkit objects with PHP?

A:

Please read the following document: Using ActiveComport Toolkit with PHP. This document
describes how to refer to the ActiveComport Toolkit library, and how to declare, create and use
the object.

[ ACTIVECOMPORT - COLDFUSION ]
Q3670010 - How do I use the ActiveComport Toolkit objects with ColdFusion?

A:

Please read the following document: Using ActiveComport Toolkit with ColdFusion. This
document describes how to refer to the ActiveComport Toolkit library, and how to declare,
create and use the object.
[ ACTIVECOMPORT - LICENSING ]
Q3700005 - Where can I find detailed information about licensing?

A:

To learn about the different license options for ActiveComport, click here.

Q3700010 - What happens after the 30 day trial period?

A:

After 30 days of evaluation, you won't be able to call the Open method anymore. If you call this
function, nothing happens and LastError will be set.

Q3700015 - What is a 'Distribution License'?

A:

The 'Distribution License' allows you to 'bundle' the toolkit with your own software. It allows
you to ship the product to an unlimited number of customers for an unlimited period of time.
There are no restrictions in functionality of the software, and includes multiline send and receive.
Click here for more information about the ActiveComport Licensing Scheme.

Once you have obtained a Distribution License, you receive a key that you can use on the target
computers. Click here to read more about how to distribute this key with the core product DLL
on the target computers.

Q3700017 - How to distribute a Distribution License key to target computers?

A:
Once you have obtained a Distribution License, you receive a key that you can use on the target
computers. Click here to read more about how to distribute this key with the core product DLL
on the target computers.

Q3700020 - When I buy a license, do I have to pay for future releases?

A:

ActiveXperts' Maintenance Agreement entitles customers to use ActiveXperts' technical support


services, and to receive all product upgrades, free of charge, during a specified Agreement
duration. The Maintenance Agreement applies to all ActiveXperts products.

After purchase, you get 1 year Maintenance for free

After this free Maintenance period, Licensee may purchase Maintenance. The price for the
Maintenance Agreement is 15% of the price that was payed for the product.

Read our Maintenance Agreement in PDF format.

Q3700030 - Where can I purchase the product?

A:

For detailed sales information, check the Sales webpage.

Q3700035 - I received an activation key. How do I activate the product now?

A:

There are three ways to activate the product:

 By running the Setup program - it will ask for the key;


 By calling the Activate function;
 By entering the key in the registry manually.

A detailed description is provided in the manual, in chapter 'Purchase and Product Activation'.
Q3700050 - How much does a maintenance contract cost?

A:

During the first (1) year after purchase, Maintenance is free. After this free Maintenance year,
Licensee may purchase Maintenance. The price for the Maintenance Agreement is 15% of the
price that was payed for the product.

Customers choose between one-, two- and three years Maintenance Agreement renewal. Please
read the Maintenance Agreement document for more details.

Q3700060 - How long after a maintenance contract has expired can I renew it?

A:

Renewals that come in after the maintenance has expired will be backdated to start from the old
expiry date. Also, you are only able to get Technical Support and Software Maintenance when
your support contract is valid.

Q3700070 - Is it possible to obtain the sourcecode of your product?

A:

No, we do not ship or sell the sourcecode of our products. The only sourcecode that is included
with our products, are the code samples shipped with toolkits or API�s.

[ ACTIVECOMPORT - MISCELLANEOUS ]
Q3800010 - Is ActiveComport thread-safe?

A:
Yes, ActiveComport is 100% thread-safe. It can be used by multiple applications simultaneously,
and each individual application can have multiple simultaneous threads using ActiveComport.
This doesn't mean that COM ports can be shared by different threads; usually this is not possible.

Q3800015 - I want to send a sequence of non-displayable data to the comport. How can I do this?

A:

Use the 'WriteByte' function. It sends one byte of data to the comport. Usually, you call
'WriteString "ATZ"' to initialize a modem. You can also use the following commands to
accomplish this:

obj.WriteByte 97
obj.WriteByte 116
obj.WriteByte 122
obj.WriteByte 13 ' 13 means: vbCr, the carriage character

Q3800020 - In the documentation it says that it supports simultaneous writes to multiple com ports,
but I cannot find this in any example?

A:

Basically this is how it works (illustrated by a VBScript sample):

Set o1 = CreateObject( "ActiveXperts.Comport" )


Set o2 = CreateObject( "ActiveXperts.Comport" )

o1.Device = "COM1"
o1.DeviceSpeed = 19200
o1.Open

o2.Device = "COM2"
o2.DeviceSpeed = 19200
o2.Open
ActiveComport Serial Port Toolkit Manual

© 2010 ActiveXperts Software B.V.  contact@activexperts.com

Table of Contents
 

1. Introduction
2. System Requirements
3. Installation
4. How to use ActiveComport
5. Comport object
6. Error Codes
7. Samples
8. Troubleshooting
9. Purchase and Product Activation
10. Appendix A: License Agreement

1. Introduction
1.1. What is ActiveComport?

Adding serial communications capabilities to an application is never a simple matter. It requires


specialized knowledge that might be outside an individual programmer's expertise. For years,
VBScript, Visual Basic and Visual C++ developers have relied upon the power, flexibility and
reliability of the ActiveComport serial communications control from ActiveXperts Software.
And today, also .NET developers use this control.

ActiveComport is a COM component, that provides an easy-to-use scripting interface for serial,
asynchronous communications through a serial port. ActiveComport can control modems, ISDN
modems, USB serial devices and other devices and machines that have a serial interface.

Use ActiveComport for different purposes:

 To control manufacturing machines via the serial port;


 To configure network devices (like print-servers, routers) via the serial port;
 To control a modem, connected to the serial/USB port or Bluetooth;
 To send SMS messages to a mobile telephone using a GSM SmartPhone/Modem connected to
the PC (serial/USB port or Bluetooth);
 To transfer files through a null modem cable;
 Any other scenario where serial communications is involved.
ActiveComport features the following:

 Direct COM ports supported (like 'COM2');


 Windows Telephony Devices supported (like 'Standard 9600 bps Modem');
 Support for RS-232, RS422 and RS485;
 Up to 256 ports opened simultaneously;
 Thread-safe to allow the toolkit in multi-threading environments (multi-threading samples
included);
 Support for Hayes compatible modems, connected via a serial port, USB or Bluetooth;
 Support for GSM/GPRS modems (serial port, USB or Bluetooth);
 Support for Virtual COM ports (i.e. COM ports redirected through the network);
 Hardware flow control (RTS/CTS, DTR/DSR);
 Software flowcontrol (XON/XOFF);
 Support for any baudrate;
 Ability to set baudrates, parity, stopbits;
 Full buffered data transfer;
 Text and Binary data transfer;
 Advanced logging.

ActiveComport includes samples for many development tools, including:

 Visual Basic .NET - Windows .NET based application;


 Visual C# .NET - Windows .NET based applications;
 Visual Basic 5.x or higher - Windows based applications;
 Visual C++ 5.x or higher - Windows based applications;
 ASP .NET - Web site based on Active Server Pages and the .NET Framework;
 ASP 2.x - Web site based on Active Server Pages (server-side scripting);
 PHP - Embedded HTML scripting;
 VBScript - Windows based scripts;
 Java/Javascript - Java based scripts;
 HTML - Client scripts within HTML pages;
 Any other development platform that supports ActiveX/COM components.

1.2. ActiveComport Architecture

ActiveComport is built on top of the Microsoft serial device drivers. It just uses these drivers. It
neither replaces them, nor does it install any additional serial device drivers.

The core of ActiveComport is an ActiveX/COM component that comes in a 32-bit and a 64-bit
version:

 AComport.dll - the 'ActiveComport COM Component' for 32-bit platforms;


 AComportx64.dll - the 'ActiveComport COM Component' for 64-bit platforms;
ActiveComport can be distributed easily to many PC's. Once you have purchased the licenses,
you copy the AComport.dll (or AComportx64.dll) to the PCs and register the DLL on that PC.

2. System Requirements
2.1. ASP .NET, VB .NET, VC# .NET, ASP, VB, Visual C++ and more

The ActiveComport component can be used by any of these development/scripting languages:

 ASP .NET;
 Visual Basic .NET;
 Visual C# .NET;
 ASP 2.x
 VBScript;
 HTML - Client scripts within HTML pages - requires Internet Explorer 4.x or higher;
 Visual Basic 5.x/6.x;
 Visual C++ 5.x/6.x.

2.2. .NET Framework

To use ActiveComport in an ASP .NET, Visual Basic .NET or Visual C#. NET environment, the
.NET Framework must be installed on the system. The .NET Framework is part of Windows
2003 server platforms and higher, and on Windows Vista workstation platforms and higher. For
other Windows platforms, it's available as a separate installation. Please visit the Technology
Information for the .NET Framework page to download the .NET Framework.

2.3. Internet Information Server

Internet Information Server (IIS) Setup installs the Visual Basic Script and Java Script engines.
To run ASP pages on NT4 Servers, IIS 4.x must be installed. IIS 4.x ships with the NT4 Option
Pack CD's.
To run ASP pages on Windows 2000 Servers, IIS 5.x must be installed. IIS is part of the
Windows 2000 Operating System.

2.4. Internet Explorer 4.x or higher

The Internet Explorer 4.x Setup (or higher) installs the Visual Basic Script and Java Script
engines. You can use the ActiveComport component from within the client HTML code.

2.5. Windows Scripting Host

ActiveComport can be used in VBScript scripts. VBScripts can be used by passing the script-file
as a parameter to the scripting host ( either 'cscript' or 'wscript').
WSH relies on the Visual Basic Script and Java Script engines provided with Internet Explorer
4.x or later. WSH is also installed as part of Windows 98, Windows 2000, and Internet
Information Services 4.0. A separate setup program is provided for Windows 95.
2.6. Visual Basic

ActiveComport can be used in Visual Basic 5.x or higher.

2.7. Visual C++

ActiveComport can be used in Visual C++ 5.x or higher.

3. Installation
The ActiveComport package consists of 3 components; any combination of components can be
installed:

 The ActiveComport COM component - the interface to COM compliant applications;


 The ActiveComport Help Files - documentation;
 The ActiveComport Example Files - examples.

3.1. Installation on a single computer

Simply run the AComport.exe Setup program. The InstallShield wizard will guide you through
the rest of the setup.
If you choose the ActiveComport COM component, the Setup program can perform the
registration of the COM component for you. But it will also give you the opportunity to register
the object yourself.

Any subsequent installation of ActiveComport can be performed either manually or by using the
Setup program.

3.2. Installation on multiple computers

Any subsequent installations can be performed using the setup program.


But since the installation of the core components is very simple, you may want to do it manually,
or integrate it into your companies software distribution program.

If you choose to install the COM component manually on other machines, simply perform the
following actions:

 Copy the AComport.dll (for 32-bit platforms) or AComportx64.dll (for 64-bit platforms) to a
destination location on the new machine;
 Register the COM component by using the following command on 32-bit platforms: REGSVR32
<dest-location>\AComport.dll
 Register the COM component by using the following command on 64-bit platforms: REGSVR32
<dest-location>\AComportx64.dll

4. How to use the ActiveComport object


4.1. Introduction

The following code snippets (VBScript) illustrate how to use ActiveComport.

Initialize a modem using a direct COM port


Set objComport = CreateObject( "ActiveXperts.Comport" ) ' Create a new
Comport instance

objComport.Device = "COM1" ' Use a COM port


directly (no Windows Device Driver)
objComport.BaudRate = 56000 ' Set baudrate
(default value: 9600)
objComport.HardwareFlowControl = asFLOWCONTROL_ENABLE ' Set Hardware Flow
Control (default: On)
objComport.SoftwareFlowControl = asFLOWCONTROL_ENABLE ' Set Software Flow
Control (default: Off)
objComport.Open ' Open the port
Wscript.Echo "Open, result: " & objComport.LastError
If( objComport.LastError <> 0 ) Then
WScript.Quit
End If

objComport.WriteString( "at&f" ) ' Write command


str = objComport.ReadString
WScript.Echo "Received: [" & str & "]" ' Read the response

objComport.Close ' Close the port

Initialize a modem using a Windows Telephony Driver


Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Use the Standard
9600 bps Modem Telephony driver
objComport.Open ' Open the port
Wscript.Echo "Open, result: " & objComport.LastError
If( objComport.LastError <> 0 ) Then
WScript.Quit
End If

objComport.WriteString( "at&f" ) ' Write command


str = objComport.ReadString
WScript.Echo "Received: [" & str & "]" ' Read the response

objComport.Close ' Close the port

Send an SMS using a GSM Modem connected to the PC; Enable logging
Const RECIPIENT = "+31624896641"
Const MESSAGE = "Hello, world!"

Set objComport = CreateObject( "ActiveXperts.Comport" ) ' Create a new


Comport instance

objComport.Device = "Nokia 6680 SmartPhone" ' Use the Stanrd


9600 bps Modem Telephony driver
objComport.LogFile = "C:\ActiveComport.log" ' Enable logging
objComport.Open ' Open the port
Wscript.Echo "Open, result: " & objComport.LastError
If( objComport.LastError <> 0 ) Then
WScript.Quit
End If

WriteStr objComport, "at+cmgs=" & Chr( 34 ) & strNumber & Chr( 34 )


ReadStr objComport
WriteStr objComport, strMessage
strTermCmd = Chr( 26 ) ' Terminate
message: [ctrl]z and then [enter]
WriteStr objComport, strTermCmd
objComport.Sleep 3000 ' It takes a while
before GSM phone responds
ReadStr objComport ' +CMGS: expected
ReadStr objComport ' OK expected
objComport.Close ' Close the port

' ********************************************************************
' Sub Routines
' ********************************************************************
Sub WriteStr( obj, str )
obj.WriteString str
WScript.Echo "-> " & str
End Sub

Sub ReadStr( obj )


str = "notempty"
obj.Sleep 200
Do While str <> ""
str = obj.ReadString
If( str <> "" ) Then
WScript.Echo "<- " & str
End If
Loop
End Sub
' ********************************************************************

4.2. How to use ActiveComport in Visual Basic .NET

First, make sure the ActiveComport component (AComport.dll) is registered on the machine. In
case you didn't use the installation program, be sure you used the REGSVR32.EXE program to
register to component.

Then, add a reference to the ActiveComport component using the Visual Basic .NET Solution
Explorer:

 Start the Solution Provider, go to the project's 'References' container;


 Choose 'Add Reference' from the context menu;
 From the COM components tab, choose the ActiveComport component.

On top of the code, make this declaration:


Imports ACOMPORTLib

and declare and create an object like this:

Dim objComport As ACOMPORTLib.ComPortClass ' Declaration


objComport = New ACOMPORTLib.ComPortClass() ' Creation

After the declaration and creation of the object, you can use the object in your Visual Basic .NET
code.
Visual Basic samples are part of the product installation.
They can also be found online:ftp.activexperts-labs.com/samples/acomport.

4.3. How to use ActiveComport in Visual C# .NET

First, make sure the ActiveComport component (AComport.dll) is registered on the machine. In
case you didn't use the installation program, be sure you used the REGSVR32.EXE program to
register to component.

Then, add a reference to the object using the Visual C# Solution Explorer:

 Start the Solution Provider, go to the project's 'References' container;


 Choose 'Add Reference' from the context menu;
 From the COM components tab, choose the ActiveComport component.

On top of your code, make this declaration:

using ACOMPORTLib;

and declare and create an object like this:

Comport objComport; // Declaration


objComport = new Comport(); // Creation

After the declaration and creation of the object, you can use the object in your Visual C# .NET
code.
Visual C# .NET samples are part of the product installation.
They can also be found online: ftp.activexperts-labs.com/samples/acomport.

4.4. How to use ActiveComportin Visual Basic

ActiveComport can be used in Visual Basic 5.x or higher. In Visual Basic, go to the
'Project/References...' menu item and check the box next to ActiveComport Type Library. Now,
you can declare and create ActiveComport objects.

Create a new ActiveComport object using the 'CreateObject' function:

Dim objComport As ACOMPORTLib.Comport ' Declaration


Set objComport = CreateObject( "ActiveXperts.Comport") ' Creation
After the declaration and creation of the object, you can use the object in your Visual Basic code.
Visual Basic samples are part of the product installation.
They can also be found online: ftp.activexperts-labs.com/samples/acomport.

4.5. How to use ActiveComport in Visual C++

ActiveComport can be used in Visual C++ projects. Include the *.h and *.c file provided by
ActiveXperts to bind your code to the ActiveComport component. These files are located in the
Include directory of the Visual C++ samples directory. These are the files:

 AComport.h
 AComport_i.c
 AComportConstants.h

Create the various ActiveComport object instances like this:

IComPort *pComPort; // Declaration


CoCreateInstance(CLSID_ComPort, NULL, CLSCTX_INPROC_SERVER, IID_IComPort,
(void**) &pComPort ); // Creation

After the declaration and creation of the object, you can use the object in your Visual C++ code.
Visual C++ samples are part of the product installation.
They can also be found online: ftp.activexperts-labs.com/samples/acomport.

4.6. How to use ActiveComport in an ASP 2.x environment


<html>
<body>
Version:
<script language=vbscript runat=server>
Set objComport = CreateObject( "ActiveXperts.Comport" )
Response.Write objComport.Version
</script>
</body>
</html>

ASP samples are part of the product installation.


They can also be found online: ftp.activexperts-labs.com/samples/acomport.

5. Comport Object
5.1. Comport object - Properties and Functions Overview
Property Type In/Out Mand/Opt Description

Version String Out n/a Version number of ActiveComport

Build String Out n/a Build number of ActiveComport

ExpirationDate String Out n/a Expiration date of ActiveComport


Property Type In/Out Mand/Opt Description

LastError Number In/Out n/a Result of the last called function

Device name. Either a direct COM port or a Windows


Device String In/Out M
Telephony device name

The baudrate of the communication session; default:


BaudRate Number In/Out O
9600 bps

Databits Number In/Out O The number of databits; default: 8

Stopbits Number In/Out O The number of stopbits; default: 1

Parity Boolean In/Out O Parity; default: False

HardwareFlowControl Number In/Out O Use Hardware Flow Control

Use advanced Hardware Flow Control flag: Data


DTRFlowControl Boolean In/Out O
Terminal Ready (default: True)

Use advanced Hardware Flow Control flag: Request To


RTSFlowControl Boolean In/Out O
Send; default: True

Use advanced Hardware Flow Control flag: Clear To


CTSFlowControl Boolean In/Out O
Send; default: False

Use advanced Hardware Flow Control flag: DSR (Data


DSRFlowControl Boolean In/Out O
Set Ready); default: False

SoftwareFlowControl Number In/Out O Use Software Flow Control

Timeout of ReadString, ReadByte and ReadBytes


ComTimeout Number In/Out O
functions, in millisec; default: 1000 msecs

IsOpened Boolean Out n/a True if port is opened, otherwise False

Pre command delay, in milliseconds. Only used with


PreCommandDelay Number In/Out O
the WriteString function

Delay between each character sent, in milliseconds.


InterCharDelay Number In/Out O
Only used with the WriteString function

NewLine String In/Out O The character sequence that forms a newline

All serial port commands, as well as data transfer, is


LogFile String InOut O
logged to this file
Function Description

Clear Reset all properties to the default values

GetDeviceCount Return the number of Windows telephony devices installed on the local computer

GetDevice Retrieve a Windows telephony device name

Open Open a comport

Close Close a comport

ClearTX Clears the output buffer

ClearRX Clears the input buffer

ReadString Read an ASCII string from the comport

ReadByte Read a (binary) byte from the comport

ReadBytes Read a stream of (binary) bytes from the comport

WriteString Write an ASCII string to the comport

WriteByte Write a (binary) byte to the comport

WriteBytes Write a stream of (binary) bytes to the comport

UpdateCom Update the comport with new configuration settings

RaiseRTS Raise the RTS signal

RaiseDTR Raise the DTR signal

QueryCTS Query the CTS signal

QueryDSR Query the DSR signal

QueryDCD Query the DCD signal

QueryRI Query the RI signal

Sleep Be idle for some time

GetErrorDescription Get error description

Activate Activate the product


5.2. Comport object - Properties

Comport.Version property

Description:

Version information of ActiveComport. This property is read-only; you cannot assign a value to
it.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
WScript.Echo "Version: " & objComport.Version

Comport.Build property

Description:

Build information of ActiveComport. This property is read-only; you cannot assign a value to it.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
WScript.Echo "Version: " & objComport.Version
WScript.Echo "Build: " & objComport.Build

Comport.ExpirationDate property

Description:

Expiration date of ActiveComport. This property is read-only; you cannot assign a value to it.
Once you have registered the product, the property holds the empty string ("") value.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
WScript.Echo "ExpirationDate: " & objComport.ExpirationDate

Comport.LastError property

Description:

The result of a previous called function. Use it to check the result of your last function call. A
zero indicates: success. Any non-zero value means an error.
The GetErrorDescription function provides the error description of an error code.
For a complete list of error codes, check out the following page:
www.activexperts.com/support/errorcodes.
Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
...
objComport.Open ' Open the port
WScript.Echo "LastError: " & objSnmp.LastError ' Display the
result
...

Comport.Device property

Description:

Device driver to use.


You can either use a Windows telephony device (recommended) or a physical COM port
(directly).

Assign one of the following strings to the 'Device' property:

 A valid Windows telephony device name - this must be the literal name as it appears in Modems
tab of the Phone and Modems Options applet in the Control Panel. For instance: "Standard 9600
bps Modem";
Use the GetDevice function to retrieve Windows telephony device names;
 A valid COM port string, formatted as COMx, where x is a valid COM port number. When you
assign the 'Device' property with a COM port string, you bypass all Windows telephony
intelligence, like dialing rules, port sharing and so on.

Windows telephony devices are highly recommended.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 19200 bps Modem"' Use a Windows
telephony device (recommended)
...

Comport.BaudRate property

Description:

Baud rate at which the communications device operates. The default value is 0, which means that
the baud rate setting is inherited from the Port/Device settings in the Control Panel of Windows.
You should use the UpdateCom function if you want to change the baudrate and the port is
already opened.
This property can be one of the following values:

 0 (Default - inherit baud rate from the device settings as defined in the Control Panel)
 110
 300
 600
 1200
 2400
 4800
 9600
 14400
 19200
 38400
 56000
 57600
 115200
 128000
 230400
 256000
 460800
 921800

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.BaudRate = 38400 ' Use 38400 bps
objComport.Open
...

Comport.DataBits property

Description:

Number of databits in a byte. The default value is asDATABITS_DEFAULT, which means that
the data bits setting is inherited from the Port/Device settings in the Control Panel of Windows.
You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.DataBits = objComport.asDATABITS_7 ' Use 7 bit data
bits
objComport.Open
...

Comport.StopBits property

Description:

You can configure StopBits to be asSTOPBITS_DEFAULT, asSTOPBITS_1, asSTOPBITS_2


or asSTOPBITS_15.
If StopBits is asSTOPBITS_1, one stop bit is used to indicate the end of data transmission.
If StopBits is asSTOPBITS_2, two stop bits are used to indicate the end of data transmission.
If StopBits is asSTOPBITS_15, the stop bit is transferred for 150% of the normal time used to
transfer one bit.

The default value is asSTOPBITS_DEFAULT, which means that the stop bits setting is inherited
from the Port/Device settings in the Control Panel of Windows.

You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.StopBits = objComport.asSTOPBITS_15 ' Use 1.5 stop bits
objComport.Open
...

Comport.Parity property

Description:

Parity checking can detect errors of one bit only. An error in two bits might cause the data to
have a seemingly valid parity, when in fact it is incorrect.

You can configure Parity to be none, odd, even, mark, or space.


If Parity is asPARITY_DEFAULT, the parity setting is inherited from the Port/Device settings in
the Control Panel of Windows.
If Parity is asPARITY_NONE (=none), parity checking is not performed and the parity bit is not
transmitted.
If Parity is asPARITY_ODD (=odd), the number of mark bits (1's) in the data is counted, and the
parity bit is asserted or unasserted to obtain an odd number of mark bits.
If Parity is asPARITY_EVEN (=even), the number of mark bits in the data is counted, and the
parity bit is asserted or unasserted to obtain an even number of mark bits.
If Parity is asPARITY_MARK (=mark), the parity bit is asserted.
If Parity is asPARITY_SPACE (=space), the parity bit is unasserted.

The default value is asPARITY_DEFAULT.

You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.Parity = objComport.asPARITY_NONE ' No parity
objComport.Open
...

Comport.HardwareFlowControl property

Descripton:

Use Hardware Flow Control. The default value is asFLOWCONTROL_DEFAULT, which


means that the hardware flow control settings are inherited from the Port/Device settings in the
Control Panel of Windows.

This property sets the generic hardware flow control control properties.

When you set 'HardwareFlowControl' to asFLOWCONTROL_ENABLE:

 DTRFlowControl and RTSFlowControl are both set to asFLOWCONTROL_ENABLE


 CTSFlowControl and DSRFlowControl are both set to asFLOWCONTROL_DISABLE

When you set 'HardwareFlowControl' to asFLOWCONTROL_DISABLE:

 DTRFlowControl and RTSFlowControl are both set to asFLOWCONTROL_DISABLE


 CTSFlowControl and DSRFlowControl are both set to asFLOWCONTROL_DISABLE

In most circumstances, it is not necessary to assign DTRFlowControl, RTSFlowControl,


CTSFlowControl or DSRFlowControl individually. However, in some situations you want need
to assign these properties individually.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.HardwareFlowControl = objComport.asFLOWCONTROL_DISABLE ' No
hardware flow control
objComport.Open
...

Comport.DTRFlowControl property

Descripton:

Advanced Hardware Flow Control. Usually, the HardwareFlowControl property will suffice: it
sets all four advanced hardware flow control flags (DTRFlowControl, RTSFlowControl,
CTSFlowControl, DSRFlowControl).
The default value is asFLOWCONTROL_DEFAULT, which means that the DTR flow control
settings are inherited from the Port/Device settings in the Control Panel of Windows.

You cannot change the value when the port is already opened.
Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.DTRFlowControl = objComport.asFLOWCONTROL_DISABLE ' No DTR
hardware flow control
objComport.Open
...

Comport.RTSFlowControl property

Description:

Advanced Hardware Flow Control. Usually, the HardwareFlowControl property will suffice: it
sets all four advanced hardware flow control flags (DTRFlowControl, RTSFlowControl,
CTSFlowControl, DSRFlowControl).
The default value is asFLOWCONTROL_DEFAULT, which means that the RTS flow control
settings are inherited from the Port/Device settings in the Control Panel of Windows.

You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.RTSFlowControl = objComport.asFLOWCONTROL_DISABLE ' No RTS
objComport.Open
...

Comport.CTSFlowControl property

Description:

Advanced Hardware Flow Control. Usually, the HardwareFlowControl property will suffice: it
sets all four advanced hardware flow control flags (DTRFlowControl, RTSFlowControl,
CTSFlowControl, DSRFlowControl).
The default value is asFLOWCONTROL_DEFAULT, which means that the CTS flow control
settings are inherited from the Port/Device settings in the Control Panel of Windows.

You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.CTSFlowControl = objComport.asFLOWCONTROL_DISABLE ' No CTS
hardware flow control
objComport.Open
...

Comport.DSRFlowControl property

Description:

Advanced Hardware Flow Control. Usually, the HardwareFlowControl property will suffice: it
sets all four advanced hardware flow control flags (DTRFlowControl, RTSFlowControl,
CTSFlowControl, DSRFlowControl).
The default value is asFLOWCONTROL_DEFAULT, which means that the DSR flow control
settings are inherited from the Port/Device settings in the Control Panel of Windows.

You cannot change the value when the port is already opened.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.DSRFlowControl = objComport.asFLOWCONTROL_DISABLE ' No DSR
hardware flow control
objComport.Open
...

Comport.SoftwareFlowControl property

Description:

Software flow control. You should use the UpdateCom function if you want to change the
baudrate after you have opened the port.
The default value is asFLOWCONTROL_DEFAULT, which means that the software flow
control settings are inherited from the Port/Device settings in the Control Panel of Windows. The
other valid values are: asFLOWCONTROL_DISABLE and asFLOWCONTROL_ENABLE.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "COM2" ' Set device to
COM2
objComport.SoftwareFlowControl = objComport.asFLOWCONTROL_ENABLE ' Use
software flow control
objComport.Open
...

Comport.ComTimeout property

Description:

Timeout of ReadString function, in milliseconds. You can call this function anytime you want.
The default value is 1000.
Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600bps Modem" ' Set device to
Standard 9600 bps Modem
str = objComport.ReadString ' Blocks until
string is read or 1 sec is elapsed
WScript.Echo str
objComport.ComTimeout = 5000 ' Set timeout to
5000 msecs
str = objComport.ReadString ' Blocks until
string is read or 5 sec is elapsed
WScript.Echo str
objComport.Close ' Close port
...

Comport.IsOpened property

Description:

True if port is opened, otherwise False.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
If( objComport.IsOpened ) Then
WScript.Echo "Port is opened"
objComport.Close ' Close port
End If

Comport.PreCommandDelay property

Description:

Specifies a delay (in milliseconds) used before WriteString actually starts writing the command
string. This property was introduced to support slow devices that do not accept a few commands
right after eachother. These devices need a small delay between commands, which can be
accomplished by setting this 'PreCommandDelay' property.
Note that the property does NOT apply to the WriteBytes and WriteByte functions.
Default value: 0, indicating no delay between commands.

Example:

Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new


Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
objComport.PreCommandDelay = 500 ' WriteString will
use a delay of 500 msecs
' before the
command string is sent
objComport.InterCharDelay = 10 ' A delay of 10
milliseconds between each character
' Transmitted by
the WriteString function
...
objComport.WriteString "AT&F"
...
objComport.Close ' Close the port
End If

Comport.InterCharDelay property

Description:

Specifies a delay (in milliseconds) used in WriteString between each character transmitted. This
property was introduced to support slow devices that do not allow each character tranmitted right
after eachother in command mode. These devices need a small delay between characters, which
can be accomplished by setting this 'InterCharDelay' property.
Note that the property does NOT apply to the WriteBytes function.
Default value: 0, indicating no delay between characters.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
objComport.PreCommandDelay = 500 ' WriteString will
use a delay of 500 msecs
' before the
command string is sent
...
objComport.InterCharDelay = 10 ' Delay of 10
milliseconds between each character
' transmitted by
the WriteString function
objComport.WriteString "AT&F"
...
objComport.Close ' Close the port
End If

 Comport.NewLine property

Description:

The character sequence that forms a newline. Default value: the CR (carriage return) string. Most
frequent used newline strings:
 CR (carriage return) - a string containing only the ASCII-13 character (in C: "\r"; in VB: vbCr )
 LF (linefeed) - a string containing only the ASCII-10 character (in C: "\n"; in VB: vbLf )
 CRLF (carriage return / linefeed) - a string containing the ASCII-13, ASCII-10 sequence (in C:
"\r\n"; in VB: vbCrLf )

A newline is used internally by two functions:

 ReadString - bytes are read from the port until a newline is detected;
 WriteString - bytes are written to the port. Finally a newline is sent.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
objComport.NewLine = vbCrLf ' Use CRLF in the
subsequent ReadBytes/WriteBytes calls
' transmitted by
the WriteString function
objComport.WriteString "AT&F" ' AT&F is sent,
followed by a CRLF
...
objComport.Close ' Close the port
End If

Comport.LogFile property

Description:

By default, LogFile holds the empty string and nothing is logged. If you assign a valid file name
to it, all device commands and responses will be written to this log file.
Output is always appended.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.LogFile = "C:\MyLogFile.txt" ' All operations
are logged here
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Open the port
...
5.3. Comport object - Functions

Comport.Clear function

Description:

Reset all properties to their initial values.

Parameters:

None.

Return value:

Always 0.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open
...
objComport.Close
objComport.Clear ' Clear all
properties
objComport.Device = "COM1" ' Set device to
COM1:
objComport.Open
...

Comport.GetDeviceCount function

Description:

Returns the number of installed Windows telephony devices on the local computer.

Parameters:

 None

Return value:

The number of installed Windows telephony devices. Check the LastError property to see if the
function was completed successfully.

NOTE: The number of Windows telephony devices does not include the number installed COM
ports.
Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new Comport
instance
WScript.Echo "Number of installed Windows telephony devices: " &
objComport.GetDeviceCount()

Comport.GetDevice function

Description:

Returns the n-th telephony device of the system. The number n can be between 0 and
GetDeviceCount()-1.

Parameters:

 Zero based index, to iterate over all telephony devices.

Return value:

The name of the device. Call the LastError function to see if the function was completed
successfully.
The name of the device can be assigned to the Device property to open a Windows telephony
device.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
n = objComport.GetDeviceCount()
For i = 0 to n-1
WScript.Echo "Device " & i & ": " & objComport.GetDevice( i )
Next

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
If( objComport.GetDeviceCount() > 0 )
objComport.Device = objComport.GetDevice( 0 ) ' Use the first telephony
device
objComport.WriteByte 32
End If

Comport.Open function

Description:

Open the comport. The Device indicates to port to open.

Parameters:

None.
Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new Comport
instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
...

Comport.Close function

Description:

Close the COM port.

Parameters:

None.

Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
...
objComport.Close ' Close the port
End If

Comport.ClearTX function

Description:

Clears the output buffer (if the device or UART has one).

Parameters:

None.
Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
COM2
objComport.Open ' Now open the
Standard 9600 bps Modem
If( objComport.LastError = 0 ) Then
...
objComport.ClearTX ' Clear
transmission queue
objComport.WriteString "AT&F"
...
objComport.Close ' Close the port
End If

Comport.ClearRX function

Description:

Clears the input buffer (if the device or UART has one).

Parameters:

None.

Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
...
objComport.ClearTX ' Clear
transmission queue
objComport.ClearRX ' Clear
transmission queue
...
objComport.WriteString "AT&F"
WScript.Echo objComport.ReadString ' Read incoming
data
...
objComport.Close ' Close the port
End If

Comport.WriteString function

Description:

This function sends a string of ASCII data to the device. Finally NewLine is sent to the device.

Parameters:

 ASCII string to send

Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new
Comport instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
...
objComport.WriteString "AT&F"
...
objComport.Close ' Close the port
End If

Comport.WriteByte function

Description:

This function sends a (binary) byte to the device.

Parameters:

 One byte

Return value:

Always 0. Check LastError property to see if the function was completed successfully.

Example:
Set objComport = CreateObject("ActiveXperts.Comport") ' Create a new Comport
instance
objComport.Device = "Standard 9600 bps Modem" ' Set device to
Standard 9600 bps Modem
objComport.Open ' Now open the port
If( objComport.LastError = 0 ) Then
...
objComport.WriteByte 97 ' [A]
objComport.WriteByte 116 ' [T]
objComport.WriteByte 122 ' [Z]
objComport.WriteByte 13

Vous aimerez peut-être aussi