Slow serial port reading from Arduino in VB

六月ゝ 毕业季﹏ 提交于 2019-12-12 06:57:06

问题


I have an issue with reading data from a serial port, and that data comes from an arduino that periodically (1 or 2 times a second) sends the status of what it's doing. Using Atmel studio or Arduino IDE to read the serial port, everything works fine, but I'm writing a monitoring program in VB.net 2010 and then things start to go to heck.

I open my port (115200 baud) and have an event handler for the 'Datareceived" event, in this event, I have a stringbuilder which appends the output of Serial.Readline and updates a textbox with it.

Now here's the problem.. it only seems to read about 4-6 lines (~20 bytes each), and holds up the processing on the arduino side.. I've played with buffer sizes, transfer speeds (going down to 9600 didn't help, it just read less lines, and higher transfer speeds (230400) didn't change anything. Played with the buffer length, handshakes.. you name it.

Here is an example of what I should be getting once per second

Sample = 885 Time = 885008 RPM.Value = 0.00 RPM.Slope = 0.00 TPS.Value = 5.05 TPS.Slope = 25.25 MAP.Value = 20.58 MAP.Slope = 6.02 EGP.Value = 20.58 EGP.Slope = 3.01 TSS.Value = 0.00 TSS.Slope = 0.00 BPS.Value = 171.18 POT = 25 AUX = 25 Base Position = 80 DPR comp = 0 TPS slope comp = 74 Aux Compensation = 75 All Compensation = 149 Normal Mode = 80 Overboost comp = 0 Limited Position = 229

(Sorry, linebreaks didn't seem to want to work... you get the idea though)

What is funny is that I'm not missing any data, my few lines of data I get come in at the frequency I should be getting all of them at... Somehow the port isn't keeping up, even though my event handler really isn't doing a whole lot.. I've tried just dumping the raw serial data to the debug window, it didn't change anything... you would think that if it was a problem with the function being too demanding, I would get more or less data depending on how much I had to do

Currently working on a new idea... doing the parsing of the variables/values on a timer tick event (250 ms interval), and just adding each new line to a queue.. it should speed things up.


回答1:


Instead of using the blocking ReadLine try using ReadExisting. You'll have to detect newlines and extract messages manually.

Private Sub SerPort_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles SerPort.DataReceived
    Static sb As New System.Text.StringBuilder
    sb.Append(SerPort.ReadExisting)
    If sb.ToString.Contains(SerPort.NewLine) Then
        'the stringbuilder contains at least one message
        'that ends in a newline
    End If
End Sub

There are other(better) ways to do this, but this should help you.



来源:https://stackoverflow.com/questions/34456962/slow-serial-port-reading-from-arduino-in-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!