none
Serial Port Error: showing port is already open?a RRS feed

  • Question

  • Hi everyone, 

    I fairly new to C# and have been trying to create a program that connects to a port and sends text to it. However when I try to connect or disconnect to the port it throws an error: port is already open. I've never worked with serial port communication before, so I'm having a hard time figuring out what I'm doing wrong. The goal is to open the port, send a hex command to setup the screen (clear the screen), then write a new string to the port, and finally disconnect from the port. Any help would be greatly appreciated. 

    public partial class Form1 : Form
        {
            static string device_name = "COM3";
            static int baud_rate = 19200;
            SerialPort sp = new SerialPort(device_name, baud_rate, Parity.None, 8, StopBits.One);
          
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            // open port 
            private void btnConnect_Click(object sender, EventArgs e)
            {
                byte[] clear_screen = new byte[2] { 0xFE, 0x58 };
    
                // setup screen
                try
                {
                    sp.Close();
                    sp.Open();
                    sp.Write(clear_screen, 0, clear_screen.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // close port 
            private void btnDisconnect_Click(object sender, EventArgs e)
            {
                byte[] save_screen = new byte[2] { 0xFE, 0xC2 };
    
                try
                {
                    sp.Write(save_screen, 0, save_screen.Length);
                    sp.Close();
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // write to port 
            private void btnWrite_Click(object sender, EventArgs e)
            {
                byte[] write_line = new byte[2] { 0xFE, 0x40 };
                string str = textBox1.Text.ToString();
                try
                {
                    sp.Close();
                    sp.Open();
                    sp.Write(str);
                    sp.Write(write_line, 0, write_line.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
         
        }


    Wednesday, February 6, 2019 8:33 PM

Answers

  • Hi espro88,

    Thank you for posting here.

    For your question, I do some change, please try the code below.

    public partial class Form1 : Form
        {
            static string device_name = "COM3";
            static int baud_rate = 19200;
            SerialPort sp = new SerialPort(device_name, baud_rate, Parity.None, 8, StopBits.One);
          
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            // open port 
            private void btnConnect_Click(object sender, EventArgs e)
            {
                byte[] clear_screen = new byte[2] { 0xFE, 0x58 };
    
                // setup screen
                try
                {
                    sp.Open();
                    sp.Write(clear_screen, 0, clear_screen.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // close port 
            private void btnDisconnect_Click(object sender, EventArgs e)
            {
                byte[] save_screen = new byte[2] { 0xFE, 0xC2 };
    
                try
                {
                    sp.Write(save_screen, 0, save_screen.Length);
                    sp.Close();
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // write to port 
            private void btnWrite_Click(object sender, EventArgs e)
            {
                byte[] write_line = new byte[2] { 0xFE, 0x40 };
                string str = textBox1.Text.ToString();
                try
                {
                    sp.Write(str);
                    sp.Write(write_line, 0, write_line.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
         
        }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by espro88 Thursday, February 7, 2019 6:48 PM
    Thursday, February 7, 2019 4:06 AM
    Moderator

All replies

  • Rather than write all your code inside the button click event handlers try organizing your code into subroutines and functions that you can call from within the buttons

    example call in button


    private void btnOpen_Click(object sender, EventArgs e)
            {
                    openPort();
            }



    example sub checking the state of the port before opening

     private void openPort()
            {
                if (!sp.IsOpen)
                {
                    try
                    {
                        sp.Open();
                    }
                    catch
                    {
                    }
                }
            }



    your use of try-catch is good but test the open and close operations separate from your write operations.

    When opening and closing serial ports allow time for the port to close, close followed too quickly by open does not give the port time to close and will give the exception you describe

    Write subs for your serial write routines also and call them with a button or some other event.

                            
    • Edited by Jeff_T_1234 Thursday, February 7, 2019 2:26 AM
    Thursday, February 7, 2019 2:23 AM
  • Hi espro88,

    Thank you for posting here.

    For your question, I do some change, please try the code below.

    public partial class Form1 : Form
        {
            static string device_name = "COM3";
            static int baud_rate = 19200;
            SerialPort sp = new SerialPort(device_name, baud_rate, Parity.None, 8, StopBits.One);
          
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            // open port 
            private void btnConnect_Click(object sender, EventArgs e)
            {
                byte[] clear_screen = new byte[2] { 0xFE, 0x58 };
    
                // setup screen
                try
                {
                    sp.Open();
                    sp.Write(clear_screen, 0, clear_screen.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // close port 
            private void btnDisconnect_Click(object sender, EventArgs e)
            {
                byte[] save_screen = new byte[2] { 0xFE, 0xC2 };
    
                try
                {
                    sp.Write(save_screen, 0, save_screen.Length);
                    sp.Close();
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
            // write to port 
            private void btnWrite_Click(object sender, EventArgs e)
            {
                byte[] write_line = new byte[2] { 0xFE, 0x40 };
                string str = textBox1.Text.ToString();
                try
                {
                    sp.Write(str);
                    sp.Write(write_line, 0, write_line.Length);
                }
                catch (Exception E) { MessageBox.Show(E.ToString(), "Error"); }
            }
    
         
        }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by espro88 Thursday, February 7, 2019 6:48 PM
    Thursday, February 7, 2019 4:06 AM
    Moderator
  • Thank-you so much for your help. I didn't realize that I re-opened the port when writing to the screen. 
    Thursday, February 7, 2019 6:49 PM
  • Thank-you for your reply. I will organize my code into functions and create subs for the serial routine. It'll definitely make everything look cleaner. 
    Thursday, February 7, 2019 6:51 PM