Android Question help with sensors, IDE debugger message

HowardTheDuck

Member
Licensed User
Hi,
Noob here. My program doesn't seem to be capturing orientation sensor data and I haven't been able to figure out why. I used Erel's sensor demo program as the basis for this, removed what I didn't need and was left with Y and Z orientation sensors only. I confirmed that it was working as expected, then added a bunch of code which shouldn't interfere with it, and now I can't get it to run.

There's a few problems:

1. From observing the logs, I can see that the program runs as expected until it gets inside the Sub GameLoop. Within GameLoop there is a conditional statement If tiltY <> 0 Or tiltZ <> 0 Then... which should allow the game to proceed, however since these values are not updated, it hangs there.

2. I have set a timer and created a Sub Timer1_Tick, which doesn't seem to be processed. Since I didn't see any graphics being drawn as a result of this sub, I added a Log message to test it; it's never being processed.

3. Also, when I compile this in Debug mode, there is a message on the screen which never goes away that says "Waiting for IDE debugger to connect."

Does anyone have any ideas about what I might have done wrong? BTW, in its current state, when working correctly this should display a maze and do nothing more.

Thanks in advance. Sorry I can't narrow the scope of this code down any, but I'm clueless about where the problem is likely to be.


B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: True
    #ApplicationLabel: progname
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

'Activity module
Sub Process_Globals
    'This map maps between PhoneSensors and SensorData objects.
    Dim SensorsMap As Map
    Type SensorData (Name As String, ThreeValues As Boolean)
    Public level = 1 As Int
    Public MazeMap(10,10) As List' items in list indicate T/F for presence of wall on current cell 0=N, 1=E, 2=S, 3=W, 4=Visited(T/F)
    Public Timer1 As Timer
    Public FPS = 1000/60 As Long ' set denominator to desired FPS
    Public tiltY, tiltZ As Float
    Public Xdpi,Ydpi As Float
    Public TileWidth=32 As Int
    Public LastX = 0, LastY = 0 As Double
    Public StartTile, CurrentTile, EndTile As List
End Sub

Sub Globals
    Private pnlScreen As Panel
    Private cvsScreen As Canvas
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Main")
    If FirstTime Then
        SensorsMap.Initialize
        Dim ps As PhoneSensors 'This object is only used to access the type constants.
        AddSensor(ps.TYPE_ORIENTATION, "ORIENTATION", True)
    End If
    cvsScreen.Initialize(pnlScreen)
    Timer1.Initialize("Timer1",FPS)
    Timer1.Enabled = True
    
    'determine the screen size so it can calculate velocity realistically
    Dim r As Reflector 'requires reflection library
    r.Target = r.GetContext
    r.Target = r.RunMethod("getResources")
    r.Target = r.RunMethod("getDisplayMetrics")
    Log(r.GetField("xdpi"))
    Log(r.GetField("ydpi"))
    Xdpi = r.GetField("xdpi")
    Ydpi = r.GetField("ydpi")
End Sub

Sub AddSensor(SensorType As Int, Name As String, ThreeValues As Boolean) As SensorData
    Dim sd As SensorData
    sd.Initialize
    sd.Name = Name
    sd.ThreeValues = ThreeValues
    Dim ps As PhoneSensors
    ps.Initialize(SensorType)
    SensorsMap.Put(ps, sd)'ps seems to be an object not a string, why does that work as a key?
    Log(Name & " MaxValue = " & ps.MaxValue)
End Sub

Sub Activity_Resume
    'Here we start listening for SensorChanged events.
    'By checking the return value we knoe if the sensor is supported.
    For i = 0 To SensorsMap.Size - 1
        Dim ps As PhoneSensors
        Dim sd As SensorData
        ps = SensorsMap.GetKeyAt(i)
        sd = SensorsMap.GetValueAt(i)
        If ps.StartListening("Sensor") = False Then
            Log(sd.Name & " is not supported.")
        End If
    Next
    GameLoop
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    'Stop listening for events.
    For i = 0 To SensorsMap.Size - 1
        Dim ps As PhoneSensors
        ps = SensorsMap.GetKeyAt(i)
        ps.StopListening
    Next
End Sub

Sub Sensor_SensorChanged (Values() As Float)
    Log(Values(1) & "|" & Values(2))
    tiltY = Values(1)
    tiltZ = Values(2)
    'Z tilt left up to 90, right to -90
    'Y tilt toward me -90, away from me 90
    
'    lblX.Text = "X: " & NumberFormat(Values(0), 0 ,3)
'    lblY.Text = "Y: " & NumberFormat(Values(1), 0 ,3)
'    lblZ.Text = "Z: " & NumberFormat(Values(2), 0 ,3)
End Sub

