การเชื่อมต่อ rs232 หรือ serial port โดยใช้ vb2005
สร้าง Form1 ให้มี ปุ่ม 2 ปุ่ม
ปุ่มแรกชื่อ btnSend
ปุ่ม 2 ชื่อ btnClear
และสร้าง RichTextBox 2 อัน
อันแรกชื่อ txtSent อันที่ txtReceived
สร้าง Module1 ขึ้นมา แล้วใช้ code ตามนี้
Module Module1
Public Const xStartFrame = &H2 ‘@0×02
Public Const xStopFrame = &H5E ‘^
Public Const xCheckFrame = &HC6 ‘Protocal of Board RS232=&HB6
Public BTx(99) As Byte
Public BRx(99) As Byte
Public ReadBuf As String
Public index As Byte
Public inNo As Integer
Public x As Byte
Public Sub SendTx()
Dim i As Integer
Form1.SerialPort1.Write(BTx, 0, UBound(BTx) + 1)
For i = 0 To UBound(BTx)
Form1.txtSent.Text = Form1.txtSent.Text & “/” & Hex(BTx(i))
Call delay(30000)
Next i
End Sub
Public Sub delay(ByVal wait As Long)
Dim i As Long
For i = 0 To wait
Next i
End Sub
End Module
แล้วสำหรับ Form1 ใช้ code นี้
Public Class Form1
Dim inNo As Integer
Dim ReadBuf As String
Dim index As Byte
Dim BRx(99) As Byte
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Me.SerialPort1.IsOpen Then Me.SerialPort1.Close()
Me.SerialPort1.Open()
Me.SerialPort1.BaudRate() = 9600
Me.SerialPort1.DiscardOutBuffer() ‘clear output buffer
Me.SerialPort1.DiscardInBuffer() ‘clear input buffer
Me.SerialPort1.RtsEnable = True
Me.SerialPort1.DtrEnable = True
Timer1.Enabled = True
Timer1.Interval = 2
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim i As Integer
inNo = SerialPort1.BytesToRead
If inNo = 0 Then Exit Sub
For i = 1 To inNo
BRx(index) = SerialPort1.ReadByte
Me.txtReceived.Text = Me.txtReceived.Text & “/” & Hex(BRx(index))
index = index + 1
Next i
index = 0
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim i As Integer
ReDim BTx(7)
BTx(0) = xStartFrame ‘Start 0×02
BTx(1) = &HC6 ‘Check 0xC6
BTx(2) = &H10 ‘Command 0×108F
BTx(3) = &H8F
BTx(4) = &H1 ‘Len 0×01
BTx(5) = &H3 ‘Data 0×03
For i = 1 To 6
BTx(i) = BTx(i) Xor BTx(i + 1)
Next i
BTx(7) = xStopFrame
Call SendTx()
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
Me.txtSent.Text = “”
Me.txtReceived.Text = “”
End Sub
End Class
เวลา Test ให้ short ขา 2กับ3 ของ serial port แล้วลองกดปุ่ม Send ดู ถ้ามี ข้อความขึ้นที่ txtReceived ตรงกับที่ txtSent ขึ้นก็แสดงว่า serial port ถูกแล้ว ใช้งานได้เป็นปกติ
ความเห็นล่าสุด