2012年2月18日 星期六

Receiving RS232 message

參考引用
--
Public Class Form1

    Dim inputData As String = ""
    Public Event DataReceived As IO.Ports.SerialDataReceivedEventHandler

    Private Sub Form1_Load(ByVal sender As System.Object, _
                   ByVal e As System.EventArgs) Handles MyBase.Load
        'Set values for some properties
        SerialPort1.PortName = "COM1"
        SerialPort1.BaudRate = 9600
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.DataBits = 8
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.Handshake = IO.Ports.Handshake.None
        SerialPort1.RtsEnable = True

        ' Open the Serial Port
        SerialPort1.Open()

        'Writes data to the Serial Port output buffer
        If SerialPort1.IsOpen = True Then
            SerialPort1.Write("MicroCommand")
        End If
    End Sub

    ' Receive data from the Serial Port
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
                      ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
                      Handles SerialPort1.DataReceived
        inputData = SerialPort1.ReadExisting 'or SerialPort1.ReadLine
        Me.Invoke(New EventHandler(AddressOf DoUpdate))
    End Sub

    'Show received data on UI controls and do something
    Public Sub DoUpdate()
        TextBox1.Text = TextBox1.Text & inputData
    End Sub

    Private Sub Form1_FormClosed(ByVal sender As System.Object, _
                   ByVal e As System.Windows.Forms.FormClosedEventArgs) _
                   Handles MyBase.FormClosed
        ' Close the Serial Port
        SerialPort1.Close()
    End Sub

End Class

沒有留言:

張貼留言