我最近用.net自带的serialport类写的串口通信的程序。对方是一个电子称,我的是一个PDA(WINCE)。电子称随这重量不断变化,不断的通过串口向PDA发送数据。看起来就这么简单。由于连续的发数据,所以我要不段的读串口的数据。我使用了recevied的事件读取数据,可是我无法直接赋值给标签显示出来,如果通过函数赋值给标签显示,也显示不出动态的变化来,觉得很奇怪,VB里都没的问题,VB。net扎个就不行呢。
后来想出了这个办法,可不可行?
代码如下
使用两个timer轮番的打开和关闭串口,来接受和提取数据 一个关闭,一个又去打开
Public tmpstr As String
Public oldstr As String
Public bolview As Boolean = False
Public bolallclose As Boolean = False
‘打开串口
Private Sub btnOpenSerialPort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenSerialPort.Click
second.Enabled = False
Try
Timer1.Interval = Int(second.Text) ’设置时间好多秒
Timer2.Interval = Int(second.Text)
Catch ex As Exception
Timer1.Interval = 1000 ‘默认
Timer2.Interval = 1000
End Try
bolallclose = False
SerialPort1.PortName = "com1"
SerialPort1.DtrEnable = True
SerialPort1.RtsEnable = True
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.BaudRate = 1200
SerialPort1.DataBits = 8
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.Encoding = System.Text.Encoding.ASCII
SerialPort1.ReceivedBytesThreshold = 13
SerialPort1.ReadTimeout = 100
SerialPort1.WriteTimeout = 512
SerialPort1.ReadBufferSize = 13
SerialPort1.WriteBufferSize = 512
SerialPort1.Handshake = IO.Ports.Handshake.RequestToSendXOnXOff
SerialPort1.DiscardNull = True
If SerialPort1.IsOpen Then
Else
SerialPort1.Open()
End If
Timer1.Enabled = True
End Sub
Private Sub ThreadProcUnsafe()
Me.labelWeight.Text = tmpstr
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
’把接收到的数据给一全局变量string
tmpstr=xxxxx;‘代码省略
End Sub
Private Sub btnCloseSerialPort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCloseSerialPort.Click
If SerialPort1.IsOpen Then
SerialPort1.Close()
End If
bolallclose = True
second.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If bolallclose Then
Timer1.Enabled = False
Timer2.Enabled = False
If SerialPort1.IsOpen Then
SerialPort1.Close()
labelWeight.Text = "close"
Timer2.Enabled = False
Else
labelWeight.Text = "close"
End If
End If
If SerialPort1.IsOpen Then
Timer1.Enabled = False
Else
SerialPort1.Open()
Timer2.Enabled = True
End If
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If bolallclose Then
Timer1.Enabled = False
Timer2.Enabled = False
If SerialPort1.IsOpen Then
SerialPort1.Close()
labelWeight.Text = "close"
Timer2.Enabled = False
Else
labelWeight.Text = "close"
End If
End If
If oldstr <> tmpstr Then
oldstr = tmpstr
labelWeight.Text = oldstr
If Not SerialPort1.IsOpen Then
SerialPort1.Close()
End If
Timer1.Enabled = True
Else
labelWeight.Text = oldstr
End If
End Sub
这个代码反复的打开串口稳定吗?
读数据速度会受到时间设置的限制
写成线程该如何写,我没查到