public MainPage()
        {
            this.InitializeComponent();
            Current  = this;
            rootPage = Current;

            if (!NumberFed)
            {
                this.set_data();
            }

            _accelerometer = Accelerometer.GetDefault();
            if (_accelerometer != null)
            {
                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                // This value will be used later to activate the sensor.
                uint minReportInterval = _accelerometer.MinimumReportInterval;
                // Keeping Minimum Time between readings as 30 ms
                _desiredReportInterval = minReportInterval > 30 ? minReportInterval : 30;
                // Getting Access to geolocation
                AskGeolocatorPermission();
            }
            else
            {
                NotifyUser("No accelerometer found. This app is not compatible with your device.", NotifyType.ErrorMessage);
                SendButton.IsEnabled = false;
            }
        }
Example #2
0
        public GamePage()
        {
            this.InitializeComponent();

            this.navigationHelper            = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

#if WINDOWS_PHONE_APP
            StatusBar statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            statusBar.HideAsync();
#endif

            gameVM           = new GameViewModel(this.Width, this.Height);
            this.DataContext = gameVM;

            this.Accelerometer = Accelerometer.GetDefault();

            this.Accelerometer.ReportInterval = 10;

            this.Accelerometer.ReadingChanged += (snd, args) =>
            {
                var dx = args.Reading.AccelerationX;
                var dy = args.Reading.AccelerationY;
                var dz = args.Reading.AccelerationZ;

                this.Dispatcher.RunAsync((Windows.UI.Core.CoreDispatcherPriority.Normal), () =>
                {
                    gameVM.MovePlayerWithDelta(dz, dx);
                });
            };
        }
Example #3
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Instantiate the accelerometer
            _accelerometer = Accelerometer.GetDefault();
        }
        /// <summary>
        /// Background task entry point.
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Accelerometer = Accelerometer.GetDefault();

            if (null != Accelerometer)
            {
                SampleCount = 0;

                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                uint minReportIntervalMsecs = Accelerometer.MinimumReportInterval;
                Accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16;

                // Subscribe to accelerometer ReadingChanged events.
                Accelerometer.ReadingChanged += new TypedEventHandler <Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);

                // Take a deferral that is released when the task is completed.
                Deferral = taskInstance.GetDeferral();

                // Get notified when the task is canceled.
                taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

                // Store a setting so that the app knows that the task is running.
                ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
            }
        }
