Finding a COM port device automatically can be done in the two following steps:
- 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(); - 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