how to do to auto-detect a serial port, instead of I place it manually

Asked

Viewed 111 times

0

Instead of me having to manually place the port in the txt field, how to make it be auto-detect and fill 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);
        }
    }
}

}

2 answers

1


  • beauty, vlw by help, actually C Sharp to starting now, to accompany some video-lesson , and I will test some commands here on the console

0

Insert inside a button

    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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.