how to auto-detect a serial port, instead of putting it manually

0

Instead of having to manually put the port in the txt field, how to make it auto-detect and fill in the field?

    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
           SerialPort sp = new SerialPort();
            sp.PortName = txtPort.Text;
            sp.Open();
            sp.WriteLine("AT" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CMGF=1" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CSCS=\"GSM\"" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CMGS=\"" + txtPhoneNumber.Text + "\"" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine(txtMessage.Text + Environment.NewLine);
            Thread.Sleep(100);
            sp.Write(new byte[] { 26 }, 0, 1);
            Thread.Sleep(100);
            var response = sp.ReadExisting();
            if (response.Contains("ERRO"))
                MessageBox.Show("Envio falhou , tente novamente daqui 5 segundos !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("SMS Enviado !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            sp.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

}

    
asked by anonymous 23.04.2017 / 22:36

2 answers

1

The SerialPort object has methods and properties that can help you find the correct COM. Like the PortName property with no arguments that returns the available ports. Open each one, send some boot AT commands and see if the return was correct for the serial device.

link

    
24.04.2017 / 02:45
0

Insert inside a click_click

    Try
        With SerialPort1
            'aqui pega nome da porta COM (COM11)
            .PortName = Label3.Text '
            .BaudRate = 9600
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
            .RtsEnable = True
            .ReceivedBytesThreshold = 1
            .NewLine = vbCr
            .ReadTimeout = 1000
            .Open()

        End With
        If SerialPort1.IsOpen Then
            Thread.Sleep(1000)
            Label4.Text = "CONECTADO COM SUCESSO !"
        Else
            Label4.Text = "Conexao do modem Falhou !"
            Label4.ForeColor = Color.Red
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    
27.04.2017 / 12:48