Sub GameLoop
    CreateMaze
    Log("Sub CreateMaze has returned us to Sub GameLoop")
    Dim velocX = 0, velocY = 0 As Double
    Dim LastUpdateTime = DateTime.Now As Long
    Dim LastTiltY = 0, LastTiltZ = 0 As Long
    StartTile.Initialize
    CurrentTile.Initialize
    EndTile.Initialize
    StartTile = DefineStartTile 'origin is midpoint of this tile, which at start is midpoint of screen
    'keep track of movement of ball relative to origin, then calculate what needs displayed based upon those coordinates
    'use precise numbers (not Integers) to track pixel location, then floor for display purposes
    EndTile = DefineEndTile(StartTile)
    CurrentTile.Add(StartTile.Get(0))
    CurrentTile.Add(StartTile.Get(1))
    Log("Start, Current, and EndTile lists created")
    'loop while current location <> EndPoint
    Do Until CurrentTile.Get(0) = EndTile.Get(0) And CurrentTile.Get(1) = EndTile.Get(1)
        Log("loop started " & DateTime.Now)
        'there should be a pause button, touching the screen should start/stop the game. it should be paused at the start of a new level
        
        'if tilt Y or Z is not level, calculate where ball would have moved to since last update and place it there
        'for simplification, I am ignoring momentum and friction in calculating ball position
        Log(tiltY & " " & tiltZ)
        If tiltY <> 0 Or tiltZ <> 0 Then
            Dim UpdateInterval, Adjacent=0, Hypotenuse=0, deltaX=0, deltaY=0 As Long
            Dim dirX=1, dirY=1 As Int
            UpdateInterval = DateTime.Now - LastUpdateTime
            Log("UpdateInterval: " & UpdateInterval & " ms")
            Log(tiltY & " " & tiltZ)
            Dim Ipss = 32.17405 * 12 As Long 'this is inches per second squared, the acceleration of a falling object
            If tiltY <> 0 Then
                'make sure velocY is still valid, i.e. if it has changed direction reset it to 0
                If LastTiltY < 0 And tiltY >= 0 Then velocY = 0
                If LastTiltY > 0 And tiltY <= 0 Then velocY = 0
                'determine direction of travel
                If tiltY >0 Then
                    dirY = 1
                Else
                    dirY = -1
                End If
                Adjacent = velocY*(UpdateInterval/1000) + 0.5*Ipss*Power((UpdateInterval/1000),2)'distance ball would have moved toward ground, not across screen, in inches
                velocY = velocY + Ipss*(UpdateInterval/1000)
                Hypotenuse = Adjacent/CosD(tiltY)'this should be the distance travelled in the vertical direction of the screen, in inches. convert to pixels
                deltaY = Hypotenuse * Ydpi / 4'divide by four? to convert from actual to displayed resolution? should be number of displayed pixels to move from last location
                LastTiltY = tiltY
            End If
            If tiltZ <> 0 Then
                'make sure velocX is still valid, i.e. if it has changed direction reset it to 0
                If LastTiltZ < 0 And tiltZ >= 0 Then velocX = 0
                If LastTiltZ > 0 And tiltZ <= 0 Then velocX = 0
                'determine direction of travel
                If tiltZ > 0 Then
                    dirX = -1
                Else
                    dirX = 1
                End If
                Adjacent = velocX*(UpdateInterval/1000) + 0.5*Ipss*Power((UpdateInterval/1000),2)'distance ball would have moved toward ground, not across screen, in inches
                velocX = velocX + Ipss*(UpdateInterval/1000)
                Hypotenuse = Adjacent/CosD(tiltZ)'this should be the distance travelled in the vertical direction of the screen, in inches. convert to pixels
                deltaX = Hypotenuse * Xdpi / 4'divide by four? to convert from actual to displayed resolution? should be number of displayed pixels to move from last location
                LastTiltZ = tiltZ
            End If
            'now update the current position of the ball and determine what tile it is in
            LastX = LastX + dirX*deltaX
            LastY = LastY + dirY*deltaY
            Dim TileShiftX = 0, TileShiftY = 0 As Int
            TileShiftX = Floor((LastX+(TileWidth/2))/TileWidth)
            TileShiftY = Floor((LastY+(TileWidth/2))/TileWidth)
            CurrentTile.Set(0,StartTile.Get(0)+TileShiftX)
            CurrentTile.Set(1,StartTile.Get(1)+TileShiftY)
        End If
    Loop
    'if current location = EndPoint then increment level and restart GameLoop
    level = level + 1
    GameLoop
End Sub

