天天看點

序列槽異步調用方法

Imports System.Text

Public Class Form1

    Dim buffB(17) As Byte     '序列槽接收緩沖區

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.BaudRate = 9600 '波特率設定

        SerialPort1.PortName = "COM1" '端口設定

        SerialPort1.DataBits = 7
        SerialPort1.StopBits = IO.Ports.StopBits.Two

        SerialPort1.Parity = IO.Ports.Parity.Even
        SerialPort1.ReceivedBytesThreshold = 1
        SerialPort1.Encoding = Encoding.ASCII

        If SerialPort1.IsOpen = False Then SerialPort1.Open() '打開序列槽
    End Sub


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

        SerialPort1.Read(buffB, 0, SerialPort1.BytesToRead)

        BeginInvoke(New EventHandler(AddressOf ReadFun), SerialPort1.BytesToRead()) '接收字元串

    End Sub

    Private Sub ReadFun(ByVal sender As System.Object, ByVal e As System.EventArgs)

        TextBox1.Text = TextBox1.Text & Encoding.ASCII.GetString(buffB) & Environment.NewLine   '顯示

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        SerialPort1.Write("1234567890123456")

    End Sub
End Class