Berikut Contoh desain formnya ya:
Public Class Form1
Dim readBuffer As String
Private Sub SendBtn_Click(sender As Object, e As EventArgs) Handles SendBtn.Click
Try
SerialPort1.Write(TextBox1.Text + Environment.NewLine)
TextBox3.AppendText(">" + TextBox1.Text + Environment.NewLine)
TextBox3.ScrollToCaret()
TextBox1.Text = String.Empty
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim portName() As String
Dim i As Integer
Try
portName = System.IO.Ports.SerialPort.GetPortNames()
For i = 0 To i >= (portName.Length)
ComList.Items.Add(portName(i))
Next i
ComList.SelectedText = ComList.Items(0)
disBtn.Enabled = False
Catch ex As Exception
MsgBox("Belum Ada Serial Port Aktif, Silahkan Cek Koneksi Serial Anda")
End Try
Private Sub ConBtn_Click(sender As Object, e As EventArgs) Handles ConBtn.Click
If SerialPort1.IsOpen Then
SerialPort1.Close()
End If
Try
With SerialPort1
.PortName = ComList.Text
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Open()
End With
Label1.Text = ComList.Text + " Connected"
ConBtn.Enabled = False
disBtn.Enabled = True
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub disBtn_Click(sender As Object, e As EventArgs) Handles disBtn.Click
Try
SerialPort1.DiscardInBuffer() 'mengosongkan input buffer
SerialPort1.Close()
ConBtn.Enabled = True
disBtn.Enabled = False
Label1.Text = " Disconnected"
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
''' <summary>
''' async read on secondary thread
''' </summary>
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles SerialPort1.DataReceived
If SerialPort1.IsOpen Then
Try
readBuffer = SerialPort1.ReadLine()
'data to UI thread
Me.Invoke(New EventHandler(AddressOf DoUpdate))
Catch ex As Exception
MsgBox("read " & ex.Message)
End Try
End If
End Sub
''' <summary>
''' update received string in UI
''' ini subrutine tambahan
''' </summary>
Public Sub DoUpdate(ByVal sender As Object, ByVal e As System.EventArgs)
Dim temp As Decimal
temp = CInt(readBuffer) / 1024 * 5 * 100
TextBox2.Text = Int(temp)
TextBox4.Text = CInt(readBuffer)
End Sub
End Class
Sumber referensi:
http://students.netindonesia.net/blogs/sapikuda/archive/2012/07/25/membuat-program-koneksi-ke-plc-menggunakan-c.aspx
http://code.msdn.microsoft.com/windowsdesktop/SerialPort-Sample-in-VBNET-fb040fb2
http://msdn.microsoft.com/en-us/library/vstudio/s2dy91zy.aspx
No comments:
Post a Comment