Sub CreateMaze
    'define the number of rows and columns
    If level = 1 Then
        'start with a simple 10x10 grid
        Dim Height = 10 As Int
    Else If level = 2 Then
        'now generate a maze big enough to fill the screen vertically, requiring it to scroll horizontally
        Dim Height = 15 As Int
    Else
        'generate a grid of [level 2 height] + (level - 2), square
        Dim Height = 15 + level - 2 As Int
    End If
    Public MazeMap(Height,Height) As List' items in list indicate T/F for presence of wall on current cell 0=N, 1=E, 2=S, 3=W, 4=Visited(T/F)
    Dim visited = 1, currentX = 0, currentY = 0, nextX, nextY As Int
    Dim nextLoc As String
    Dim path As List
    path.Initialize
    path.Add("0,0")
    MazeMap(0,0).Initialize
    MazeMap(0,0).AddAll(Array As Boolean(True,True,True,True,True))
    Do Until visited = Height * Height
        'look up neighboring cells and see which are unvisited
        Dim unvisited As List
        unvisited.Initialize
        For i = -1 To 1
            For j = -1 To 1
                If i + currentX >= 0 And i + currentX < Height Then
                    If j + currentY >= 0 And j + currentY < Height Then
                        'Log(i & " " & currentX & " " & j & " " & currentY)
                        If MazeMap(i + currentX, j + currentY).IsInitialized Then
                            If MazeMap(i + currentX, j + currentY).Get(4) = False Then
                                unvisited.Add((i + currentX) & "," & (j + currentY))
                            End If
                        Else
                            unvisited.Add((i + currentX) & "," & (j + currentY))
                        End If
                    End If
                End If
            Next
        Next
        
        If unvisited.Size > 0 Then
            'choose one at random
            nextLoc = unvisited.Get(Rnd(0,unvisited.Size))
            
            'make sure there are no walls between current location and nextLoc
            Dim commaLoc As Int
            commaLoc = nextLoc.IndexOf(",")
            nextX = nextLoc.SubString2(0, commaLoc)
            nextY = nextLoc.SubString(commaLoc + 1)
        
            If MazeMap(nextX,nextY).IsInitialized = False Then
                MazeMap(nextX,nextY).Initialize
                MazeMap(nextX,nextY).AddAll(Array As Boolean(True,True,True,True,True))
            End If
            'presence of wall on current cell 0=N, 1=E, 2=S, 3=W, 4=Visited(T/F)
            If nextX = currentX Then
                'remaining in same row, is it to the left or right?
                If currentY < nextY Then
                    'remove the top wall of current and lower wall of next
                    MazeMap(currentX,currentY).Set(0,False)
                    MazeMap(nextX,nextY).Set(2,False)
                Else
                    'remove the lower wall of current and top wall of next
                    MazeMap(currentX,currentY).Set(2,False)
                    MazeMap(nextX,nextY).Set(0,False)
                End If
            Else
                'remaining in same column, is it up or down?
                If currentX > nextX Then
                    'remove the left wall of current and the right wall of next
                    MazeMap(currentX,currentY).Set(3,False)
                    MazeMap(nextX,nextY).Set(1,False)
                Else
                    'remove the right wall of current and the left wall of next
                    MazeMap(currentX,currentY).Set(1,False)
                    MazeMap(nextX,nextY).Set(3,False)
                End If
            End If
        
            'set as visited
            path.Add(nextX & "," & nextY)
            MazeMap(nextX,nextY).Set(4,True)
            visited = visited + 1   
        Else
            'There is no where new to go, back up to the previous location and try this again
            path.RemoveAt(path.Size - 1)
            nextLoc = path.Get(path.Size - 1)
            nextX = nextLoc.SubString2(0, commaLoc)
            nextY = nextLoc.SubString(commaLoc + 1)
            
        End If
        currentX = nextX
        currentY = nextY
        nextX = 0'error using Null here
        nextY = 0
        Log("visited: " & visited)
    Loop
    Log("Maze generation completed")
End Sub

Sub DefineStartTile As List
    'choose a random starting point
    Dim tempList As List
    tempList.Initialize
    tempList.Add(Rnd(0,MazeMap.Length))
    tempList.Add(Rnd(0,MazeMap.Length))
    Return tempList
End Sub

Sub DefineEndTile(x_startpos As List) As List
    'determine what quadrant starting point is in (if any) and place endpoint in a different quadrant
    Dim x1,x2,mid As Int 'this will define the range to select from
    Dim tempList As List
    tempList.Initialize
    mid = Floor(MazeMap.Length/2)
    If x_startpos.Get(0) < mid Then
        x1 = mid
        x2 = MazeMap.Length -1
    Else
        x1 = 0
        x2 = mid
    End If
    tempList.Add(Rnd(x1,x2))
    tempList.Add(Rnd(0, MazeMap.Length))
    Return tempList
End Sub

