帮忙解释一下VB小程序
本帖最后由 bcrun 于 2012-12-11 19:59:02 编辑 谁能帮忙解释一下下面的vb代码,越详细越好!总体是通过的串口控件,读取485串口中ABC三相的电流和电压值
本人初学,最好一句一句解释一下,在这里先谢谢高手了!
Dim rsend(5) As Byte
Dim send(7) As Byte
Dim buf(33) As Variant
Dim Jyh0 As Byte
Dim Jyh1 As Byte
Dim ValCRC As Long
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Public Function CRC(Brr() As Byte) As Long
Dim i As Integer, j As Integer
Dim TempVal As Long
Dim YWval As Long
Dim LSB As Integer
TempVal = &HFFFF&
For i = 0 To UBound(Brr())
TempVal = TempVal Xor Brr(i)
For j = 1 To 8
YWval = Int(TempVal / 2)
LSB = TempVal Mod 2
If LSB = 1 Then
YWval = YWval Xor &HA001&
End If
TempVal = YWval
Next j
Next i
CRC = TempVal Mod 65536
End Function
Private Sub Command1_Click()
MSComm1.CommPort = Text1.Text
MSComm1.Settings = "4800,N,8,1"
MSComm1.InputMode = comInputModeBinary
MSComm1.InputLen = 1
MSComm1.RThreshold = 33
MSComm1.PortOpen = True
End Sub
Private Sub Command11_Click()
rsend(0) = Text2.Text
rsend(1) = &H4
rsend(2) = 0
rsend(3) = 0
rsend(4) = 0
rsend(5) = &HD
ValCRC = CRC(rsend)
Jyh0 = ValCRC Mod 256
Jyh1 = Int(ValCRC / 256)
send(0) = rsend(0)
send(1) = rsend(1)
send(2) = rsend(2)
send(3) = rsend(3)
send(4) = rsend(4)
send(5) = rsend(5)
send(6) = Jyh0
send(7) = Jyh1
MSComm1.Output = send
End Sub
Private Sub Command2_Click()
MSComm1.PortOpen = False
End Sub
Private Sub MSComm1_OnComm()
Dim k As Integer
Dim a As Integer
Dim s As Double
Dim rbuff(4) As Byte
For a = 0 To 33
buf(a) = MSComm1.Input
Next a
'A相电流值
k = buf(5)(0) + buf(4)(0) * 256
Text3.Text = k / 1000
'B相电流值
k = buf(7)(0) + buf(6)(0) * 256
Text4.Text = k / 1000
'C相电流值
k = buf(9)(0) + buf(8)(0) * 256
Text5.Text = k / 1000
'A相电流相位
k = buf(11)(0) + buf(10)(0) * 256
k = 65535 - k
s = k / 10000
Text6.Text = s
'B相电流相位
k = buf(13)(0) + buf(12)(0) * 256
k = 65535 - k
s = k / 10000
Text7.Text = s
'C相电流相位
k = buf(15)(0) + buf(14)(0) * 256
k = 65535 - k
s = k / 10000
Text8.Text = s
End Sub
rsend(0) = Text2.Text //给rsend数组每个元素赋值
rsend(1) = &H4
rsend(2) = 0
rsend(3) = 0
rsend(4) = 0
rsend(5) = &HD
ValCRC = CRC(rsend) //计算crc
Jyh0 = ValCRC Mod 256 //crc值低字节
Jyh1 = Int(ValCRC / 256) //crc值高字节
send(0) = rsend(0) //将rsend数据复制到send数组
send(1) = rsend(1)
send(2) = rsend(2)
send(3) = rsend(3)
send(4) = rsend(4)
send(5) = rsend(5)
send(6) = Jyh0 //添加入crc值
send(7) = Jyh1
MSComm1.Output = send //通过串口发送出去
End Sub
[解决办法]
我也建议楼主先去找本端口协议的书看看吧~