简体   繁体   English

在插入和输出C#中自动检测Arduino状态

[英]Auto Detecting Arduino Status on plug in and out c#

I am trying to create an application that communicates with the arduino and want to cover for issues like plugging out and in of the arduino device when the application is running. 我正在尝试创建一个与arduino通信的应用程序,并希望在应用程序运行时解决诸如将其插入arduino设备之类的问题。 I would like it to continue receiving data from the arduino as soon it is plugged back in. 我希望它一插回就可以继续从arduino接收数据。

This is the error i get: An unhandled exception of type 'System.IO.IOException' occurred in System.dll 这是我得到的错误:System.dll中发生了'System.IO.IOException'类型的未处理异常

Additional information: The I/O operation has been aborted because of either a thread exit or an application request. 附加信息:由于线程退出或应用程序请求,I / O操作已中止。

This is the code from which i have tried but it 这是我尝试过的代码,但它

  private bool AutoDetectArduino()
    {
        ManagementScope connectionscope = new ManagementScope();

        SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionscope, serialQuery);

        bool weturn = false;

        try
        {

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

                if (desc.Contains("USB Serial Device"))
                {
                    sp.Close();
                    sp.PortName = deviceid;

                    weturn = true;
                }
                else
                {
                    weturn = false;
                }
            }

        }
        catch (ManagementException e)
        {

        }

        return weturn;
    }

    string[] generalarray = new string[3];

    public void readArduinoLightData()
    {
        AutoDetectArduino();
        try
        {
            if (!sp.IsOpen)
            {
                sp.Open();
            }

            sp.Parity = Parity.None;
            sp.StopBits = StopBits.One;
            sp.Handshake = Handshake.None;

            sp.ReadTimeout = 10000;

            sp.DataReceived += new SerialDataReceivedEventHandler(datareceive);
        }
        catch
        {

        }
    }


    private void datareceive(object sender, SerialDataReceivedEventArgs e)
    {

            for (count = 0; count < generalarray.Length; count++)
            {
                generalarray[count] = sp.ReadLine();
            }

            temperature =Convert.ToDouble(generalarray[0]);
            light = Convert.ToDouble(generalarray[1]);
            currentvolt = Convert.ToDouble(generalarray[2]);
        }

// I have created a timer that keeps on checking if the ports from the Auto Detect method but can't get it right. //我创建了一个计时器,该计时器会继续检查是否使用“自动检测”方法的端口,但是无法正确执行。 Does any one have a clue on this, Thank You !! 有人对此有任何线索吗,谢谢!

You are entirely at the mercy of the driver that sits between your application and the hardware connection. 完全由位于应用程序和硬件连接之间的驱动程序所左右。 Some drivers handle the sudden removal better than others. 一些驱动程序比其他驱动程序处理更好。 For the drivers that do not fail gracefully, there is no amount of try/catching you can do to catch this reliably. 对于无法正常故障的驱动程序,您无需进行任何尝试/捕获就可以可靠地捕获此故障。

The issue occurs when data is being read while the underlying basestream is still open. 在底层基础流仍处于打开状态时读取数据时,会发生此问题。 There are workarounds for this particular issue but again, you will still be at the mercy of the driver. 有针对此特定问题的解决方法,但同样,您仍然会受到驾驶员的控制。

If you are interested in capturing USB insertion and removal events without polling, checkout my project here https://github.com/corytodd/porty . 如果您有兴趣在不进行轮询的情况下捕获USB插入和拔出事件,请在https://github.com/corytodd/porty上检出我的项目。 This listens to messages on the process message pump and handles them accordingly. 这将侦听过程消息泵上的消息并进行相应处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM