0

When running a project in Visual Studio 2019 that requires serial communication, I get the error: The COM3 port does not exist. How could I solve this?

CODE:

        public Form1()
        {
            InitializeComponent();

            if (!serialPort1.IsOpen)
            {
                serialPort1.Open();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            OnOffButton.Text = "OFF";
        }

        private void Form1_close(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void OnOffButton_Click(object sender, EventArgs e)
        {
            if (ON=="A0" && aux==false)
            {
                ON = "A1";
                serialPort1.WriteLine(ON);
                OnOffButton.Text = "ON";
                OnOffButton.BackColor = Color.LimeGreen;
            }
            else
            {
                ON = "A0";
                serialPort1.WriteLine(ON);
                OnOffButton.Text = "OFF";
                OnOffButton.BackColor = Color.Red;
            }

        }
Charlieface
  • 52,284
  • 6
  • 19
  • 43
Michy
  • 1
  • 1
    ...so... do you actually have a port named `COM3` or don't you? – Dai Jun 17 '23 at 09:25
  • 1
    `Environment.Exit(0);` <-- Calling this is unnecessary: WinForms will end your process when the last `Form` is closed. – Dai Jun 17 '23 at 09:26
  • You should not be performing actions that have external side-effects inside a constructor, especially not a UI-level constructor like your `Form1()` ctor: move your `serialPort1.Open()` call to your `Form1_Load` event-handler or the `override void OnLoad` method - and wrap it in a `try/catch( )` and catch [only the specific exception-types listed in the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.open?view=dotnet-plat-ext-7.0). – Dai Jun 17 '23 at 09:27
  • Open Device Manager and see whether you have COM3. And where is `SerialPort` variable and port name assignment? – i486 Jun 17 '23 at 09:28
  • You need to run as Admin to add a plug and play Com device. Device may be Com4 instead of Com3, – jdweng Jun 17 '23 at 10:14
  • Use the PowerShell commands at the end of this [post](https://stackoverflow.com/a/74895268/10024425) to determine the correct port. – Tu deschizi eu inchid Jun 17 '23 at 15:01

0 Answers0