Example #5
0
        private async System.Threading.Tasks.Task checkForAccelerometer()
        {
            _myAcc = Accelerometer.GetDefault();
            MessageDialog msgDialog = new MessageDialog("Standard Message");

            if (_myAcc == null)
            {
                // no accelerometer available, do something else
                // add the eventhandler for the key press here rather than in
                // constructor
                Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

                msgDialog.Content = "No accelerometer available! Use arrow keys instead. Click inside the sreen window to start.";
                await msgDialog.ShowAsync();
            }
            else
            {
                // create the event handlers for readings
                // changed and the shaken event.
                _myAcc.ReadingChanged += _myAcc_ReadingChanged;

                // set the report intervals in milliseconds
                uint minReportInterval = _myAcc.MinimumReportInterval;

                /*
                 * compare the min report interval against the requested
                 * interval of 100 milliseconds
                 * if the minimum possible value is > 100, then use the
                 * accelerometer min value, otherwise use the requested value
                 * of 100 milliseconds.
                 */
                _desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
                _myAcc.ReportInterval  = _desiredReportInterval;
            }
        }
        /// <summary>
        /// Initializes a new instance of the DeviceMotionImplementation class.
        /// </summary>
        public DeviceMotionImplementation()
        {
            try
            {
                accelerometer = Accelerometer.GetDefault();
                gyrometer     = Gyrometer.GetDefault();
                compass       = Compass.GetDefault();

#if WINDOWS_PHONE_APP
                magnetometer = Magnetometer.GetDefault();
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            sensorStatus = new Dictionary <MotionSensorType, bool>()
            {
                { MotionSensorType.Accelerometer, false },
                { MotionSensorType.Gyroscope, false },
                { MotionSensorType.Magnetometer, false },
                { MotionSensorType.Compass, false }
            };
        }
Example #7
0
        public StarCatcher() //Intialises all the starting variables
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Disabled;
            bounds       = Window.Current.Bounds; //Assigns the width and height of the screen to bounds
            lstStar      = new List <Image>();
            lstMovement  = new List <animation>();
            lstStar2     = new List <Image>();
            lstMovement2 = new List <animation>();
            starSound    = new Uri("ms-appx:///Assets/shootingStarMini.WAV");
            uBlip        = new Uri("ms-appx:///Assets/Blip.mp3");
            endGame      = new Uri("ms-appx:///Assets/gameOver.WAV");

            myAccelerometer = Accelerometer.GetDefault();
            roll            = 0.0;       // Sets the initial value or roll to 0;
            dptTimer        = new DispatcherTimer();
            if (myAccelerometer != null) //Checks to see if phone has an accelerometer
            {
                uint reportInterval;
                if (myAccelerometer.MinimumReportInterval > 10)
                {
                    reportInterval = myAccelerometer.MinimumReportInterval;
                }
                else
                {
                    reportInterval = 10;
                }
                myAccelerometer.ReportInterval = reportInterval;

                // Create the accelerometer event handler
                myAccelerometer.ReadingChanged += MyAccelerometer_ReadingChanged;
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            Accelerometer _accelerometer = Accelerometer.GetDefault(AccelerometerReadingType.Standard);;

            _gyrometer = Gyrometer.GetDefault();
            uint _acclDesiredReportInterval = _accelerometer.MinimumReportInterval;
            uint _gyroDesiredReportInterval = _gyrometer.MinimumReportInterval;

            // make timestamped folder for this record session
            string pathParent = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
            string folderPath = System.IO.Path.Combine(pathParent, "IMUData");

            System.IO.Directory.CreateDirectory(new Uri(folderPath).LocalPath);

            // create csv file for this record session
            String fileName = nanoTime() + ".csv";
            String filePath = System.IO.Path.Combine(folderPath, fileName);

            writerCSV = new StreamWriter(new FileStream(new Uri(filePath).LocalPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true));
            writerCSV.WriteLine("timestamp" + "," + "omega_x" + "," + "omega_y" + "," + "omega_z" + "," + "alpha_x" + "," + "alpha_y" + "," + "alpha_z");
            //writerCSV.WriteLine("timestamp" + "," +  "alpha_x" + "," + "alpha_y" + "," + "alpha_z");


            // Establish the report interval
            _accelerometer.ReportInterval = _acclDesiredReportInterval;
            _gyrometer.ReportInterval     = _gyroDesiredReportInterval;


            _accelerometer.ReadingChanged += AcclReadingChanged;
            _gyrometer.ReadingChanged     += GyroReadingChanged;
            Console.WriteLine("Data Collecting ...");
            Console.ReadLine();
            writerCSV.Close();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            foreach (FilterInfo device in videoDevices)
            {
                comboBox1.Items.Add(device.Name);
            }
            comboBox1.SelectedIndex = 0;

            videoSource = new VideoCaptureDevice();
            //Accelerometer defaultAcc = Accelerometer.GetDefault();
            _accelerometer = Accelerometer.GetDefault(AccelerometerReadingType.Standard); // set to standard instead of linear acceleration!!!
            //Accelerometer tmp = Accelerometer.GetDefault(AccelerometerReadingType.Linear);
            _gyrometer = Gyrometer.GetDefault();
            textBox1.Clear();
            if (_accelerometer != null)
            {
                _acclDesiredReportInterval = _accelerometer.MinimumReportInterval;
                textBox1.Text      = "IMUs are available on this device!";
                textBox1.BackColor = Color.Green;
                //InitializeTimer();
            }
            else
            {
                textBox1.Text      = "No IMU available on this device!";
                textBox1.BackColor = Color.Red;
            }
            if (_gyrometer != null)
            {
                _gyroDesiredReportInterval = _gyrometer.MinimumReportInterval;
            }
            //if (DEBUG) InitializeTimer();
        }
Example #10
0
        /// <summary>
        /// Initialize settings for Accelerometer.
        /// </summary>
        private void InitializeAccelerometer()
        {
            txtTitle.Text = String.Format(CultureInfo.CurrentCulture, App.LoadString("Test"), App.LoadString("Accelerometer"));

            try
            {
                // Instantiate the Accelerometer.
                _accelerometer = Accelerometer.GetDefault();

                if (_accelerometer == null)
                {
                    // The device on which the application is running does not support the gyrometer sensor
                    txtStatus.Text = String.Format(CultureInfo.CurrentCulture, App.LoadString("NotSupported"), App.LoadString("Accelerometer"));
                    App.LogError(txtStatus.Text);
                }
                else
                {
                    // Add ReadingChanged event handler
                    _accelerometer.ReadingChanged += accelerometer_ReadingChanged;
                }
            }
            catch (NotSupportedException)
            {
                _accelerometer = null;
                txtStatus.Text = App.LoadString("Error");
                App.LogError(txtStatus.Text);
            }
            catch (Exception ex)
            {
                _accelerometer = null;
                txtStatus.Text = App.LoadString("Error") + " (" + ex.Message + ")";
                App.LogError(txtStatus.Text);
            }
        }
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // check first if there is an accelerometer
            _myAcc = Accelerometer.GetDefault();
            MessageDialog msgDialog = new MessageDialog("Standard Message");

            if (_myAcc == null)
            {
                // tell someone who cares.
                // not there
                msgDialog.Content = "Cheap pc, no accelerometer";
                await msgDialog.ShowAsync();
            }
            else
            {
                // create the event handlers for readings
                // changed and the shaken event.
                _myAcc.ReadingChanged += _myAcc_ReadingChanged;
                _myAcc.Shaken         += _myAcc_Shaken;
                // set the report intervals in milliseconds
                uint minReportInterval = _myAcc.MinimumReportInterval;

                /*
                 * compare the min report interval against the requested
                 * interval of 100 milliseconds
                 * if the minimum possible value is > 100, then use the
                 * accelerometer min value, otherwise use the requested value
                 * of 100 milliseconds.
                 */
                _desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
                _myAcc.ReportInterval  = _desiredReportInterval;
            }
        }
        private async void SendDeviceToCloudMessagesAsync()
        {
            byte[]  byteData;
            string  JSONString = "";
            Message EventToSend;

            count++;
            if (chkGoSlow.IsChecked == true)
            {
                if (count % 10 != 0)
                {
                    return;
                }
            }
            // Calculate Accelleration and Position
            Accelerometer        accelerometer = Accelerometer.GetDefault();
            AccelerometerReading r             = accelerometer.GetCurrentReading();
            double G = Math.Sqrt((r.AccelerationX * r.AccelerationX) + (r.AccelerationY * r.AccelerationY) + (r.AccelerationZ * r.AccelerationZ));

            // Create JSON String
            JSONString = "{\"DataTypeKey\": \"ACC\", \"Count\": " + count + ", \"X\": " + Math.Round(r.AccelerationX, 2) + ", \"Y\": " + Math.Round(r.AccelerationY, 2) + ", \"Z\": " + Math.Round(r.AccelerationZ, 2) + ", \"G\": " + Math.Round(G, 2) + "}";

            Label1.Text = JSONString;
            byteData    = Encoding.UTF8.GetBytes(JSONString);
            EventToSend = new Message(byteData);

            if (sending == 1)
            {
                await deviceClient.SendEventAsync(EventToSend);
            }
        }