Sub Timer1_Tick
    'refresh the screen with the current data
    'LastX and LastY tells where the current view is centered relative to the origin
    Log(DateTime.Now)'not getting here
    Private rect1 As Rect
    rect1.Initialize(0dip,0dip,100%x,100%y)
    cvsScreen.DrawRect(rect1,Colors.Black,True,1) 'draw a black background
    'iterate over entire maze cell by cell to determine what is visible and where it should be displayed
    'may wish to put something in here to reduce iteration scope for very large mazes
    For i = 0 To MazeMap.Length - 1
        For j = 0 To MazeMap.Length - 1
            'determine where this tile is relative to starting tile and LastX,LastY
            Dim DistToStartX, DistToStartY As Int
            DistToStartX = (StartTile.Get(0) - i)*TileWidth
            DistToStartY = (StartTile.Get(1) - j)*TileWidth
            
            Dim ULTileX,ULTileY As Double 'x & y coordinates of upper left corner of current tile
            If CurrentTile.Get(0) <> StartTile.Get(0) Then
                ULTileX = 0 - (TileWidth/2) - DistToStartX - LastX'coordinates relative to center of screen, i.e. origin at 160,240
            Else
                ULTileX = 0 - DistToStartX - LastX
            End If
            If CurrentTile.Get(1) <> StartTile.Get(1) Then
                ULTileY = 0 + (TileWidth/2) + DistToStartY - LastY
            Else
                ULTileY = 0 + DistToStartY - LastY
            End If
            'the above may have produced fractional numbers, floor everything so we can use it for pixel display
            ULTileX = Floor(ULTileX)
            ULTileY = Floor(ULTileY)
            
            'the upper left corner of this tile's coordinates are known; check whether any of this tile is visible
            If ULTileX >= (-160-TileWidth) And ULTileX < 160 Then 'if any of the X coordinates are visible
                If ULTileY <= (240 + TileWidth) And ULTileY > -240 Then 'if any of the Y coordinates are visible
                    'draw this tile's features
                    'determine the coordinates of the 4 visible corners of this tile
                    Dim ULX, ULY, URX, URY, LLX, LLY, LRX, LRY As Int
                    If ULTileX + 160 < 0 Then
                        ULX = 0'truncate, tile begins to the left of the screen
                    Else
                        ULX = ULTileX + 160
                    End If
                    
                    If ULTileY - 240 > 0 Then
                        ULY = 0'truncate, tile begins above the screen
                    Else
                        ULY = 240 - ULTileY
                    End If
                    
                    If ULTileX + TileWidth + 160 > 320 Then
                        URX = 320'truncate, tile extends past the right of the screen
                    Else
                        URX = ULTileX + TileWidth + 160
                    End If
                    
                    If ULTileY - 240 > 0 Then
                        URY = 0'truncate, tile begins above the screen
                    Else   
                        URY = 240 - ULTileY
                    End If
                    
                    If ULTileX + 160 < 0 Then
                        LLX = 0 'truncate, tile begins to the left of the screen
                    Else
                        LLX = ULTileX + 160
                    End If
                    
                    If ULTileY - TileWidth < -240 Then
                        LLY = 480'truncate, tile lies partially below screen
                    Else
                        LLY = 240 - ULTileY + TileWidth
                    End If
                    
                    If ULTileX + TileWidth + 160 > 320 Then
                        LRX = 320'truncate, tile extends past the right of the screen
                    Else
                        LRX = ULTileX + TileWidth + 160
                    End If
                    
                    If ULTileY - TileWidth < -240 Then
                        LRY = 480'truncate, tile lies partially below screen
                    Else
                        LRY = 240 - ULTileY + TileWidth
                    End If
                    
                    'coordinates are defined above, draw the tile
                    Private Tile As Rect
                    Tile.Initialize(ULX,ULY,LRX,LRY)
                    cvsScreen.DrawRect(Tile,Colors.White,True,0)
                    
                    'now draw any required boundary lines on this tile
                    'need to test whether these boundaries are supposed to be visible
                    If MazeMap(i,j).Get(0) Then
                        'North wall is True
                        Private North As Rect
                        North.Initialize(ULX,ULY,URX,URY-1)
                        cvsScreen.DrawRect(North,Colors.Black,True,0)
                    End If
                    If MazeMap(i,j).Get(1) Then
                        'East wall is True
                        Private East As Rect
                        East.Initialize(URX-1,URY,LRX,LRY)
                        cvsScreen.DrawRect(East,Colors.Black,True,0)
                    End If
                    If MazeMap(i,j).Get(2) Then
                        'South wall is True
                        Private South As Rect
                        South.Initialize(LLX,LLY+1,LRX,LRY)
                        cvsScreen.DrawRect(South,Colors.Black,True,0)
                    End If
                    If MazeMap(i,j).Get(3) Then
                        'West wall is True
                        Private West As Rect
                        West.Initialize(ULX,ULY,ULX+1,LLY)
                        cvsScreen.DrawRect(West,Colors.Black,True,0)
                    End If
                End If
            End If
        Next
    Next
    pnlScreen.Invalidate
End Sub
 
Top