关于VB串口通讯MSCOMM控件的问题!急求程序!!!

2024-12-01 14:42:40
推荐回答(1个)
回答(1):

Option Explicit
Dim strInput As String
Dim strSend As String
Dim sum As Integer

Private Sub Command1_Click()
If MSComm1.PortOpen = False Then MSComm1.PortOpen = True
End Sub

Private Sub Form_Load()
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeText
MSComm1.RThreshold = 1
MSComm1.PortOpen = True
Timer1.Interval = 100 '控制发送延迟时间
Timer1.Enabled = False
End Sub

Private Sub MSComm1_OnComm()
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.InputLen = 0
strInput = strInput & MSComm1.Input
Text1 = strInput
If strInput = "Q" Then
strSend = "R"
strInput = ""
Timer1.Enabled = True
ElseIf Len(strInput) < 8 And strInput <> "R" Then
strSend = strInput
strInput = ""
'MSComm1.RThreshold = 8
Timer1.Enabled = True
Else ' Then
sum = sum + 8
Text2 = sum / 8
If sum >= 160 Then
strSend = "E"
'MSComm1.PortOpen = False '本句似乎可不用
sum = 0
Else
strSend = "C"
End If
strInput = ""
Timer1.Enabled = True
End If
End Select
End Sub

Private Sub Timer1_Timer()
If MSComm1.PortOpen = True Then
MSComm1.Output = strSend
Timer1.Enabled = False
End If
End Sub

补充:2进制接收
Option Explicit
Dim strInput As String
Dim strSend() As Byte
Dim sum As Integer
Dim strSj As String
Private Sub Command1_Click()
If MSComm1.PortOpen = False Then MSComm1.PortOpen = True
End Sub

Private Sub Form_Load()
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeBinary
'MSComm1.InputMode = comInputModeText
MSComm1.RThreshold = 1
MSComm1.PortOpen = True
Timer1.Interval = 100 '控制发送延迟时间
Timer1.Enabled = False
End Sub

Private Sub MSComm1_OnComm()
Dim buffer() As Byte
Dim i As Integer
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.InputLen = 0
buffer = MSComm1.Input
For i = 0 To UBound(buffer)
strInput = strInput & Right("0" & Hex(buffer(i)), 2)
Next
If Mid(strInput, 1, 2) = "51" Then
ReDim strSend(0)
strSend(0) = &H52
strInput = ""
Timer1.Enabled = True
ElseIf Len(strInput) < 16 And Mid(strInput, 1, 2) <> "51" Then
ReDim strSend(1 To Len(strInput) / 2)
For i = 1 To Len(strInput) Step 2
strSend((i + 1) / 2) = Val("&H" & Mid(strInput, i, 2))
Next
strInput = ""
Timer1.Enabled = True
Else ' Then
sum = sum + 8
Text2 = sum / 8
strSj = strSj & strInput '& vbCrLf
If sum >= 160 Then
ReDim strSend(0)
Text1 = strSj
'请进入数据处理代码,转换为ASCII字符号。
MSComm1.PortOpen = False '本句似乎可不用
strSend(0) = &H45
sum = 0
Else
ReDim strSend(0)
strSend(0) = &H43
End If
strInput = ""
Timer1.Enabled = True
End If
End Select
End Sub

Private Sub Timer1_Timer()
If MSComm1.PortOpen = True Then
MSComm1.Output = strSend
Timer1.Enabled = False
End If
End Sub