Click here to Skip to main content
14,209,124 members
Rate this:
Please Sign up or sign in to vote.
 Dim outData As Byte() = New Byte(0) {}

Private Function HextoByte(ByVal msg As String) As Byte()
        msg = msg.Replace(" ", "")

        Dim combuffer As Byte() = New Byte(msg.Length \ 2 - 1) {}
        For i As Integer = 0 To msg.Length - 1 Step 2
            combuffer(i \ 2) = CByte(Convert.ToByte(msg.Substring(i, 2), 16))
        Next

        Return combuffer
    End Function

Private Function BytetoHex(ByVal comByte As Byte()) As String
        Dim builder As New StringBuilder(comByte.Length * 3)
        For Each data As Byte In comByte
            builder.Append((Convert.ToString(data, 16).PadLeft(2, "0")))
        Next
        Return builder.ToString().ToUpper()
    End Function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lblDataValue.Text = ScrollData.Value.ToString()
        ScrollData.Enabled = False
        ScrollData.Maximum = 255
        ScrollData.LargeChange = 1
        btnDisconnect.Enabled = False
        tbRx.Text = "00"

        Dim Portnames as String() = SerialPOrt.GetPortNames
        IF Portnames is nothing then
            msgbox("No ports detected")
            me.close()
        End If
        cbComPort.Items.AddRange(Portnames)
        cbComPort.Text = Portnames(0)
    End Sub

Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click

        outData(0) = Convert.ToByte(lblDataValue.Text)

        Try
            SerialPort1.PortName = cboCOMPorts.Items(cboCOMPorts.SelectedIndex).ToString()
            SerialPort1.BaudRate = 9600
            SerialPort1.Open()
            SerialPort1.Write(outData, 0, 1)
            btnDisconnect.Enabled = True
            ScrollData.Enabled = True
            btnConnect.Enabled = False
        Catch ex As Exception
            btnDisconnect.PerformClick()
        End Try
    End Sub

 Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
        Try
            SerialPort1.DiscardInBuffer()
            SerialPort1.DiscardOutBuffer()
            SerialPort1.Close()
            ScrollData.Value = 0
            ScrollData.Enabled = False
            btnConnect.Enabled = True
            btnDisconnect.Enabled = False
        Catch ex As Exception

        End Try
    End Sub

Private Sub ScrollData_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles ScrollData.Scroll
        lblDataValue.Text = ScrollData.Value.ToString("X")

        outData(0) = Convert.ToByte(ScrollData.Value)
        SerialPort1.Write(outData, 0, 1)
    End Sub

Private Delegate Sub DisplayDelegate(ByVal displayChar As String)

    Private Sub DisplayCharacter(ByVal displayChar As String)
        tbRx.Text = displayChar
    End Sub

    Private Sub serialPort1_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim rx As Integer
        rx = SerialPort1.BytesToRead
        Dim comBuff As Byte() = New Byte(rx - 1) {}
        SerialPort1.Read(comBuff, 0, rx)
        tbRx.Invoke(New DisplayDelegate(AddressOf DisplayCharacter), New Object() {BytetoHex(comBuff)})
    End Sub


the code is from this website


[^]

What I have tried:

http://www.codeproject.com/Tips/341405/Read-n-bytes-from-the-serial-port-in-NET

In the link above, it explains how to read n bytes which is what i was thinking I should do since I am expecting 2 bytes as per the commands manual from the manufacturer:

https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwj8xNS2-Z3PAhVDD8AKHQotAIIQFgg0MAI&url=http%3A%2F%2Fwww.optris.co.uk%2Finterfaces%3Ffile%3Dtl_files%2Fdownloads%2FManuals%2Faddendums-de-en%2Fct-ctlaser-commands.pdf&usg=AFQjCNEkEtwUoiM6jsJYOnGD4-8Yo2Cprg&bvm=bv.133387755,bs.2,d.d2s
Posted
Updated 20-Sep-16 22:09pm
v3
Comments
Member 12292743 20-Sep-16 8:38am
   
but nothing changes in tbRx in which I want a temp value to be seen
Member 12292743 20-Sep-16 8:39am
   
if i am right about the reading of more than 1 byte, how do i implement that into my code
Rate this:
Please Sign up or sign in to vote.

Solution 1

Serial ports are generally not "fast devices" - and when you use 9600 baud, you are saying "this port transfers 9600 bits of information per second at most". That's roughly 960 bytes per second (slightly less than that due to start, stop, and parity bits in fact) - which in terms of your PC processing power is positively glacial. And the DataReceived event is signalled every time a byte is received by the hardware. So if your remote device sends five bytes, you will probably get five well-spaced events: one for each byte.

And each time your receive a byte, you overwrite what is in the textbox...so you will only ever see the final byte, none of the others.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

If you want to read more than 1 Byte (this answer is additional to the solution from OG) then you could/should wait until "SerialPort1.BytesToRead" has that value you want to have - perhaps with a loop or "Do ... until" ... or in the method "serialPort1_DataReceived" you check first if BytesToRead has the right value - in other case you leave the method without doing anything ...

for example :
Private Sub serialPort1_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    Dim rx As Integer
    rx = SerialPort1.BytesToRead
    if rx >= 2 then
       Dim comBuff As Byte() = New Byte(rx - 1) {}
       SerialPort1.Read(comBuff, 0, rx)
       tbRx.Invoke(New DisplayDelegate(AddressOf DisplayCharacter), New Object() {BytetoHex(comBuff)})
    end if
End Sub
   
v4
Comments
Member 12292743 20-Sep-16 16:14pm
   
how do i check if BytesToRead has the right value?
Ralf Meier 20-Sep-16 17:33pm
   
you have a line in your code where you wrote "rx = SerialPort1.BytesToRead".
if you now wait for 2 Bytes and the value of "rx" isn't 2 then you abort the method (for example "Exit Sub")
Member 12292743 21-Sep-16 4:47am
   
sorry to be a pain guys, but i have implemented your suggestion and still nothing happens.

I noticed something strange, i put a breakpoint in the scrolldata function and when and step through and go line by line, an error message appears on this line:

SerialPort1.Write(outData, 0, 1)

telling me the port is closed.

I tried inserting SerialPort1.open() before but another error message appeared saying that the port was already open?

What do I do
Ralf Meier 21-Sep-16 9:02am
   
Does your ComboBox-Selection contains a valid COM-Port when you use the Btn_Connect-Method ?
Perhaps you should first debug the (complete) SerialPort-Settings (by setting a Breakpoint in the Line "SerialPort1.Write(outData, 0, 1)".
The code-changes I made in this Solution are not able to effect this behaviour ...
Rate this:
Please Sign up or sign in to vote.

Solution 3

You might use a buffer to append received bytes (one at time) to. Then when the accumulated bytes in the buffer are enough, you process them in order to abtain the meaningful info.
   
Comments
Member 12292743 21-Sep-16 4:58am
   
is it possible for you to show me an example of what you mean?

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



Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190617.3 | Last Updated 21 Sep 2016
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100