2012-09-18 75 views
0

我在C#中爲我的Arduino做了一個小應用程序。一切正常,但問題出在我的應用程序。用戶可以在numericUpDown中選擇他/她的COM端口。Arduino的C#串行端口通信

它的工作原理,但如果用戶選擇錯誤的端口,並嘗試連接,它崩潰,所以我想我需要一個IF statmant給出一條消息。例如,錯誤的端口等,但我不知道如何做到這一點。我該怎麼做?

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; 
using System.IO.Ports; 

namespace IO_Arduino_experiment_project 
{ 
    public partial class Form1 : Form 
    { 
     public static System.IO.Ports.SerialPort serialPort1; 
     private delegate void LineReceivedEvent(string line); 
     public Form1() 
     { 
      InitializeComponent(); 
      button5.Enabled = false; 
      button2.Enabled = false; 
      button3.Enabled = false; 
     } 

     private void button1_Click(object sender, EventArgs e) // Connect Button 
     { 
      System.ComponentModel.IContainer components = new System.ComponentModel.Container(); 
      serialPort1 = new System.IO.Ports.SerialPort(components); // Creating the new object. 
      serialPort1.PortName = "COM" + numericUpDown1.Value.ToString(); // Setting what port number. 
      serialPort1.BaudRate = 9600; 
      serialPort1.DtrEnable = true; 
      serialPort1.Open(); // Open the port for use. 
      button1.Text = "Connected."; 
      button1.Enabled = false; 
      numericUpDown1.Enabled = false; 
      button5.Enabled = true; 
      button2.Enabled = true; 
      button3.Enabled = true; 
     } 

     private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
     { 

     } 

     private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
     { 
      if (serialPort1.IsOpen) serialPort1.Close(); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      serialPort1.Write("1"); 
      textBox1.Text = "LED is on!"; 
      button2.Enabled = false; 
      button3.Enabled = true; 
     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      serialPort1.Write("0"); 
      textBox1.Text = "LED is off!"; 
      button2.Enabled = true; 
      button3.Enabled = false; 
     } 

     private void button4_Click(object sender, EventArgs e) 
     { 
      Close(); 
     } 

     private void button5_Click(object sender, EventArgs e) 
     { 
      serialPort1.Close(); 
      button1.Enabled = true; 
      numericUpDown1.Enabled = true; 
     } 
    } 
} 
+1

try/catch塊怎麼樣? –

+0

肯定會工作 – user1680862

+0

我會建議給一個有效的端口列表。 – Jeff

回答

1

你真的應該更換數字上/下一個ComboBox或其他一些列表控件/菜單時,窗體打開時或刷新按鈕被點擊填充(或其他自動裝置,如定時器) 。

ComboBoxList可以使用GetPortNames方法填寫: -

String[] pNames; 
pNames = System.IO.Ports.SerialPort.GetPortNames(); 

如果你想要做你的描述,你可以查找端口,看看它是否使用類似之前企圖使用存在什麼代碼: -

if (System.IO.Ports.SerialPort.GetPortNames().indexOf("COM" + thePortNum.ToString())>-1) 

注意GetPortNames()返回一個列表如下: -

COM1 
COM10 
COM12 
+0

好的Tnx gona試試吧 – user1680862

+0

它爲你工作了嗎? –