Example #13
0
        private async void InitAccelerometer()
        {
            var accelerometer = Accelerometer.GetDefault();

            accelerometer.ReadingChanged += OnAccelerometerReadingChanged;
            accelerometer.Shaken         += OnShake;
        }
        //-------------------------------------------------------------------------------------
        // Input handling


        /// <summary>
        /// Determines which input capabilities are present for the current device
        /// </summary>
        /// <returns></returns>
        public static InputCapabilities GetInputCapabilities(bool forceRefresh = false)
        {
            // Have we already figured this all out?
            // (Or are we being asked to refresh any existing data?)
            if (!_inputCaps._isDataPopulated || forceRefresh)
            {
#if WINDOWS_PHONE
                // Check for keyboard support
                _inputCaps.IsKeyboardPresent = Microsoft.Phone.Info.DeviceStatus.IsKeyboardPresent;
                // WP doesn't support mice
                _inputCaps.IsMousePresent = false;
                // WP always supports touch screens
                _inputCaps.IsTouchPresent = true;
                // Attempt to obtain an accelerometer object -- if this succeeds then the accelerometer is present
                _inputCaps.IsAccelerometerPresent = (Accelerometer.GetDefault() != null);
                // WP doesn't support GamePads
                _inputCaps.IsGamePadPresent = false;
#else
                // Check the various device present values -- non-zero will indicate that the device is present
                _inputCaps.IsKeyboardPresent = (new Windows.Devices.Input.KeyboardCapabilities()).KeyboardPresent != 0;
                _inputCaps.IsMousePresent    = (new Windows.Devices.Input.MouseCapabilities()).MousePresent != 0;
                _inputCaps.IsTouchPresent    = (new Windows.Devices.Input.TouchCapabilities()).TouchPresent != 0;
                // Attempt to obtain an accelerometer object -- if this succeeds then the accelerometer is present
                _inputCaps.IsAccelerometerPresent = (Accelerometer.GetDefault() != null);
                // Check whether player one's gamepad is available.
                // This isn't the full picture, but will usually be indicative if a gamepad being connected.
                _inputCaps.IsGamePadPresent = Microsoft.Xna.Framework.Input.GamePad.GetCapabilities(PlayerIndex.One).IsConnected;
#endif
                // Remember that we've populated the data so that we don't need to do it again
                _inputCaps._isDataPopulated = true;
            }

            // Return the populated capabilities data
            return(_inputCaps);
        }
