以往我的做法是”COM”+數字(1~16)

然後再去跑回圈測試可能的串列埠, snipet code like this[1]:

using System.IO.Ports;
 
private SerialPort sp;
 
for (int i = 1; i <= 16; i++)
{
      try
      {
           sp = new SerialPort("COM" + i.ToString(), baud, parity, databits, stopbits);
           sp.Open();
           if(sp.IsOpen){
               this.Label1.Text += ("COM"+i.ToString()+" is available.\n");
           }
       }
       catch (Exception)  //開埠不成功就會到這來
       {
        // 執行開埠不成功的處理
       }
       finally {
            sp.Close();
       }
}

後來發現其實有更好的做法

1. 直接抓本機器硬體裝置清單中的串列埠, 忽略一些不可能的串列埠

2. 掃秒每一個硬體串列埠清單, 測試方法如上面的snipet code

image

取得體裝置清單中的全部串列埠 

private Array myport;        

this.myport = SerialPort.GetPortNames();

或是放在字串陣列[2]

// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
 
Console.WriteLine("The following serial ports were found:");
 
// Display each port name to the console.
foreach(string port in ports)
{
    Console.WriteLine(port);
}

=======================================================

SerialPort.DtrEnable 屬性


在序列通訊期間啟用 Data Terminal Ready (DTR) 信號[5]: 

Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

白話地說就是通知儀器說我(電腦)這邊已經準備好了

在網路上找了許多C# 串列埠的範例, 但都沒有提到這個重要屬性,

這個屬性會讓你的電腦無法和某些儀器溝通, 即使你的其他SerialPort屬性都設定正確,

關於DTR這一個屬性, 我吃過一次虧到昨天才恍然大悟,

一年多前 Arduino RS232 模擬儀器輸出訊號,

那時候是用C# serial port和 arduino做通訊, 當時並未打開DtrEnable卻可以正常通訊,

可是當我改接到客戶儀器卻失敗了, 於是改用BCB重新改寫卻又意外可以,

現在想想應該是BCB預設有提供DTR Enable, 而C#預設DTR是Enable = false

真….是….冏… 啊!
















參考資料:

1. C# 掃描COM Port是否可用

2. SerialPort.GetPortNames 方法 ()

3. SerialPort.DtrEnable 屬性

4. Arduino RS232 模擬儀器輸出訊號

5. Data Terminal Ready

全站熱搜
創作者介紹
創作者 me1237guy 的頭像
me1237guy

天天向上

me1237guy 發表在 痞客邦 留言(0) 人氣()