以下是引用ZHTOK在2014/10/10 8:42:33的发言:
重点:看看vb与通讯的部分,弄到熟悉的程度。
'在窗体的Load事件中加入下列代码对串口进行初始化:
Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.InputMode = 1
MSComm1.RThreshold = 1
MSComm1.SThreshold = 1
MSComm1.Settings = "9600,E,8,1"
MSComm1.PortOpen = True
End Sub
'向S7-200PLC发送读指令,读取寄存器VW100中的数据,发送指令:
'68 1B 1B 68 02 00 6C 32 01 00 00 00 00 00 0E 00 00 04 01 12 0A 10 04 00 01 00 01 84 00 03 20 8D 16
'PLC返回数据 E5 后,发确认命令:10 02 00 5C 5E 16
'PLC返回数据68 17 17 68 00 02 08 32 03 00 00 00 00 00 02 00 06 00 00 04 01 FF 04 00 10 50 E1 90 16
'其中第25字节如50和第26字节E1就反映输入电压值
Private Sub Timer1_Timer()
Dim temp As String
Dim arr() As Byte
Dim n As Integer
Dim temp1 As String
Dim arr1() As Byte
Dim n1 As Integer
Dim Inbyte() As Byte
Dim Inbyte1() As Byte
Dim data(10) As String '电压值16进制各位
Dim datan As Long '电压值的数字量形式
Dim dataV As Single '电压实际值
bz = bz + 1
If bz = 1 Then
temp = "681B1B6802006C320100000000000E00000401120A100400010001840003208D16"
n = Len(temp) \ 2 - 1
ReDim arr(n)
For i = 0 To n
arr(i) = Val("&H" & Mid(temp, i * 2 + 1, 2))
Next i
MSComm1.Output = arr '发送读指令
End If
If bz = 2 Then
Inbyte = MSComm1.Input '读取返回数据串"E5"
temp1 = "1002005C5E16"
n1 = Len(temp1) \ 2 - 1
ReDim arr1(n1)
For i = 0 To n1
arr1(i) = Val("&H" & Mid(temp1, i * 2 + 1, 2))
Next i
'PLC返回数据 E5 后,确认写入命令,发送以下数据:10 02 00 5C 5E 16
If Hex(Inbyte(0)) = "E5" Then
MSComm1.Output = arr1 '发送确认指令
End If
End If
If bz = 3 Then
Inbyte1 = MSComm1.Input '读取返回数据串
T16.Text = Hex(Inbyte1(25)) & Hex(Inbyte1(26)) '取电压值的16进制(第25和第26字节)
'取电压16进制值各位
If Len(Hex(Inbyte1(25))) = 1 Then
data(1) = "0": data(2) = Mid(Hex(Inbyte1(25)), 1, 1)
Else
data(1) = Mid(Hex(Inbyte1(25)), 1, 1): data(2) = Mid(Hex(Inbyte1(25)), 2, 1)
End If
If Len(Hex(Inbyte1(26))) = 1 Then
data(3) = "0": data(4) = Mid(Hex(Inbyte1(26)), 1, 1)
Else
data(3) = Mid(Hex(Inbyte1(26)), 1, 1): data(4) = Mid(Hex(Inbyte1(26)), 2, 1)
End If
datan = Val("&H" & data(1)) * (16 ^ 3) + Val("&H" & data(2)) * (16 ^ 2) + _
Val("&H" & data(3)) * (16 ^ 1) + Val("&H" & data(4)) * (16 ^ 0) '计算电压10进制值
Tdata.Text = Str(datan)
dataV = datan / 3200 '0-10V为3200 0-5V为6400
Tv.Text = Format(dataV, "0.00")
bz = 0
End If
End Sub
'当退出程序时,关闭串行口
Private Sub Cmdquit_Click()
MSComm1.PortOpen = False '关闭串口
Unload Me
End Sub
代码看不懂, 程序示例是读取VW100中的数值, 如果还要读取VW102呢?