Saturday, March 6, 2010

COM Port Connection Automation - Python and CSharp

Many control and measurement devices support RS232 serial interface for communication what easily allows automation. It is pretty convenient when software can find out on its own what device is connected to what COM port. It is the case especially when the port is not a physical one with a fixed number, but a virtual representation in system and its number may change from one connection to another. Some of Fluke and Agilent multimeters, Arroyo temperature controllers and many other devices using similar to USB FTDI chips connection approach can be examples of that.

Finding a COM port device automatically can be done in the two following steps:
  1. Find all available COM ports in system. In Python it can be a function like this:
    import serial

    def COMportScan():
    """scans for available COM ports."""
    availableCOMports = []
    for i in range(256):
    try:
    COMport = serial.Serial(i)
    availableCOMports.append(COMport.portstr)
    COMport.close()
    except serial.SerialException:
    pass
    return availableCOMports

    The same thing in C Sharp:
    using System.IO.Ports;

    string[] availableCOMports;
    availableCOMports = SerialPort.GetPortNames();

  2. Among the available ports find the port which is connected to a particular device. Any device interface command with predictable response can be used for that, for example, for Fluke 189 DMM it can be Identification "ID" command:

    With Python a solution can look like this:
    def ReadDataString(self):
    strData = ''
    cycles = 0
    char = self.comport.read()
    while (char != chr(13) and cycles < 100):
    strData = strData + char
    char = self.comport.read()
    cycles += 1
    return strData

    def readFlukeID(self):
    strFlukeID = ''

    self.comport.write("ID" + chr(13))
    char = self.comport.read() # Read out '0'
    char = self.comport.read() # Read out chr(13)
    self.m_strFlukeID = self.ReadDataString()
    return self.m_strFlukeID

    Similarly with C# :
    public string ReadDataString()
    {
    string strData = "";
    int cycles = 0;
    char[] ch = new char[1];

    try
    {
    COMPort.Read(ch, 0, 1);

    while ((ch != '\r') && (cycles < 100))
    {
    strData += ch;
    COMPort.Read(ch, 0, 1);
    cycles += 1;
    }
    }
    catch (TimeoutException) { }

    return strData;
    }

    public string ReadFlukeID()
    {
    string strFlukeID = "";
    COMPort.WriteLine("ID\r");
    COMPort.Read(ch, 0, 1); // Read out '0';
    COMPort.Read(ch, 0, 1); // Read out chr(13);
    strFlukeID = ReadDataString();
    return strFlukeID;
    }

0 comments:

Post a Comment