同时自动检测COM-Port和WriteLine
本文关键字:WriteLine COM-Port 自动检测 | 更新日期: 2023-09-27 18:11:17
你好,我只是做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)
{
}
}
}
请帮帮我…我现在什么都听不懂了……我完全瞎了…现在……
尝试将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);
}
}
}
}
}
谢谢 ...............