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
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