Example #15
0
        private void OnGetAccelerometer(object sender, RoutedEventArgs e)
        {
            Accelerometer        accelerometer = Accelerometer.GetDefault();
            AccelerometerReading reading       = accelerometer.GetCurrentReading();

            this.DefaultViewModel["AccelerometerResult"] = GetAccelerometerResult(reading);
        }
Example #16
0
        public AccelHandler()
        {
            // Fetch the Accelerator from our device
            A = Accelerometer.GetDefault();

            setA();
        }
Example #17
0
        public MainPage()
        {
            this.InitializeComponent();

            _accelerometer = Accelerometer.GetDefault();

            if (_accelerometer != null)
            {
                // Establish the report interval
                uint minReportInterval = _accelerometer.MinimumReportInterval;
                uint reportInterval    = minReportInterval > 16 ? minReportInterval : 16;
                _accelerometer.ReportInterval = reportInterval;

                // Assign an event handler for the reading-changed event
                _accelerometer.ReadingChanged += new TypedEventHandler <Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
            }

            // so numbers will start slowly
            for (int i = 0; i < 100; i++)
            {
                list.Add(0);
            }

            var timer = new DispatcherTimer();

            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
Example #18
0
        public void StartTiming(bool startOnMovement = true)
        {
            if (geolocator == null)
            {
                throw new InvalidOperationException("LapTimer must be initialized before calling StartTiming.");
            }

            if (isTiming)
            {
                StopTiming();
            }

            lapNumber            = 1;
            lapStartElapsedTime  = TimeSpan.Zero;
            headingNormalisation = new List <double>();
            lapCoordinates       = new List <LapDataPointViewModel>();
            currentSector        = generateSectors ? null : sectorCoordinates.MinBy(s => s.SectorNumber);
            accelerometer        = Accelerometer.GetDefault();
            if (accelerometer != null)
            {
                accelerometer.ReadingChanged += accelerometer_ReadingChanged;
            }

            geolocator.PositionChanged += geolocator_PositionChanged;
            if (!startOnMovement)
            {
                stopwatch.Start();
                isTiming = true;
                if (TimingStarted != null)
                {
                    TimingStarted(this, null);
                }
            }
            isFirstReading = true;
        }
 private void InitializeAccelerometer()
 {
     _accelerometer = Accelerometer.GetDefault();
     if (_accelerometer != null)
     {
         _accelerometer.ReadingChanged += AccelerometerOnCurrentValueChanged;
     }
 }
        public SensorPage()
        {
            this.InitializeComponent();

            _accelerometer = Accelerometer.GetDefault();

            InitializeBtComponentAsync();
        }
Example #21
0
 private void RegisterShaken()
 {
     shakenHandler = new TypedEventHandler <Accelerometer, AccelerometerShakenEventArgs>(OnShaken);
     accelerometer = Accelerometer.GetDefault();
     if (accelerometer != null)
     {
         accelerometer.Shaken += shakenHandler;
     }
 }
Example #22
0
        private void GetAcc_Click(object sender, RoutedEventArgs e)
        {
            Accelerometer a = Accelerometer.GetDefault();

            if (a != null)
            {
                a.ReadingChanged += A_ReadingChanged;
            }
        }
Example #23
0
        public MainPage()
        {
            accelerometer = Accelerometer.GetDefault();
            pid           = new PidController.PidController(PROPORTIONAL_GAIN, INTEGRAL_GAIN, DERIVATIVE_GAIN, 100f, 0f);
            pid.SetPoint  = 0;
            motor         = new Motor(0, 36, 250);

            this.InitializeComponent();
        }
Example #24
0
 void MainPage_Loaded(object sender, RoutedEventArgs e)
 {
     acc = Accelerometer.GetDefault();
     if (acc != null)
     {
         acc.ReportInterval  = 100;
         acc.ReadingChanged += acc_ReadingChanged;
     }
 }
 public GraviViewer()
 {
     InitializeComponent();
     list    = new PictureStore().Images;
     current = list.Count / 2;
     Display();
     acc      = Accelerometer.GetDefault();
     dt.Tick += dt_Tick;
     dt.Start();
 }
 public MainPage()
 {
     InitializeComponent();
     _accelerometer = Accelerometer.GetDefault();
     if (_accelerometer != null)
     {
         _accelerometer.ReportInterval  = Math.Max(16, _accelerometer.MinimumReportInterval);
         _accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
     }
 }
Example #27
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            accelerometer = Accelerometer.GetDefault();

            if (accelerometer != null)
            {
                accelerometer.ReadingChanged += accelerometer_ReadingChanged;
                accelerometer.Shaken         += accelerometer_Shaken;
            }
        }
