vb中的通讯中的指令,vb.net中如何修改
下段程序段是VB和OMRON PLC通讯的例子,转换到vb.net中,必须引用vb6.0后,Timer才能使用,如果不想引用vb6.0
的话,应该如何修改
Public Function read_DM(ByVal startAddress As String, ByVal Lengh As Integer, ByRef value As String)
Dim outstring As String
Dim Lengh1 As String
MSComm1.InBufferCount = 0 'clear off inbuffer
Order = UCase(Order) '命令大写
keyorder = startAddress '首地址
Lengh1 = four_bit(Lengh)
outstring = "@" + "00" + "RD" + keyorder + Lengh1
fcdd$ = XORR(outstring)
outstring = outstring + fcdd$ + "*" + Chr$(13)
MSComm1.Output = outstring
Time_out = Timer
'判断通讯错误
Do
If Timer > (Time_out + 1) Then
ERROR_COM = True
Else
ERROR_COM = False
End If
DoEvents
Loop Until ((MSComm1.InBufferCount >= 11 + 4 * Lengh) Or (ERROR_COM = True))
Instring = MSComm1.Input
order1 = Mid(Instring, 6, 2) '结束码
Call ErrMessage(order1)
value = Mid(Instring, 8, 4 * Lengh)
End Function
在VB。net中,必须先
Imports VB = Microsoft.VisualBasic
For i = 1 To ReadNum
startaddress = address + (i - 1) * 20
startaddress = Four_Bit(startaddress)
outstring = "@" & "00" & "RD" & startaddress & "0020"
fcdd = XORR(outstring)
outstring = outstring & fcdd & "*" & Chr(13)
MSComm1.Output = outstring
Time_out = VB.Timer()
'判断通讯错误
Do
If VB.Timer() > (Time_out + 1) Then
ERROR_COM = True
Else
ERROR_COM = False
End If
System.Windows.Forms.Application.DoEvents()
Loop Until ((MSComm1.InBufferCount >= 11 + 20 * 4) Or (ERROR_COM = True))
[解决办法]
vb6的timer就是累计当天的秒数。
Timer可以用
CInt((DateTime.Now-DateTime.Today).TotalSeconds)
替代。就不需要用Timer方法了。
[解决办法]
vb.net下,其实只要在开始时记录一下开始时间,然后一直用当前时间减去开始时间,来获取通讯时间就可以判断超时了.并不一定要死抱着timer不放,代码从vb6迁移到vb.net时,要更灵活.
另外串口通讯在.net下有SerialPort类支持(.net 2.0后),他的性能完全优于mscomm控件,且自带的同步读取带有超时控制项,异步方式也可以通过其他方式来实现超时.只不过改写起来,代码变动会稍大一些,不过还是推荐的.毕竟一直死抱着vb6的控件,也不是件好事.