1
votes

I am using this piece of code to find serial ports and show their names in combobox.

string[] ports = SerialPort.GetPortNames();
foreach (string p in ports)
{
    comboBox1.Items.Add(p);
}
comboBox1.SelectedIndex = 0;

So, when I start my program, the default port should be the first from the ports

I am using this function to initialize serial port

private void portInit()
{
        port.PortName = comboBox1.Text;
        port.BaudRate = 57600;
        port.Parity = Parity.None;
        port.ReceivedBytesThreshold = 8;
        port.DataBits = 8;
        port.Handshake = Handshake.None;
        port.StopBits = StopBits.One;
        port.DataReceived += new SerialDataReceivedEventHandler(datarecievedhandler);
        port.Open();
}

I have this event handler if the user decides to change serial port

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        port.Close();
        port.PortName = comboBox1.Text;
        port.Open();
    }

I intialize my serial port in this part of code

public Form1()
{
      InitializeComponent();
      InitializeGraphs();
      portInit();
      if (port.IsOpen)
            textBox1.Text += "-Port " + port.PortName + " is opened\r\n";
}

The device is connected to the first(default) serial port. When I run my program, the first port opens(I know that it opens because of the textbox), but the datarecieved event handler doesnt work. When I change serial port in combobox, nothing happens(expected behaviour), and when I change my serial port back to the first one, it opens, and the datarecieved event handler works fine. Of course, I want the first serial port to work instantly, without changeing serial ports. I know this question is a long shot, but maybe someone had the similar problem.

1
When you set the Handshake to None it is up to you to turn on the handshake signals. Set RtsEnable and DtrEnable to true. - Hans Passant

1 Answers

1
votes

Simplify the problem- get the basics working first and then add extra features.

Remove the event handler that reopens the port, and disable unnecessary settings like ReceivedBytesThreshold, as these might have side effects that muddy the waters.

Then you can check that you have a working port - if you have the wrong baud rate, you might never receive any data. Make sure the basics are working before you move on.

Once you have a working hard-coded serial port, then add these features back in one by one so you can see which one breaks it.

Also, you could try Disposing your port and creating a new one, if reopening the same port object fails.