2010-07-20 12 views
17

मैं एक सी # आवेदन करने के लिए संचार के लिए Firmata पुस्तकालय के साथ एक Arduino का उपयोग कर रहा है, और मैं एक COM पोर्ट विन्यास घटक को खत्म करने के बाद से यह मशीन से मशीन को बदल सकते हैं ...Arduino COM पोर्ट को स्वतः कैसे पहचानें?

क्या यह संभव है करने के लिए:

  1. सिस्टम में COM बंदरगाहों की संख्यात्मक सूची? (मेरे गुगल में मैंने कुछ काफी बदसूरत Win32 एपीआई कोड देखा है, उम्मीद है कि अब शायद एक क्लीनर संस्करण हो सकता है)
  2. स्वतः पता लगाएं कि कौन सी COM पोर्ट Arduino से जुड़े हुए हैं?

उत्तर

14

कोड का यह छोटा सा इस के लिए बहुत अच्छा प्रदर्शन किया है (रिटर्न COM पोर्ट स्ट्रिंग, यानी "COM12" अगर Arduino का पता चला है):

private string AutodetectArduinoPort() 
     { 
      ManagementScope connectionScope = new ManagementScope(); 
      SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort"); 
      ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery); 

      try 
      { 
       foreach (ManagementObject item in searcher.Get()) 
       { 
        string desc = item["Description"].ToString(); 
        string deviceId = item["DeviceID"].ToString(); 

        if (desc.Contains("Arduino")) 
        { 
         return deviceId; 
        } 
       } 
      } 
      catch (ManagementException e) 
      { 
       /* Do Nothing */ 
      } 

      return null; 
     } 
+0

मैंने इस कोड को आजमाया है और यह मेरी मशीन पर कुछ भी नहीं लगता है। उस समय मेरे पास एक देखा गया था। – cmroanirgo

+0

@cmroanirgo यह डिवाइस मैनेजर में क्या दिखाता है? – Brandon

+2

यह "यूएसबी सीरियल पोर्ट" के रूप में दिखाता है (और एक डेसिमिला भी इसका जवाब देता है)। मेरे लिए, एकमात्र असली समाधान प्रत्येक COM पोर्ट को खोलना था, एक जादू बाइट भेजना और जादू प्रतिक्रिया के लिए सुनना था, जैसे अन्य उत्तरों सुझाव देते हैं। – cmroanirgo

9
  1. आप SerialPort.GetPortNames() का उपयोग स्ट्रिंग COM पोर्ट नाम की एक सरणी वापस जाने के लिए कर सकते हैं।
  2. मुझे नहीं लगता कि आप बंदरगाहों का पता लगा सकते हैं, डिवाइस को कनेक्ट करने के लिए आपको डिवाइस को पिंग करना होगा।
+1

मैं बंदरगाहों खोलने और एक कमांड भेजने/प्रतिक्रिया के लिए सुनने के साथ ठीक हूँ ... बस अगर वहाँ एक करने के लिए पता नहीं है सर्वोत्तम अभ्यास "पी आईएनजी "कि एक Arduino का जवाब होगा .. और यह भी पता लगाएं कि बंदरगाह पहले से ही किसी अन्य चीज़ द्वारा उपयोग में है, आदि – Brandon

+2

