在Vb上调用接收数据功能

时间:2014-10-10 10:03:48

标签: vb.net vba serial-port

我已经完成了Link vb串口通信。他们使用以下功能获取数据。我的问题如下

  1. 如何在VB上调用以下函数
  2. 我的串行数据是CSV值,如何分开并在文本框中显示
  3. 更新文本框值?

    函数ReceiveSerialData()As String         '从串行端口接收字符串。         Dim returnStr As String =""

        Dim com3 As IO.Ports.SerialPort = Nothing
        Try
            com3 = My.Computer.Ports.OpenSerialPort("COM3")
            com3.ReadTimeout = 10000
            Do
                Dim Incoming As String = com3.ReadLine()
                If Incoming Is Nothing Then
                    Exit Do
                Else
                    returnStr &= Incoming & vbCrLf
                End If
            Loop
        Catch ex As TimeoutException
            returnStr = "Error: Serial Port read timed out."
        Finally
            If com3 IsNot Nothing Then com3.Close()
        End Try
    
        Return returnStr
    End Function
    
  4. MY compelte code aS BELOW

    Imports System
    Imports System.IO.Ports
    Imports System.ComponentModel
    Imports System.Threading
    
    Imports System.Drawing
    Imports System.Drawing.Drawing2D
    Imports System.Windows.Forms
    Imports Microsoft.VisualBasic.FileIO
    Imports System.IO
    
    
    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim myPort As Array
            myPort = IO.Ports.SerialPort.GetPortNames()
            PortComboBox.Items.AddRange(CType(myPort, Object()))
    
            BaudComboBox.Items.Add(9600)
            BaudComboBox.Items.Add(19200)
            BaudComboBox.Items.Add(38400)
            BaudComboBox.Items.Add(57600)
            BaudComboBox.Items.Add(115200)
            ConnectButton.Enabled = True
            DisconnectButton.Enabled = False
            Timer1.Interval = 1000
            Timer1.Start()
            Receive.Text = ReceiveSerialData()
        End Sub
    
        Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
            SerialPort1.PortName = PortComboBox.Text
            SerialPort1.BaudRate = CInt(BaudComboBox.Text)
            SerialPort1.Open()
            Timer1.Start()
    
            'lblMessage.Text = PortComboBox.Text & " Connected."
            ConnectButton.Enabled = False
            DisconnectButton.Enabled = True
        End Sub
    
        Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
            SerialPort1.Close()
            DisconnectButton.Enabled = False
            ConnectButton.Enabled = True
        End Sub
    
    
    
        Function ReceiveSerialData() As String
            ' Receive strings from a serial port. 
            Dim returnStr As String = ""
    
            Dim com3 As IO.Ports.SerialPort = Nothing
            Try
                com3 = My.Computer.Ports.OpenSerialPort("COM3")
                com3.ReadTimeout = 10000
                Do
                    Dim Incoming As String = com3.ReadLine()
                    If Incoming Is Nothing Then
                        Exit Do
                    Else
                        returnStr &= Incoming & vbCrLf
                    End If
                Loop
            Catch ex As TimeoutException
                returnStr = "Error: Serial Port read timed out."
            Finally
                If com3 IsNot Nothing Then com3.Close()
            End Try
    
            Return returnStr
        End Function
    
    
    
    End Class
    

1 个答案:

答案 0 :(得分:0)

我正在尝试为您创建一个简短的示例,但您需要了解线程和串行工作。按照步骤创建此示例

将新的类模块添加到代码中,名称为mySerial,并在其中包含以下代码(替换代码)

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

Public Class dataReceivedEventArgs
    Inherits EventArgs
    Private m_StringData As String

    Public Sub New(strData As String)
        Me.m_StringData = strData
    End Sub

    Public ReadOnly Property ReceivedData As String
        Get
            Return m_StringData
        End Get
    End Property
End Class

Public Class mySerial
    Private ReadThread As Thread
    Dim SPort As SerialPort
    Private syncContext As SynchronizationContext
    Public Event DataReceived(Sender As Object, ByVal e As dataReceivedEventArgs)

    Public Sub New(ByVal COMMPORT As String, ByVal BaudRate As Integer)
        Me.New(COMMPORT, BaudRate, Parity.None, 8, StopBits.One)
    End Sub    

    Public Sub New(ByVal _COMMPORT As String, ByVal _BaudRate As Integer, ByVal _Parity As Parity, ByVal _DataBits As Integer, ByVal _StopBits As StopBits)
        SPort = New SerialPort
        With SPort
            .PortName = _COMMPORT
            .BaudRate = _BaudRate
            .Parity = _Parity
            .DataBits = _DataBits
            .StopBits = _StopBits
            .Handshake = Handshake.XOnXOff
            .DtrEnable = True
            .RtsEnable = True
            .NewLine = vbCrLf
        End With
        Me.syncContext = AsyncOperationManager.SynchronizationContext
        ReadThread = New Thread(AddressOf ReadPort)
    End Sub

    Public Sub OpenPort()
        If Not SPort.IsOpen Then
            SPort.Open()
            SPort.DiscardNull = True
            SPort.Encoding = System.Text.Encoding.ASCII
            ReadThread.Start()
        End If
    End Sub

    Public Sub ClosePort()
        If SPort.IsOpen Then
            SPort.Close()
        End If
    End Sub

    Private Sub ReadPort()
        Do While SPort.IsOpen
            Dim ReceviceData As String = String.Empty
            Do While SPort.BytesToRead <> 0 And SPort.IsOpen And ReceviceData.Length < 5000
                Try
                    ReceviceData &= SPort.ReadExisting()
                    Thread.Sleep(100)
                Catch ex As Exception

                End Try
            Loop
            If ReceviceData <> String.Empty Then
                'raise event and provide data
                syncContext.Post(New SendOrPostCallback(AddressOf onDataReceived), ReceviceData)
            End If
            Thread.Sleep(500)
        Loop
    End Sub

    Private Sub onDataReceived(ByVal ReceivedData As String)
        RaiseEvent DataReceived(Me, New dataReceivedEventArgs(ReceivedData))
    End Sub
End Class

这是一个类,它将作为你的包装类,现在为了使它工作添加一个名为frmSerial的表单和一个名为txtData的textBox,并设置multiline = true,scrollbars = both,现在通过以下代码

Public Class frmSerial
    Dim WithEvents _Serial As mySerial

    Private Sub frmSerial_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        _Serial.ClosePort()
    End Sub

    Private Sub frmSerial_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        _Serial = New mySerial("COM1", 9600)
        _Serial.OpenPort()
    End Sub

    Private Sub _Serial_DataReceived(Sender As Object, e As dataReceivedEventArgs) Handles _Serial.DataReceived
        txtData.Text &= e.ReceivedData
        txtData.SelectionStart = txtData.Text.Length
        txtData.ScrollToCaret()
    End Sub
End Class

跳这会帮助你和像你这样的人