Asif Uz Zaman Asif Uz Zaman - 2 months ago 7
C++ Question

Making auto detect COM-Port and WriteLine at a same time

Hello I just make Windows From Application, and I also doing Arduino project,
I want to make auto detect COM-Port and WriteLine at a same time, Here Is my codes...

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)
{

}



}
}


Please help me.. I can not understand any thing now... I am fully BLIND... right now..... Inside Arduino my LED is not turning ON..

Answer

Try to put SerialPort.Open() in try-catch block and call the SerialPort.Close() method after sending data:

  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); 
       }
  }