本系統以PC對基于PLC的交通燈控制系統的監控為例,在上位機與PLC正常通信的前提下,設計如下界面。窗體的內容主要包括,四大區:端口、站號選擇區,設定時間輸入區,監控顯示區,控制按紐區。從站號選擇區選擇不同站號即不同PLC,實現對多個PLC的實時監控。
3.1 串口初始化程序
If MSComm1.PortOpen <> True Then
MSComm1.PortOpen=True
End If
MSComm1.Settings=“9600,E,7,2”
MSComm1.InputLen=0
MSComm1.InBufferCount=0
MSComm1.InputMode=comInputModeText
MSComm1.Handshaking=comNone
3.2 計算機與PLC通信的VB程序
Public Function ReadData(ByVal InputStr As String, ByVal Num1 As Integer, ByVal Num2 As Integer) As String
Dim OutputStr As String
Dim InString As String
Dim ReturnStr As String
Dim EndString As String
Dim FCSString As String
Dim ReturnFCSString As String
Form1.MSComm1.InBufferCount=0
OutputStr=InputStr+FCS(InputStr)+“*”
If Form1.MSComm1.PortOpen=True Then
Form1.MSComm1.Output=OutputStr+Chr$(13)’按照PLC幀格式輸出
End If
Do
DoEvents
Loop Until Form1.MSComm1.InBufferCount >=Num2’返回幀的長度
InString=Form1.MSComm1.Input
EndString=Mid$(InString,6,2)’取返回幀的響應碼
If EndString <> “00”Then
ReadData=“Error”
Exit Function
End If
EndString=Mid$(InString,1,Len(InString)-4)
ReturnFCSString=Mid$(InString, Len(InString) -3,2)’取返回幀校驗碼
FCSString=FCS(EndString)
If FCSString <> ReturnFCSString Then
ReadData=“Error”
Exit Function
End If
If Len(InString)>=Num2 Then
ReturnStr=Mid$(InString, Len(InString)-Num1-3, Num1)’取返回幀的數據,其度為Num1
ReadData = ReturnStr
End If
End Function