Attribute VB_Name = "Module1"
Option Explicit

Public Declare Function GetTickCount Lib "kernel32" () As Long
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Public MeasExeFlag As Integer               'On Measurement Flag
Public MeasTimeData As Double               'Measurement Time Data

Public ud As Integer

Public Function WaitMeasEnd() As Integer
Call ibwrt(ud, "*CLS")
Call ibwrt(ud, "OPR 16")
WaitMeasEnd = Wait_Meas(10)
End Function

Public Function WaitAvgEnd() As Integer
Call ibwrt(ud, "*CLS")
Call ibwrt(ud, "OPR 256")
WaitAvgEnd = Wait_Meas(10)
End Function

Public Function WaitSweepEnd() As Integer
Call ibwrt(ud, "*CLS")
Call ibwrt(ud, "OPR 8")
WaitSweepEnd = Wait_Meas(10)
End Function

Public Function CH1_SweepEnd() As Integer
'-----*CLS; OPR 8;  Need in the main routine
CH1_SweepEnd = Wait_Meas(10)
End Function

Public Function CH2_SweepEnd() As Integer
'-----*CLS; OPR 2048;  Need in the main routine
CH2_SweepEnd = Wait_Meas(10)
End Function


Private Function Wait_Meas(Wtime As Long) As Integer
'Return val
'0 = OK
'1 = Meas error
'2 = Timed out
'
Dim ret As Integer, i As Integer, Stat As Integer
Dim ReadBuffer As String * 10
Dim Tmr As Double
    
Call ibwrt(ud, "*SRE 160")

Wait_Meas = 0
Tmr = Timer
Do
    Sleep 10
    DoEvents
    
    Call ibwrt(ud, "*STB?")
    Call ibrd(ud, ReadBuffer)
    Stat = Val(ReadBuffer)
    Debug.Print "SPA STAT: " & Stat, ibsta
    If Timer > (Tmr + Wtime) Then
        Wait_Meas = 2
        Exit Function
    End If
Loop While ((Stat And 128) = 0) And ((Stat And 32) = 0) 'v044
Debug.Print "SPA STAT: " & Stat

If (Stat And 32) Then
    Call ibwrt(ud, "*ESR?")
    Call ibrd(ud, ReadBuffer)
    Stat = Val(ReadBuffer)
    If (Stat And 16 + 8) Then
        Wait_Meas = 1
    End If
End If

End Function

