Click here to Skip to main content
15,891,785 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
VB
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports

Public Class frmMain

   
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

Private Sub frmMain_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
cmbBaud.Items.Add(9600)     ‘Populate the cmbBaud Combo box to common baud rates used

cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)


For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next
cmbPort.Text = cmbPort.Items.Item(0)    ‘Set cmbPort text to the first COM port detected
cmbBaud.Text = cmbBaud.Items.Item(0)    ‘Set cmbBaud text to the first Baud rate on the list

btnDisconnect.Enabled = False           ‘Initially Disconnect Button is Disabled

End Sub





Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text         ‘Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Text         ‘Set Baud rate to the selected value on list

‘Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8            ‘Open our serial port
SerialPort1.Open()

btnConnect.Enabled = False          ‘Disable Connect button
btnDisconnect.Enabled = True        ‘and Enable Disconnect button

End Sub





Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close()             ‘Close our Serial Port

btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub




Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text & vbCr) ‘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
End Sub




Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
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.rtbReceived.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.rtbReceived.Text &= [text]
End If
End Sub




Private Sub cmbPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPort.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.PortName = cmbPort.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 cmbBaud_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaud.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.BaudRate = cmbBaud.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

End Class


How do I make it so that you can only send and receive hex??

Thanks

What I have tried:

VB
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text         ‘Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Integer      ‘Set Baud rate to the selected value on list

‘Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8            ‘Open our serial port
SerialPort1.Open()

btnConnect.Enabled = False          ‘Disable Connect button
btnDisconnect.Enabled = True        ‘and Enable Disconnect button

End Sub

Invalid Cast excpetion was unhandled message appears, conversion from string to type integer not valid
Posted
Updated 1-Sep-16 2:58am
v3

invalid Cast exception was unhandled , conversion from string "" to type integer is not valid

Is pretty clear - it's a text value you get from the COmbo Box - so you can;t just assign that to an integer. Convert it instead:
VB
SerialPort1.BaudRate = Integer.Parse(cmbBaud.Text)
 
Share this answer
 
Comments
Member 12292743 1-Sep-16 8:40am    
sorry I meant to say hex not integer
not post your whole app, coz no one is going to read it all. and don't need to.
post just that part with your problem.

witch is as OriginalGriff already mentioned that you give a String to a Property witch awaits an Integer.

you better put your Project to Option Strict ON
so Visual Studio shows you that error already while writing that piece of code.

as simple Solution for this, you just need to tell the Integer.Parse function that the String represents a Hex value

VB
SerialPort1.BaudRate = Integer.Parse(cmbBaud.Text,System.Globalization.NumberStyles.HexNumber)

//Edit: This is wrong for your code!!


Update:
Error 1
if I change it to
VB
Dim myPort As String() = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available

it works for me.
just have seen you defined it as Array better don't do that. define it as String() and define it local as it's not going to be used elsewhere

instead of the For loop you can use just
VB
cmbPort.Items.AddRange(myPort)
'and this here to select the first element.
cmbPort.SelectedIndex = 0
cmbBaud.SelectedIndex = 0


Error 2
Well its simple, the signatures are not matching
text as Byte VS text as String
you need to change one, the Method or the Delegate

also IMPORTANT .. there is another problem
have a look at Serial port - Wikipedia, the free encyclopedia[^]
9600, 19200, 38400 and so on.. are allready Integers.. thats no HEX if I read your program right.
It will only work if you select 9600 (Hex) as this is 38400 (dec) whitch is an valid Port speed. No need to parse that with base 16 ..
just an
VB
SerialPort1.BaudRate = Integer.Parse(cmbBaud.Text)
like OriginalGriff sayd is the right answer
There is no HEX in that code you posted! I think you got that wrong!
 
Share this answer
 
v2
Comments
Member 12292743 1-Sep-16 9:55am    
2 errors have appeared now.

Private Sub frmMain_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
cmbBaud.Items.Add(9600) ‘Populate the cmbBaud Combo box to common baud rates used

cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)


For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next

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

btnDisconnect.Enabled = False ‘Initially Disconnect Button is Disabled

End Sub

Option strict on disallows late binding (port(i) has been highlighted


SECOND ERROR

Private Sub ReceivedText(ByVal [text] As String)
‘compares the ID of the creating Thread to the ID of the calling Thread
If Me.rtbReceived.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.rtbReceived.Text &= [text]
End If
End Sub

ReceivedText has been underlined and this error message is shown
Option Strict on doesnt allow narrowing in implicit type conversions between PRivate Sub receievedtext(text as String) and delegate delegate Sub SetTextCallback(text as Byte)
F. Xaver 6-Sep-16 12:14pm    
I updated my Solution

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