यह (http://stackoverflow.com/questions/195483/c-check-if-a- कॉम-सीरियल-पोर्ट-पहले से ही खुला है) एक बंदरगाह उपयोग में है या नहीं, यह जानने के बारे में पोस्ट वार्ता। असल में आपको उन्हें आजमाने और खोलने की जरूरत है। यदि आपको अपवाद मिलता है, तो शायद इसका उपयोग किया जा सकता है। यदि यह ठीक खुलता है, तो आप यह सत्यापित करने के लिए IsOpen संपत्ति की जांच कर सकते हैं कि यह जुड़ा हुआ है। मुझे Arduino बोर्ड से सबसे छोटा संदेश या संशोधन प्रतिक्रिया संदेश मिलेगा ताकि यह सत्यापित किया जा सके कि आप वास्तव में बोर्ड से जुड़े हैं और कुछ अन्य डिवाइस नहीं हैं। – SwDevMan81

1

इस प्रयास करें, मैं एक पर काम कर रहा हूँ बहुत ही समान परियोजना, कोई भी इसे संपादित करने के लिए स्वतंत्र महसूस करें!

Arduino कोड के सेटअप हिस्से में, मैंने इसे सेटअप कॉमम्स() विधि कहा है, यह विधि केवल "ए" को प्रिंट करने तक "ए" प्रिंट करती है। एक बार "ए" प्राप्त हो जाने पर यह मुख्य पाश() फ़ंक्शन पर कूद जाता है। तो सी # भाग "ए" के लिए प्रत्येक उपलब्ध बंदरगाह की जांच करता है और यदि "ए" पाया जाता है तो हम जानते हैं कि हमने बंदरगाह को Arduino में खोला है!

फिर से, यह बहुत साफ नहीं हो सकता है लेकिन यह काम करता है, मैं किसी भी टिप्पणी और सुझाव के लिए खुला हूं!

foreach (string s in SerialPort.GetPortNames()) 
     { 
      com.Close(); // To handle the exception, in case the port isn't found and then they try again... 

      bool portfound = false; 
       com.PortName = s; 
       com.BaudRate = 38400; 
       try 
       { 
        com.Open(); 
        status.Clear(); 
        status.Text += "Trying port: " + s+"\r"; 
       } 
       catch (IOException c) 
       { 
        status.Clear(); 
        status.Text += "Invalid Port"+"\r"; 
        return; 
       } 
       catch (InvalidOperationException c1) 
       { 

        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       catch (ArgumentNullException c2) 
       { 
        // System.Windows.Forms.MessageBox.Show("Sorry, Exception Occured - " + c2); 
        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       catch (TimeoutException c3) 
       { 
        // System.Windows.Forms.MessageBox.Show("Sorry, Exception Occured - " + c3); 
        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       catch (UnauthorizedAccessException c4) 
       { 
        //System.Windows.Forms.MessageBox.Show("Sorry, Exception Occured - " + c); 
        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       catch (ArgumentOutOfRangeException c5) 
       { 
        //System.Windows.Forms.MessageBox.Show("Sorry, Exception Occured - " + c5); 
        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       catch (ArgumentException c2) 
       { 
        //System.Windows.Forms.MessageBox.Show("Sorry, Exception Occured - " + c2); 
        status.Clear(); 
        status.Text += "Invalid Port" + "\r"; 
        return; 
       } 
       if (!portfound) 
       { 
        if (com.IsOpen) // Port has been opened properly... 
        { 
         com.ReadTimeout = 500; // 500 millisecond timeout... 
         sent.Text += "Attemption to open port " + com.PortName + "\r"; 
         try 
         { 
          sent.Text += "Waiting for a response from controller: " + com.PortName + "\r"; 
          string comms = com.ReadLine(); 
          sent.Text += "Reading From Port " + com.PortName+"\r"; 
          if (comms.Substring(0,1) == "A") // We have found the arduino! 
          { 
           status.Clear(); 
           status.Text += s + com.PortName+" Opened Successfully!" + "\r"; 
           //com.Write("a"); // Sends 0x74 to the arduino letting it know that we are connected! 
           com.ReadTimeout = 200; 
           com.Write("a"); 
           sent.Text += "Port " + com.PortName + " Opened Successfully!"+"\r"; 
           brbox.Text += com.BaudRate; 
           comboBox1.Text = com.PortName; 

          } 
          else 
          { 
           sent.Text += "Port Not Found! Please cycle controller power and try again" + "\r"; 
           com.Close();  
          } 
         } 
         catch (Exception e1) 
         { 
          status.Clear(); 
          status.Text += "Incorrect Port! Trying again..."; 
          com.Close(); 
         } 
        } 
       } 
     } 

जब मैं मूल रूप से परीक्षण कर रहा था तब से सभी प्रयास कैच स्टेटमेंट वहां से हैं, इसने मेरे लिए अब तक काम किया है। सौभाग्य!

5

डब्लूएमआई प्रबंधन मार्ग को थोड़ा आगे लेते हुए, मैं एक रैपर वर्ग के साथ आया हूं जो Win32_SerialPorts घटनाओं पर हुक करता है और गतिशील रूप से Arduino और Digi International (X-Bee) उपकरणों के लिए सीरियल पोर्ट्स की एक सूची पॉप्युलेट करता है, पोर्टनाम और BaudRates।

अभी के लिए, मैंने Win32_SerialPorts प्रविष्टि में डिवाइस के लिए कुंजी के रूप में डिवाइस विवरण का उपयोग किया है, लेकिन इसे आसानी से बदला जा सकता है।

यह एक Arduino यूएनओ के साथ सीमित क्षमता के लिए परीक्षण किया गया है और यह स्थिर लगता है।

// ------------------------------------------------------------------------- 
// <copyright file="ArduinoDeviceManager.cs" company="ApacheTech Consultancy"> 
//  Copyright (c) ApacheTech Consultancy. All rights reserved. 
// </copyright> 
// <license type="GNU General Public License" version="3"> 
//  This program is free software: you can redistribute it and/or modify 
//  it under the terms of the GNU General Public License as published by 
//  the Free Software Foundation, either version 3 of the License, or 
//  (at your option) any later version. 
// 
//  This program is distributed in the hope that it will be useful, 
//  but WITHOUT ANY WARRANTY; without even the implied warranty of 
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
//  GNU General Public License for more details. 
// 
//  You should have received a copy of the GNU General Public License 
//  along with this program. If not, see http://www.gnu.org/licenses 
// <license> 
// ------------------------------------------------------------------------- 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Diagnostics; 
using System.IO.Ports; 
using System.Linq; 
using System.Management; 
using System.Runtime.CompilerServices; 

// Automatically imported by Jetbeans Resharper 
using ArduinoLibrary.Annotations; 

namespace ArduinoLibrary 
{ 
    /// <summary> 
    ///  Provides automated detection and initiation of Arduino devices. This class cannot be inherited. 
    /// </summary> 
    public sealed class ArduinoDeviceManager : IDisposable, INotifyPropertyChanged 
    { 
     /// <summary> 
     ///  A System Watcher to hook events from the WMI tree. 
     /// </summary> 
     private readonly ManagementEventWatcher _deviceWatcher = new ManagementEventWatcher(new WqlEventQuery(
      "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 OR EventType = 3")); 

     /// <summary> 
     ///  A list of all dynamically found SerialPorts. 
     /// </summary> 
     private Dictionary<string, SerialPort> _serialPorts = new Dictionary<string, SerialPort>(); 

     /// <summary> 
     ///  Initialises a new instance of the <see cref="ArduinoDeviceManager"/> class. 
     /// </summary> 
     public ArduinoDeviceManager() 
     { 
      // Attach an event listener to the device watcher. 
      _deviceWatcher.EventArrived += _deviceWatcher_EventArrived; 

      // Start monitoring the WMI tree for changes in SerialPort devices. 
      _deviceWatcher.Start(); 

      // Initially populate the devices list. 
      DiscoverArduinoDevices(); 
     } 

     /// <summary> 
     ///  Gets a list of all dynamically found SerialPorts. 
     /// </summary> 
     /// <value>A list of all dynamically found SerialPorts.</value> 
     public Dictionary<string, SerialPort> SerialPorts 
     { 
      get { return _serialPorts; } 
      private set 
      { 
       _serialPorts = value; 
       OnPropertyChanged(); 
      } 
     } 

     /// <summary> 
     ///  Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 
     /// </summary> 
     public void Dispose() 
     { 
      // Stop the WMI monitors when this instance is disposed. 
      _deviceWatcher.Stop(); 
     } 

     /// <summary> 
     ///  Occurs when a property value changes. 
     /// </summary> 
     public event PropertyChangedEventHandler PropertyChanged; 

     /// <summary> 
     ///  Handles the EventArrived event of the _deviceWatcher control. 
     /// </summary> 
     /// <param name="sender">The source of the event.</param> 
     /// <param name="e">The <see cref="EventArrivedEventArgs"/> instance containing the event data.</param> 
     private void _deviceWatcher_EventArrived(object sender, EventArrivedEventArgs e) 
     { 
      DiscoverArduinoDevices(); 
     } 

     /// <summary> 
     ///  Dynamically populates the SerialPorts property with relevant devices discovered from the WMI Win32_SerialPorts class. 
     /// </summary> 
     private void DiscoverArduinoDevices() 
     { 
      // Create a temporary dictionary to superimpose onto the SerialPorts property. 
      var dict = new Dictionary<string, SerialPort>(); 

      try 
      { 
       // Scan through each SerialPort registered in the WMI. 
       foreach (ManagementObject device in 
        new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort").Get()) 
       { 
        // Ignore all devices that do not have a relevant VendorID. 
        if (!device["PNPDeviceID"].ToString().Contains("VID_2341") && // Arduino 
         !device["PNPDeviceID"].ToString().Contains("VID_04d0")) return; // Digi International (X-Bee) 

        // Create a SerialPort to add to the collection. 
        var port = new SerialPort(); 

        // Gather related configuration details for the Arduino Device. 
        var config = device.GetRelated("Win32_SerialPortConfiguration") 
             .Cast<ManagementObject>().ToList().FirstOrDefault(); 

        // Set the SerialPort's PortName property. 
        port.PortName = device["DeviceID"].ToString(); 

        // Set the SerialPort's BaudRate property. Use the devices maximum BaudRate as a fallback. 
        port.BaudRate = (config != null) 
             ? int.Parse(config["BaudRate"].ToString()) 
             : int.Parse(device["MaxBaudRate"].ToString()); 

        // Add the SerialPort to the dictionary. Key = Arduino device description. 
        dict.Add(device["Description"].ToString(), port); 
       } 

       // Return the dictionary. 
       SerialPorts = dict; 
      } 
      catch (ManagementException mex) 
      { 
       // Send a message to debug. 
       Debug.WriteLine(@"An error occurred while querying for WMI data: " + mex.Message); 
      } 
     } 

     /// <summary> 
     ///  Called when a property is set. 
     /// </summary> 
     /// <param name="propertyName">Name of the property.</param> 
     [NotifyPropertyChangedInvocator] 
     private void OnPropertyChanged([CallerMemberName] string propertyName = null) 
     { 
      var handler = PropertyChanged; 
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 
+0

मुझे लगता है कि आप इस पंक्ति में "वापसी" के बजाय "जारी रखें" का अर्थ है: यदि (! डिवाइस ["PNPDeviceID"]। ToString() में शामिल हैं ("VID_2341") &&! डिवाइस ["PNPDeviceID"]। ToString()। इसमें शामिल हैं ("VID_04d0")) वापसी; – Guilherme

+0

काफी संभवतः। मैंने इस वर्बैटिम को एक कामकाजी समाधान से पोस्ट किया। मेरे पास अब परीक्षण करने के लिए Arduino नहीं है, इसलिए यदि यह काम करता है, तो मुझे बताएं और मैं पोस्ट संपादित करूंगा। :-) – Apache

0

मैंने देखा है कि Arduino नैनो की मेरी चीनी क्लोन डिवाइस प्रबंधक में सही ढंग से COM पोर्ट पता चलता है, लेकिन यह सी # एप्लिकेशन सूची देहात नीचे पर प्रदर्शित नहीं करता है जब आप इस का उपयोग कर कोशिश करते हैं और सभी बंदरगाहों मिल आदेश:

using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort")); 

हालांकि, यह सही ढंग से दिखाया गया है जब क्रियान्वित: 1 कोड के उत्पादन के साथ एक, और 2 कोड से उत्पादन के साथ एक:

foreach (string z in SerialPort.GetPortNames()) 

तो मैं 2 सूचियों की है। दोनों की तुलना करते समय, यह सही COM पोर्ट मिलेगा।जाहिर है, मूल एंडुरिनो यूनो का उपयोग करते समय दोनों आदेश सही ढंग से पोर्ट प्रदर्शित करते हैं, इसलिए यह समाधान केवल चीनी क्लोन के लिए काम करेगा, जो कि कुछ अजीब कारणों से using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"));

1

यह विधि आपको यह पता लगाने में सहायता नहीं करती है कि आपका Arduino किस पोर्ट से जुड़ा हुआ है आपके कंप्यूटर

SerialPort.GetPortNames विधि()

// Get a list of serial port names. 
     string[] ports = SerialPort.GetPortNames(); 

     Console.WriteLine("The following serial ports were found:"); 
     Console.WriteLine("Aşşağıda Seri Bağlantı Noktaları Bulundu:");//For Turkish 
     // Display each port name to the console. 
     foreach(string port in ports) 
     { 
      Console.WriteLine(port); 
     } 

     Console.ReadLine(); 
+0

क्या आप अपने उत्तर में एक संक्षिप्त स्पष्टीकरण जोड़ सकते हैं? –

+0

ओकी मुझे खेद है –

संबंधित मुद्दे