Hi Folks
I have a simple synchronous function that write n bytes to the serial port and reads the same number of bytes back. In the case of the code below n = 4.
Now I have an oscilloscope connected on the serial line so I can see the actual real timings of the data on the lines and that the date is there.
The external device responds very promptly, the write and response takes a grand total of 5 milliseconds. However the actual vb.net code (2010) does not complete the reads until after between 15 - 25 ms have passed!!
I.E. The data is sent out, taking 2.08ms, the response starts 1.04ms later and takes 2.08ms to complete.
Timing the code using Systems.Diagnostics.Stopwatch shows that the writebyte functions take effectively 0ms while the reads take a total of 20ms.... even though my scope shows the whole caboodle is finished in 5ms!
eg.
Is this just due to how the serial port drivers are implemented in Windows or can I do something to improve this situation?Code:Tx: ______[]_______________________________ Rx:_________[]____________________________ ^tx 4 bytes ^rx 4 bytes ^should finish read here ^actually finishes read here
Code:Imports System.IO.Ports Imports System.Diagnostics Private _port As New SerialPort() Public Sub OpenPort _port .PortName("COM14") _port.Parity = 0 _port.BaudRate = 9600 _port.StopBits = StopBits.One _port.DataBits = 8 _port.ReadTimeout = 500 _port.WriteTimeout = 500 _port.Handshake = Handshake.None _port.Open() End Sub Public Overridable Overloads Function SendCommand(ByRef Data() As Byte, ByVal Write As Boolean) As Boolean Dim Length = Data.Length Dim Offset As Integer = 0 Dim sw1 As New Stopwatch() While Length >= 4 'Send and read data in blocks of two bytes Try If Write = True Then 'Set or clear the R#/W bit Data(Offset) = Data(Offset) Or &H80 Else Data(Offset) = Data(Offset) And Not &H80 End If _port.Write(Data, Offset, 2) 'Write the data to the port. sw1 = Stopwatch.StartNew() Data(Offset) = _port.ReadByte() 'Save data that is read back Data(Offset + 1) = _port.ReadByte() Data(Offset + 2) = _port.ReadByte() Data(Offset + 3) = _port.ReadByte() sw1.Stop() Console.WriteLine("Read time: " & sw1.ElapsedMilliseconds.ToString) Catch ex As Exception _port.DiscardInBuffer() _port.DiscardOutBuffer() Throw Return False End Try Length = Length - 4 'Update indices Offset = Offset + 4 End While Return True End Function




Reply With Quote