Example #28
0
        private void Form1_Load(object sender, EventArgs e)
        {
            _locator = new Geolocator();
            _locator.ReportInterval   = 250;
            _locator.StatusChanged   += Locator_StatusChanged;
            _locator.PositionChanged += Locator_PositionChanged;

            _accelerometor = Accelerometer.GetDefault(AccelerometerReadingType.Standard);
            _accelerometor.ReadingChanged += Accelerometor_ReadingChanged;
        }
        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        private async void Start()
        {
            if (!timer.IsEnabled)
            {
                string runningMessage = "Reading: ";

                accelSensor = Accelerometer.GetDefault();
                if (accelSensor != null)
                {
                    accelSensor.ReportInterval = 66;
                    runningMessage            += "Accelerometer ";
                }

                // while not shown in the chapter, get the current location so that
                // true heading is more accurate.
                Geolocator locator = new Geolocator();
                await locator.GetGeopositionAsync();

                compassSensor = Compass.GetDefault();
                if (compassSensor != null)
                {
                    compassSensor.ReportInterval = 66;
                    runningMessage += "Compass ";
                }

                try
                {
                    gyroSensor = Gyrometer.GetDefault();
                }
                catch (FileNotFoundException) { }

                if (gyroSensor != null)
                {
                    gyroSensor.ReportInterval = 66;
                    runningMessage           += "Gyroscope ";
                }

                inclineSensor = Inclinometer.GetDefault();
                if (inclineSensor != null)
                {
                    inclineSensor.ReportInterval = 66;
                    runningMessage += "Inclinometer ";
                }

                orientationSensor = OrientationSensor.GetDefault();
                if (orientationSensor != null)
                {
                    orientationSensor.ReportInterval = 66;
                    runningMessage += "Orientation ";
                }

                timer.Start();
                messageBlock.Text = runningMessage;
            }
        }
Example #30
0
        public Scenario2()
        {
            this.InitializeComponent();

            _accelerometer = Accelerometer.GetDefault();
            if (_accelerometer == null)
            {
                rootPage.NotifyUser("No accelerometer found", NotifyType.ErrorMessage);
            }
            _shakeCount = 0;
        }