c# - 同时自动检测 COM-Port 和 WriteLine

标签 c# c++ winforms windows arduino-uno

你好,我只是从应用程序制作 Windows,我也在做 Arduino 项目, 我想同时自动检测 COM 端口和 WriteLine,这是我的代码...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;


namespace ForTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
            }
            /// read button
            string t;
            t = comboBox1.Text.ToString();
            sErial(t);
        }

        SerialPort sp;
        void sErial(string Port_name)
        {
            sp = new SerialPort(Port_name, 9600, Parity.None, 8, StopBits.One);
            sp.Open();
            try
            {
                sp.WriteLine("G"); //send 1 to Arduino
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



    }
}

请帮助我......我现在什么都不懂......我完全失明......现在......在Arduino内部我的LED没有打开..

最佳答案

尝试将 SerialPort.Open() 放在 try-catch block 中,并在发送数据后调用 SerialPort.Close() 方法:

  void Serial(string port)
  {
      SerialPort sp = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
      try
      {
           sp.Open();
           try
           {
               sp.WriteLine("G"); // Send 1 to Arduino
               sp.Close();
           }
           catch (Exception ex)
           {
                MessageBox.Show(ex.Message);
           }
       }
       catch (Exception e)
       {
            System.Diagnostics.Debug.WriteLine(e.Message); 
       }
  }

关于c# - 同时自动检测 COM-Port 和 WriteLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839796/

相关文章:

c# - 如何仅当本地文件较旧时才下载文件

c# - 在 C# 中使用 Outlook 对象发送电子邮件时更改发件人的电子邮件地址和名称

c# - UWP InkCanvas 内存不足

c++ - 递归类型真的是构建非连续任意大小数据结构的唯一方法吗?

c++ - 左移 (<<) 是 C++11 中的负整数未定义行为吗?

winforms - WinForms 应用程序中的异步任务 Main() 具有异步初始化

c# - 在 64 位计算机上使用 C# 和 "BUILD x86"进行注册表访问

c++ - 如何将 URI 列表编码为字符串?

c# - 如何检测 Windows 关机或注销

winforms - 类实例的新线程 (C#)