从串口到网口编程

wuyuzhulpp wuyuzhulpp 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
以前一直用的是串口和机器进行通信,现在发现串口速度有点慢,所以就用网口通信了,但是试了下来还是比较慢
应该是我的通信方法不对,请大神看看

‘‘这个是向机器查询指定寄存器里的数据的,主要速度就卡在ns.Read这个函数上。
‘以前串口的思路是每发一个指令等到机器返回结果后,然后再发吓一跳指令,不知道网卡是不是这样子的?
Public Function ReadD(ByVal Address As String, ByRef ReceiveData As Int16) As Byte
Dim strCmd As String = vbNullString
Dim result As String = vbNullString
Dim result1 As String = vbNullString
Dim bCmd() As Byte
Dim bResult(Me.ReceiveBufferSize) As Byte
If Not Me.Connected Then Return 1
If Me Is Nothing Then Return 2
If Address.Length < 5 Then Address = Address.PadLeft(5, "0")
strCmd = "<" & mStation & "#RDD" & Address & Address
strCmd = strCmd & BCC(strCmd) & vbcr
bCmd = Encoding.ASCII.GetBytes(strCmd)
Static br As New IO.BinaryReader(ns)
Static bw As New IO.BinaryWriter(ns)

Try
ns.Write(bCmd, 0, bCmd.Length)
ns.Read(bResult, 0, 64)
result = Encoding.ASCII.GetString(bResult)
If result.Contains("$") Then
result1 = result.Substring(8, 2) & result.Substring(6, 2)
ReceiveData = Convert.ToInt16(result1, 16)
Return 0
Else
Return 5
End If
Catch e As SocketException
Return 4
End Try
Return 1
End Function


'这个是后台线程,用来查询地址2000里的数据,DT2000是返回的数据,SW是StopWatch
现在这个轮询周期比较长,SW的值是100ms这样,这样和串口没啥区别了
Private Sub pM()
While flag = 1
sw.Reset()
sw.Start()
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))
fpe.ReadD("2000", dt2000(0))

t = sw.ElapsedMilliseconds
Threading.Thread.Sleep(1)
End While

End Sub





...全文
评论 5
收藏 已收藏
分享
返回顶部
wuyuzhulpp
VB 16,718 成员 110,520 内容