读书人

VB.NET 串口接收中断程序中 Timer控件

发布时间: 2012-09-08 10:48:07 作者: rapoo

VB.NET 串口接收中断程序中 Timer控件不能启动求助
Public Class Form1
Dim readcommand(1) As Byte
Dim receivefunction As Byte
Dim receivepointer As Integer
Dim receivedata(99) As Byte
Dim comtransmitdata(5) As Byte
Dim recdatabuf() As Byte
Dim writecommand(11) As Byte
Dim ensurecommand(1) As Byte
Dim AIW0 As Integer
Dim I0 As Byte
Dim ACC As Byte
Dim writeflag As Boolean

Dim graphics As Long
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False

readcommand(0) = &HA5
readcommand(1) = &HF0

ensurecommand(0) = &HB5
ensurecommand(1) = &HD0

SerialPort1.PortName = "COM1"
SerialPort1.BaudRate = 9600
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.DataBits = 8
SerialPort1.StopBits = IO.Ports.StopBits.One

SerialPort1.ReceivedBytesThreshold = 1
SerialPort1.ReadBufferSize = 256

SerialPort1.Open()

SerialPort1.Write(readcommand, 0, 2)
receivepointer = 0
writeflag = False

Label2.Text = Timer1.Interval
End Sub

Public Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim i As Integer
'Timer1.Enabled = False

For i = 0 To SerialPort1.BytesToRead - 1
receivedata(receivepointer) = SerialPort1.ReadByte
receivepointer = receivepointer + 1
Next

TextBox1.Text = System.Text.Encoding.Default.GetString(receivedata)
Timer1.Interval = 100
Timer1.Enabled = True

Label2.Text = Timer1.Interval
End Sub

Public Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'Timer1.Enabled = False

receivepointer = 0
Label1.Text = System.Text.Encoding.Default.GetString(receivedata)
TextBox1.Text = "SAFDDFDA"
End Sub


End Class






在程序接收到字符串后产生中断, 然后启动定时器 Timer1, 用来判断是否字符串结尾. 但Timer1在中断程序中不能启动.


[解决办法]
线程中操作 Timer1.Enabled = True 是不起作用的.
我的解决办法是 用建一个 start as Boolean 变量.
在程序启动时就将 Timer1.Interval = 100 时钟就开始循环了.

在Timer1_Tick里面判断
if(start = true)
-------执行你要执持的内容
endif



虽然你在启动的时候已经 Control.CheckForIllegalCrossThreadCalls = False
但是线程中操作控件的 启用关闭或者可视之类的还是有问题的.需要用别的办法解决.
[解决办法]

探讨

OK THANKS

读书人网 >VB Dotnet

热点推荐