Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone.
This application connects to a COM, set a range of baud and then gives you the ability to write strings and makes you see the modem's responseHi everyone i wrote a noob application.
this app connect to a COM

this is the code
VB
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO
Imports System.IO.Ports
Public Class AtNetMain
    Dim myPort As Array  'COM Ports detected on the system will be stored here
    Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
    Dim open As Boolean
    Private Sub AtNetMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'When our form loads, auto detect all serial ports in the system and populate the cmbPort Combo box.
        myPort = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available
        Baud_cmbox.Items.Add(9600)     'Populate the cmbBaud Combo box to common baud rates used
        Baud_cmbox.Items.Add(19200)
        Baud_cmbox.Items.Add(38400)
        Baud_cmbox.Items.Add(57600)
        Baud_cmbox.Items.Add(115200)
        For i = 0 To UBound(myPort)
            Port_cmbox.Items.Add(myPort(i))
        Next
        Port_cmbox.Text = Port_cmbox.Items.Item(0)    'Set cmbPort text to the first COM port detected
        Baud_cmbox.Text = Baud_cmbox.Items.Item(0)    'Set cmbBaud text to the first Baud rate on the list
        LogOff_btn.Enabled = False           'Initially Disconnect Button is Disabled
    End Sub
    Private Sub LogOn_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogOn_btn.Click
        If (String.IsNullOrEmpty(Port_cmbox.Text) Or String.IsNullOrEmpty(Baud_cmbox.Text)) Then
            MessageBox.Show("Non hai selezionato la Porta e/o il Baud Rate", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Else
            SerialPort1.PortName = Port_cmbox.Text         'Set SerialPort1 to the selected COM port at startup
            SerialPort1.BaudRate = Baud_cmbox.Text         'Set Baud rate to the selected value on
            'Other Serial Port Property
            SerialPort1.Parity = IO.Ports.Parity.None
            SerialPort1.StopBits = IO.Ports.StopBits.One
            SerialPort1.DataBits = 8            'Open our serial port
            Try
                SerialPort1.Open()
                open = True
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            LogOn_btn.Enabled = False          'Disable Connect button
            LogOff_btn.Enabled = True        'and Enable Disconnect button
        End If
    End Sub
    Private Sub LogOff_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogOff_btn.Click
        SerialPort1.Close()             'Close our Serial Port
        LogOn_btn.Enabled = True
        LogOff_btn.Enabled = False
    End Sub
    Private Sub Send_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Send_btn.Click
        If (open) Then
            Try
                SerialPort1.WriteLine("AT+CSQ")
                'MessageBox.Show(SerialPort1.ReadExisting())
                'The text contained in the txtText will be sent to the serial port as ascii
                'plus the carriage return (Enter Key) the carriage return can be ommitted if the other end does not need it
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        Else
            MessageBox.Show("Nessuna connessione stabilita", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End If
    End Sub
    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        MessageBox.Show(SerialPort1.ReadExisting())
        ReceivedText(SerialPort1.ReadExisting())    'Automatically called every time a data is received at the serialPort
    End Sub
    Private Sub ReceivedText(ByVal [text] As String)
        'compares the ID of the creating Thread to the ID of the calling Thread
        If Me.Received_rtbox.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
        Else
            Me.Received_rtbox.Text &= [text]
        End If
    End Sub
    Private Sub Port_cmbox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Port_cmbox.SelectedIndexChanged
        If SerialPort1.IsOpen = False Then
            SerialPort1.PortName = Port_cmbox.Text         'pop a message box to user if he is changing ports
        Else                                                                               'without disconnecting first.
            MsgBox("Valid only if port is Closed", vbCritical)
        End If
    End Sub
    Private Sub Baud_cmbox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Baud_cmbox.SelectedIndexChanged
        If SerialPort1.IsOpen = False Then
            SerialPort1.BaudRate = Baud_cmbox.Text         'pop a message box to user if he is changing baud rate
        Else                                                                                'without disconnecting first.
            MsgBox("Valid only if port is Closed", vbCritical)
        End If
    End Sub
    Private Sub SerialPort1_ErrorReceived(sender As System.Object, e As System.IO.Ports.SerialErrorReceivedEventArgs) Handles SerialPort1.ErrorReceived
        MessageBox.Show("Errore", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End Sub
End Class


I use only one form that was designed as simply app
two button for connect and disconnect, two combobox for com and baud selection and a textbox where you can write the message ...

my problem is that the line of code
VB
SerialPort1.WriteLine("AT+CSQ")
 MessageBox.Show(SerialPort1.ReadExisting())
doesn't working :( i dunno why....
Posted
Updated 2-Aug-11 7:21am
v2

With the two lines of code you show, they are executed one right after the other. Some devices require a little time to process the data before sending a reply.

Also you have a DataReceived event which should capture the data being returned from the device when it does. So the second part of the problem code is redundant anyway.

[edit]
Add following right under Dim open As Boolean to your list of declarations, it is missing from your code.
VB
WithEvents SerialPort1 As New SerialPort


Delete these two subs, they are not needed.
VB
Private Sub Port_cmbox_SelectedIndexChanged
Private Sub Baud_cmbox_SelectedIndexChanged


Remove the message box line.
VB
Private Sub SerialPort1_DataReceived(ByVal sender As Object
MessageBox.Show(SerialPort1.ReadExisting()) 


I tested the code, it should work for you now.
 
Share this answer
 
v3
You WILL need to use a delegate as the serial_DataReceive function executes on a seperate thread.

Add a Delegate to the top of your code.

Private Delegate Sub SPReceiver(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)


 Private Sub SP_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SP.DataReceived
  If Me.InvokeRequired = True Then
   Me.Invoke(New SPReceiver(AddressOf SP_DataReceived), sender, e)
   Exit Sub
  End If

  dim DataRec As String = SP.ReadExisting
End sub
 
Share this answer
 
yes i use messabox to debug .. i know it's useless (the messagebox)
 
Share this answer
 
Comments
S Houghtelin 2-Aug-11 14:28pm    
It is not the message box, when you send the AT command you need to allow time for the modem or other device to respond to that command.

Also the message box is not the best one to use for reading the input from a comm port, the message box is for text, what comes in from the serial port may or may not be text.

Please next time use the blue "Add Comment" to reply to an answer. Don't use "Add your solution here" to reply. This way the person who posts an answer will get an email. Thank you.
I have got the same problem, I followed your advice, but I still not reading anything from the serial port.

When using terminal I verified that I get a response to the command I send, but with the code I am never entering in the receiving function.

Please any clues?

Here is the code I am using.

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports



Public Class ECOM_FormFx
'--------------------------
Dim myPort As Array 'COM Ports detected on the system will be stored here
WithEvents P_SerialPortFX_1 As New SerialPort

Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
Private Delegate Sub SPReceiver(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
'--------------------------
Private Sub ECOM_FormFx_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'When our form loads, auto detect all serial ports in the system and populate the cmbPort Combo box.
myPort = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available
ComboBoxBR.Items.Add(9600) 'Populate the cmbBaud Combo box to common baud rates used
ComboBoxBR.Items.Add(19200)
ComboBoxBR.Items.Add(38400)
ComboBoxBR.Items.Add(57600)
ComboBoxBR.Items.Add(115200)
For i = 0 To UBound(myPort)
ComboBoxPC.Items.Add(myPort(i))
Next
Try
P_SerialPortFX_1 = New SerialPort(ComboBoxPC.Items.Item(0).ToString)
Try
P_SerialPortFX_1.BaudRate = Val(ComboBoxBR.Items.Item(0).ToString)
Catch ex As Exception
TextBoxMainIhmView.Text = ex.Message
P_SerialPortFX_1.BaudRate = 9600
End Try
P_SerialPortFX_1.Parity = Parity.None
P_SerialPortFX_1.StopBits = StopBits.One
P_SerialPortFX_1.DataBits = 8
P_SerialPortFX_1.Handshake = Handshake.None
P_SerialPortFX_1.RtsEnable = True
AddHandler P_SerialPortFX_1.DataReceived, AddressOf SerialPortFX_1_DataReceived
Catch ex As Exception
TextBoxMainIhmView.Text = ex.Message
End Try

ComboBoxPC.Text = ComboBoxPC.Items.Item(0) 'Set cmbPort text to the first COM port detected
ComboBoxBR.Text = ComboBoxBR.Items.Item(0) 'Set cmbBaud text to the first Baud rate on the list

ButtonDisconnect.Enabled = False 'Initially Disconnect Button is Disabled

End Sub

Private Sub ButtonConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonConnect.Click
P_SerialPortFX_1.PortName = ComboBoxPC.Text 'Set SerialPort1 to the selected COM port at startup
P_SerialPortFX_1.BaudRate = ComboBoxBR.Text 'Set Baud rate to the selected value on

Try
P_SerialPortFX_1.Open()
ButtonConnect.Enabled = False 'Disable Connect button
ButtonDisconnect.Enabled = True 'and Enable Disconnect button
Catch ex As Exception
TextBoxMainIhmView.Text = ex.Message
ButtonConnect.Enabled = True 'Disable Connect button
ButtonDisconnect.Enabled = False 'and Enable Disconnect button
End Try



End Sub

Private Sub ButtonDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonDisconnect.Click
P_SerialPortFX_1.Close() 'Close our Serial Port

ButtonConnect.Enabled = True
ButtonDisconnect.Enabled = False
End Sub

'----------------------------------------------------------------
Private Sub ButtonSD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSD.Click
'The text contained in the txtText will be sent to the serial port as ascii
'plus the carriage return (Enter Key) the carriage return can be ommitted if the other end does not need it
Try
P_SerialPortFX_1.Write(TextBoxTD.Text & vbCr)
Catch ex As Exception
TextBoxMainIhmView.Text = ex.Message
End Try
End Sub
'----------------------------------------------------------------
Private Sub SerialPortFX_1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles P_SerialPortFX_1.DataReceived
' ReceivedText(P_SerialPortFX_1.ReadExisting()) 'Automatically called every time a data is received at the serialPort
'compares the ID of the creating Thread to the ID of the calling Thread
If Me.TextBoxRD.InvokeRequired Then
Me.Invoke(New SPReceiver(AddressOf SerialPortFX_1_DataReceived), sender, e)
Else
Me.TextBoxRD.Text &= [Text]
End If
End Sub
Private Sub ReceivedText(ByVal [text] As String)
'compares the ID of the creating Thread to the ID of the calling Thread
If Me.TextBoxRD.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
' Me.Invoke(New SPReceiver(AddressOf SerialPortFX_1_DataReceived), sender, e)
Else
Me.TextBoxRD.Text &= [text]
End If
End Sub
 
Share this answer
 
Comments
[no name] 2-Jul-15 11:21am    
Exactly how is this a solution to this 4 year old question?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900