Hey guys, im using this code to send and receive via rs232 com port
problem is, i want to receive right after i send. I need to know how many bytes to receive, so before receiving, i run a function that figures that out. What i think is happening is that its running too fast and isnt waiting for the entire message to come back. Therefore the buffer is smaller than what is should be. Heres so code:
send function
VB Code:
Public Sub sendData(ByVal sTx As String) '---------------------- '// Clear Tx/Rx Buffers moRS232.PurgeBuffer(Rs232.PurgeBuffers.TxClear Or Rs232.PurgeBuffers.RXClear) 'sTx = sendBox.Text sendBox.Text = sTx If chkAddCR.Checked Then sTx += ControlChars.Cr moRS232.Write(sTx) debugThis("Message Sent: " + sTx) '//clear text box 'sendBox.Text = String.Empty 'sendBox.Refresh() lbHex.Items.Clear() If chkAutorx.Checked Then Button1_Click(Nothing, Nothing) receivedata() End Sub
receive function:
VB Code:
Private Sub receiveData() Try 'first see how many bits are waiting to be read in bytesRemain = moRS232.InBufferCount.ToString() bytesRemaining.Text = bytesRemain ''MsgBox("going to read in " + CStr(bytesRemain) + " bytes") moRS232.Read(Int32.Parse(bytesRemain)) receiveBox.Text = moRS232.InputStreamString receiveBox.ForeColor = Color.Black receiveBox.BackColor = Color.White '// Fills listbox with hex values Dim aBytes As Byte() = moRS232.InputStream Dim iPnt As Int32 For iPnt = 0 To aBytes.Length - 1 lbHex.Items.Add(iPnt.ToString & ControlChars.Tab & String.Format("0x{0}", aBytes(iPnt).ToString("X"))) Next debugThis("Message Received: " + moRS232.InputStreamString) Catch Ex As Exception receiveBox.BackColor = Color.Red receiveBox.ForeColor = Color.White receiveBox.Text = moRS232.InputStreamString debugThis("Error: Could not read data") errorBox.Text = "Error: " & Ex.Message & " data fetched: " & moRS232.InputStreamString End Try End Sub




Reply With Quote