'在窗体的Load事件中加入下列代码对串口进行初始化:
Private Sub Form_Load()
MSComm1.CommPort = 1 ' 设置通信端口号为COM1
MSComm1.InputMode = 1 ' 接收二进制型数据
MSComm1.RThreshold = 1 ' 设置并返回要接收的字符数
MSComm1.SThreshold = 1 ' 设置并返回发送缓冲区中允许的最小字符数
MSComm1.Settings = "9600,E,7,1" ' 设置串口1通信参数
MSComm1.PortOpen = True ' 打开通信端口1
Timer1.Enabled = False
End Sub
'向PLC发送指令:02 30 31 30 30 30 32 30 03 35 36,功能是从D0开始读取32个字节数据
Private Sub Cmdsend_Click()
MSComm1.Output = Chr(&H2) & Chr(&H30) & Chr(&H31) & Chr(&H30) & Chr(&H30) & Chr(&H30) & Chr(&H32) & Chr(&H30) & Chr(&H3) & Chr(&H35) & Chr(&H38)
Timer1.Enabled = True
End Sub
'获得各输入端口状态
Private Sub Timer1_Timer()
Dim Inbyte() As Byte
Dim buffer As String
ReDim Inbyte(100)
Inbyte = MSComm1.Input '返回的数据串
For i = LBound(Inbyte) To UBound(Inbyte)
buffer = buffer + Hex(Inbyte(i)) + Chr(32)
Next i
'Text1.Text = buffer '显示返回的数据串,需自己添加TextBox
If Hex(Inbyte(2)) = "31" Then '31表示触点闭合
Shape1(0).FillColor = QBColor(12)
Else '30表示触点断开
Shape1(0).FillColor = QBColor(10)
End If
If Hex(Inbyte(6)) = "31" Then
Shape1(1).FillColor = QBColor(12)
Else
Shape1(1).FillColor = QBColor(10)
End If
If Hex(Inbyte(10)) = "31" Then
Shape1(2).FillColor = QBColor(12)
Else
Shape1(2).FillColor = QBColor(10)
End If
If Hex(Inbyte(14)) = "31" Then
Shape1(3).FillColor = QBColor(12)
Else
Shape1(3).FillColor = QBColor(10)
End If
If Hex(Inbyte(18)) = "31" Then
Shape1(4).FillColor = QBColor(12)
Else
Shape1(4).FillColor = QBColor(10)
End If
If Hex(Inbyte(22)) = "31" Then
Shape1(5).FillColor = QBColor(12)
Else
Shape1(5).FillColor = QBColor(10)
End If
If Hex(Inbyte(26)) = "31" Then
Shape1(6).FillColor = QBColor(12)
Else
Shape1(6).FillColor = QBColor(10)
End If
If Hex(Inbyte(30)) = "31" Then
Shape1(7).FillColor = QBColor(12)
Else
Shape1(7).FillColor = QBColor(10)
End If
If Hex(Inbyte(34)) = "31" Then
Shape1(8).FillColor = QBColor(12)
Else
Shape1(8).FillColor = QBColor(10)
End If
If Hex(Inbyte(38)) = "31" Then
Shape1(9).FillColor = QBColor(12)
Else
Shape1(9).FillColor = QBColor(10)
End If
If Hex(Inbyte(42)) = "31" Then
Shape1(10).FillColor = QBColor(12)
Else
Shape1(10).FillColor = QBColor(10)
End If
If Hex(Inbyte(46)) = "31" Then
Shape1(11).FillColor = QBColor(12)
Else
Shape1(11).FillColor = QBColor(10)
End If
If Hex(Inbyte(50)) = "31" Then
Shape1(12).FillColor = QBColor(12)
Else
Shape1(12).FillColor = QBColor(10)
End If
If Hex(Inbyte(54)) = "31" Then
Shape1(13).FillColor = QBColor(12)
Else
Shape1(13).FillColor = QBColor(10)
End If
If Hex(Inbyte(58)) = "31" Then
Shape1(14).FillColor = QBColor(12)
Else
Shape1(14).FillColor = QBColor(10)
End If
If Hex(Inbyte(62)) = "31" Then
Shape1(15).FillColor = QBColor(12)
Else
Shape1(15).FillColor = QBColor(10)
End If
Timer1.Enabled = False
End Sub
'当退出程序时,关闭串行口
Private Sub Cmdquit_Click()
MSComm1.PortOpen = False '关闭串口
Unload Me
End Sub
// 读不到PLC 输入点,下标越界,望高手指点修改