16,555
社区成员
发帖
与我相关
我的任务
分享
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
If SerialPort1.ReceivedBytesThreshold = 7 Then
SyncLock threadlock
getdatastr = (SerialPort1.ReadTo("E"))
End SyncLock
End If
end sub
Public Class GetGPS
Private Form_R As Form1
Public Sub New(ByVal myForm As Form1)
Form_R = myForm
End Sub
Public Sub run()
Form_R.Invoke(Form_R.myDelegate_GPS)
End Sub
'主程序
Delegate Sub R_Change()
Public myDelegate_GPS As R_Change
Private myThread_GPS As Thread
Dim mythread_AS As Thread '报警子线程
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
'委托数据处理过程
myDelegate_GPS = New R_Change(AddressOf R_GPS)
End Sub
'启动测量
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
SerialPort1.DiscardInBuffer()
'启动报警子线程
ThreadFunction_AS()
'启动数据处理线程
myThread_GPS = New Thread(New ThreadStart(AddressOf Threadfunction_Change))
myThread_GPS.Start()
'命令单片机开始发数
SerialPort1.Write(start_command, 0, 1)
R_stop = 0
End Sub
'主程序数据接收
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim temp As Byte
'开机设置为1
If SerialPort1.ReceivedBytesThreshold = 1 Then
temp = SerialPort1.ReadByte
'如果接收到测量开始返回值,改变缓冲区字节数为7,单片机对命令有个单字节反馈
If temp = &H3D Then
SerialPort1.ReceivedBytesThreshold = 7
'发完&H3D单片机就开始发送7个字节的数据,以"E"结尾
If SerialPort1.ReceivedBytesThreshold = 7 Then
'窗体变量
getdatastr = (SerialPort1.ReadTo("E"))
End If
End Sub
'报警声音线程,跟这个问题没什么关系,但是既然问了线程的问题,也请达人看看有什么可以优化的地方吗
Private Sub ThreadFunction_AS()
mythread_AS = New Thread(New ThreadStart(AddressOf DoScanThread))
mythread_AS.Start() '开始线程
End Sub
Public Sub DoScanThread()
Do While R_ALarmSound = 1 '全局变量在数据处理过程中判断置位
If alarm_flag = True Then
SystemSounds.Question.Play()
End If
mythread_AS.Sleep(500)
Loop
End Sub
'数据处理过程
Public Sub R_GPS()
a = TimeString
b = DateString
'每秒应该更新一次时间
DT.Text = b + Space(3) + a
If getdatastr.Length <> 0 Then
'数据处理,接受GPS和标志位判断等……
End Sub
Private Sub Threadfunction_Change()
Do While R_stop = 0
Dim myGetGPS As New GetGPS(Me)
'通过GETGPS类调用委托
myGetGPS.run()
myThread_GPS.Sleep(1000)
Loop