用VB编写的一个计算机RS232串口收发的小程序,已试验成功,跟大家分享一下
Option ExplicitDim buffer As String
Dim tr As String
Dim st As String
Dim er As Byte
Dim fir As String
Dim sec As String
Dim i, j, k, m, n As Integer
Dim p As String
Private Sub form_Load()
With Comboduankou
.AddItem "COM1"
.AddItem "COM2"
.AddItem "COM3"
.AddItem "COM4"
.AddItem "COM5"
.AddItem "COM6"
.ListIndex = 0
End With
= Comboduankou.ListIndex + 1
MSComm.Settings = "9600,N,8,1"
MSComm.InputMode = comInputModeText
MSComm.RThreshold = 9
MSComm.SThreshold = 1
If MSComm.PortOpen = False Then
MSComm.PortOpen = True
End If
If MSComm.PortOpen = True Then
Shape1.BorderColor = vbRed
Else
Shape1.BorderColor = vbGreen
End If
MsgBox "串口设定:传输速率9600,校验位N,数据位8,停止位1,请确认!"
Option1.Value = True
End Sub
Private Sub form_unload(Cancel As Integer)
If MSComm.PortOpen Then
MSComm.PortOpen = False
End If
End Sub
Private Sub clearreceive_Click()
Textreceive = vbNullString
End Sub
Private Sub clearsend_Click()
Textsend = vbNullString
End Sub
Private Sub MSComm_OnComm()
Select Case
Case comEvReceive
MSComm.InputMode = 0
buffer = MSComm.Input
End Select
If buffer <> vbNullString Then
Textreceive = Textreceive & buffer & Chr(13) & Chr(10)
End If
End Sub
Private Sub send_Click()
tr = Textsend.Text
If tr <> vbNullString Then
tr = Trim(tr)
Else
MsgBox "请输入要发送的数据!"
End If
If Option2.Value = True Then
MSComm.Output = tr
Else
i = Len(tr)
If i Mod 2 <> 0 Then
MsgBox "请注意输入偶数个字符!"
End If
For j = 1 To i - 1 Step 2
st = Mid(tr, j, 2)
fir = Left(st, 1)
m = Asc(fir)
If 47 < m And m < 58 Then
m = m - 48
ElseIf 64 < m And m < 71 Then
m = m - 55
ElseIf 96 < m And m < 103 Then
m = m - 87
Else
MsgBox "输入有误!"
End If
sec = Right(st, 1)
n = Asc(sec)
If 47 < n And n < 58 Then
n = n - 48
ElseIf 64 < n And n < 71 Then
n = n - 55
ElseIf 96 < n And n < 103 Then
n = n - 87
Else
MsgBox "输入有误!"
End If
er = m * 16 + n
p = Chr(er)
MSComm.Output = p
Text1.Text = p
Next
End If
End Sub