![](/img/trans.png)
[英]Com-Port Packages are cut off. Rather due to Zigbee or Com-Port?
[英]Making auto detect COM-Port and WriteLine at a same time
您好,我只是從Application創建Windows,並且我也在做Arduino項目,我想同時自動檢測COM-Port和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塊中,並在發送數據后調用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);
}
}
這是工作代碼...
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)
{
SerialPort sp = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
try
{
sp.Open();
try
{
sp.WriteLine("B"); // Send 1 to Arduino
sp.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ek)
{
System.Diagnostics.Debug.WriteLine(ek.Message);
}
}
}
}
}
謝謝...............
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.