vb关于数据发送与接收的问题

2025-12-25 11:23:13
推荐回答(1个)
回答1:

Dim datatemp(1000) As Single
Dim num As Integer
Private Sub cmdquit_Click()
Unload Me
End Sub
Private Sub form_queryunload(cancel As Integer, unloadmode As Integer)
MSComm1.PortOpen = False
End Sub

Private Sub cmdstart_Click()
Timer1.Enabled = True
End Sub

Private Sub cmdstop_Click()
Timer1.Enabled = False
End Sub

Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.InputMode = comInputModeBinary
MSComm1.RThreshold = 1
MSComm1.SThreshold = 1
MSComm1.Settings = "9600,n,8,1"
MSComm1.PortOpen = True
Call tabinit
End Sub

Private Sub MSComm1_OnComm()
Dim inbyte() As Byte
Dim buffer As String
Dim datatemp2a, datatemp2b As String
Dim datatemp2 As String
If num > 199 Then Call renew
Select Case MSComm1.CommEvent
Case comEvReceive
inbyte = MSComm1.Input
For i = LBound(inbyte) To UBound(inbyte)
buffer = buffer + Hex(inbyte(i)) + Chr(32)
Next i
Case comEvSend
End Select
If Len(Trim(Mid(buffer, 1, 2))) = 1 Then
datatemp(num) = Val("&h" & Mid(buf, 3, 2) & Str("0") & Mid(buffer, 1, 2)) * 0.1
Else
datatemp(num) = Val("&h" & Mid(buffer, 3, 2) & Mid(buffer, 1, 2)) * 0.1
End If
If Len(Trim(Mid(buffer, 1, 2))) = 1 Then
datatemp2a = Str("0") & Trim(Mid(buffer, 1, 2))
Else
datatemp2a = Mid(buffer, 1, 2)
End If
If Len(Trim(Mid(buffer, 3, 2))) = 1 Then
datatemp2b = Str("0") & Trim(Mid(buffer, 3, 2))
Else
datatemp2b = Mid(buffer, 3, 2)
End If
datatemp2 = datatemp2a & "" & datatemp2b
If datatemp(num) <> 0 Then
Grid.Col = 1: Grid.Row = num = 1
Grid.Text = Format$(datatemp(num), "0.0")
temptext = Format$(datatemp(num), "0.0")
text2.Text = datatemp2
num = num + 1
Call cal
Call draw
End If
End Sub
Sub cal()
On Error GoTo hh
Sum = 0
Max = datatemp(0): Min = Max
For i = 0 To num - 1
If datatemp(i) >= Max Then Max = datatemp(i)
If detatemp(i) <= Min Then Min = datatemp(i)
Sum = Sum + datatemp(i)
Next i
aver = Sum / num
maxtext.Text = Format$(Max, "0.0")
mintext.Text = Format$(Min, "0.0")
avertext.Text = Format$(aver, "0.0")
hh: Exit Sub
End Sub
Private Sub draw()
Picture1.Cls
Picture1.DrawWidth = 1
Picture1.BackColor = QBColor(5)
Picture1.Scale (0, 50)-(200, 0)
For i = 1 To num - 1
X1 = (i - 1): Y1 = datatemp(i - 1)
X2 = i: Y2 = datatemp(i)
Picture1.Line (X1, Y1)-(X2, Y2), QBColor(0)
Next i
End Sub
Private Sub renew()
If num = 0 Then Exit Sub
temptext.Text = "": avertext.Text = ""
mintext.Text = "": maxtext.Text = ""
Grid.Clear
Picture1.Cls
For i = 0 To num - 1
datatemp(i) = 0
Next i
num = 0
Call tabinit
End Sub
Public Sub tabinit()
Grid.Cols = 2
Grid.Rows = 200 + 1
Grid.ColWidth(0) = 700: Grid.ColWidth(1) = 950
Grid.Col = 0
For i = 1 To 200
Grid.Row = i: Grid.Text = "" + Str$(i)
Next i
Grid.Row = 0
Grid.Col = 0: Grid.Text = "序号"
Grid.Col = 1: Grid.Text = "温度值"
Grid.TopRow = 1
Grid.LeftCol = 1
End Sub

Private Sub Timer1_Timer()
MSComm1.Output = Chr(&H8282) & Chr(&H52) & Chr(&HC)
End Sub