Thursday, 16 April 2015

VB.NET :: Komunikasi Serial Com Port dengan VB.Net (PENERIMA)


Berikut ini adalah komponen-komponen yang digunakan :
  1. ComboBox (2 buah)
  2. Button (2 buah)
  3. Label (3 buah)
  4. TextBox (1 buah)
  5. SerialPort (1 buah)
Buat tampilan program menjadi seperti gambar dibawah ini.
terima serial
Berikut ini adalah program lengkapnya.
Public Class Form1
    Dim myPort As Array
    Delegate Sub SetTextCallback(ByVal As String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        myPort = IO.Ports.SerialPort.GetPortNames()
        ComboBox2.Items.Add(9600)
        ComboBox2.Items.Add(19200)
        ComboBox2.Items.Add(38400)
        ComboBox2.Items.Add(57600)
        ComboBox2.Items.Add(115200)
        For i = 0 To UBound(myPort)
            ComboBox1.Items.Add(myPort(i))
        Next
        ComboBox1.Text = ComboBox1.Items.Item(0)
        ComboBox2.Text = ComboBox2.Items.Item(0)
        Button1.Enabled = True
        Button2.Enabled = False
    End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SerialPort1.PortName = ComboBox1.Text
        SerialPort1.BaudRate = ComboBox2.Text
        SerialPort1.Open()
        Button1.Enabled = False
        Button2.Enabled = True
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        SerialPort1.Close()
        Button1.Enabled = True
        Button2.Enabled = False
    End Sub
Private Sub ReceivedText(ByVal As String)        ‘compares the ID of the creating Thread to the ID of the calling Thread
        If Me.TextBox1.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
        Else
            ‘Me.TextBox2.Text = ” “
            Me.TextBox1.Text =
          End If    End Sub
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        ‘Automatically called every time a data is received at the serialPort
        ReceivedText(SerialPort1.ReadExisting())
    End Sub
End Class
Untuk menguji program, kita dapat menggunakan Program Pengirim yang sudah dibahas pada artikel sebelumnya atau bisa juga menggunakan Virtual Terminal.

No comments:

Post a Comment