IO.Ports and reading bytes

TheNewKidOnTheBlock

New member
Joined
Nov 10, 2008
Messages
1
Programming Experience
Beginner
Hi all,

I am writing a small program in which a user can send/recieve data via ports.

I am able to send and recieve data.
and select:
-Open comms
-Set baud rate, parity, stop bits, etc.
I am able to view the bytes in hex.

I have a problem which i want to be able to set the number of read bytes.
I want the user to be able to enter the maxium number of bytes to read. Once the user clicks send i only want to display the maximum number of bytes.

E.g

TX = Hello Everybody, How are you?
Maximum number of bytes = 7

so RX should display Hello E

and possible an error message to say the remaining n characters could not be displayed.

I am trying to Set the number of bytes to read.
A user would select Maximum number of bytes to read. (MaxBytesTextBox)
Even if TransmissionTextBox has 30 characters to write, i only want to be able to read what was set in the MaxBytesTextBox.

I am unsure whether to write the code in the DataReceive event or to place the code in the UpdateTextBox1 once the DataRecieved.

so far it is within my update of the RecieveingTextBox1

Code Thus Far:

VB.NET:
Public Sub UpdateTextBox1()
        Dim bytes As Integer = SerialPort1.BytesToRead       'Read the bytes 
        Dim buffer(bytes) As Byte
        Dim i As Integer
             ' MaxBytes is the value entered in textbox2

        Dim sb As New System.Text.StringBuilder(buffer.Length)
        Dim MaxB As Integer = Integer.MaxValue ' MaxBytes is the value 
        MaxB = MaxBytesTextBox.Text
        If SerialPort1.BytesToRead > MaxB Then                                'if bytes to read greater than maxbytes 
            MessageBox.Show("ERROR MESSAGE")                                        'then display error
        Else
            With RecieveTextBox1()
                'to be updated
                SerialPort1.Read(buffer, 0, bytes)                   'Read RX buffer and bytes
                TextBox1.AppendText(ByteArrayToHexString(buffer))       'This will display hex values in a data contents. Always End 0D 0A 00 
                RecieveTextBox1.AppendText(SerialPort1.ReadExisting())       'The RX txtbox will display RX message
            End With
        End If
        TextBox1.AppendText(ByteArrayToHexString(buffer))
    End Sub
The code works but keeps displaying the error message twice, unsure why?
i will test my program to see if the code works, and i would recieve the error message. if try again after to test the program, whatever i do i still recieve error messages, even if Maximum numbert fo bytes are not met.

There is also a "Private Function ByteToHex" which converts the bytes read to hex and then displayed in Textbox1. would i need to but the code here?

So how would i go about accomplishing this? is there anyone who can help?

Many Thanks in advance.
 
Last edited by a moderator:
Back
Top