Visual Basic 2010串口读取?

时间:2015-11-08 08:07:48

标签: visual-studio-2010 serial-port

我有一个应用程序,它是一个微控制器发送一个20字节的字符串(数字作为文本用逗号分隔)通过UART以140字符串/秒的速率并将结果保存到文本文件,我尝试使用Visual Basic 2010与串口控制组件,serialport组件属性是ReadBufferSize = 20& ReceivedBytesThreshold = 20,它工作正常但有时它在单行中接收超过20个字节会导致如下错误:

382 ,387 ,387 ,172 ,
382 ,385 ,388 ,172 ,
382 ,390 ,389 ,172 ,
382 ,384 ,389 ,172 ,382 ,387 ,392 ,172 ,
383 ,387 ,389 ,172 ,

感谢您的帮助

代码

Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel

Public Class Form1

    Dim sw As IO.StreamWriter 
    Dim sread0 As String

    Dim swo = 0




    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        If (SerialPort1.IsOpen) Then
            SerialPort1.Close()

        End If

        If swo = 1 Then
            sw.Close()

        End If

    End Sub




    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        myPort = IO.Ports.SerialPort.GetPortNames()
        c1.Items.AddRange(myPort)

    End Sub

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        On Error GoTo j1
        swo = 1
        sw = New IO.StreamWriter(Application.StartupPath & "\" & pname.Text & ".txt")
        SerialPort1.PortName = c1.Text
        SerialPort1.BaudRate = "115200" 'c2.Text




        SerialPort1.Open()


    End Sub


    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived



        sread0 = SerialPort1.ReadExisting()

        sw.WriteLine("{0}", sread0)




    End Sub


        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'On Error GoTo u
        If (SerialPort1.IsOpen) Then
            SerialPort1.Close()

        End If

        If swo = 1 Then
            sw.Close()

        End If

        Application.Exit()
        Exit Sub

u:
        MsgBox(Err.Description)

    End Sub




End Class

0 个答案:

没有答案