------------------------------------------------------------------------------
-- JUMPER TEAM BJS                                                                         --
------------------------------------------------------------------------------

with LSM303; use LSM303;

with MicroBit.Display;
with MicroBit.Accelerometer;
with MicroBit.Console;
with MicroBit.Time;

use MicroBit;


procedure Main is

   Data : LSM303.All_Axes_Data;
   FreeFallCounter : Integer;
   FreeFallDetectionCycles : Integer;
   FreeFallCondition : Boolean;
   Threshold : Axis_Data;

begin

   Console.Put_Line ("Jumper - starting up ..");

   -- Initialization
   FreeFallCondition := False;
   FreeFallCounter := 0;
   FreeFallDetectionCycles := 100;  -- 100 * 5ms = 500ms
   Threshold := 20;

   loop
      -- READ DATA
      --  Read the accelerometer data
      Data := Accelerometer.Data;

      --  Print the data on the serial port
      Console.Put_Line ("X:" & Data.X'Img & ASCII.HT &
                        "Y:" & Data.Y'Img & ASCII.HT &
                        "Z:" & Data.Z'Img);
      --------------------------------------------------------------------

      -- FREEFALL DETECTION
      -- check wether all axis are sub-threshold => increment counter
      if abs(Data.X) < Threshold and
         abs(Data.Y) < Threshold and
         abs(Data.Z) < Threshold then
         FreeFallCounter := FreeFallCounter + 1;
      -- otherwise reset counter
      else
         FreeFallCounter := 0;
      end if;

      -- Set free fall condition when counter reaches threshold
      if FreeFallCounter >= FreeFallDetectionCycles then
         FreeFallCondition := True;
      end if;
      --------------------------------------------------------------------

      -- DISPLAY
      --  Clear the LED matrix
      Display.Clear;

      -- Check, wether FreeFallCondition was triggered
      if FreeFallCondition then
         Display.Display ('X');
      else
         Display.Display ('0');
      end if;

      Time.Sleep (5);  -- 200 samples / s

   end loop;
end Main;
