/// <summary> /// Fetch an update from the Nunchuk and push it to all the properties. /// </summary> /// <returns>An awaitable task that completes upon success.</returns> public async Task UpdateAsync() { // the nunchuk does not respond to standard SMBus-compliant register reads, so we have to write a register, then do a new transaction to read out the data await dev.WriteByteAsync(0x00).ConfigureAwait(false); var response = await dev.ReadDataAsync(6).ConfigureAwait(false); joystick.X = response[0] / 127.5f - 1f; // normalize joystick data to [-1, 1] joystick.Y = response[1] / 127.5f - 1f; if (!oldJoystickData.SequenceEqual(response.Take(2))) { JoystickChanged?.Invoke(this, new JoystickEventArgs { NewValue = joystick }); } Array.Copy(response, oldJoystickData, 2); accelerometer.X = 2 * (short)((response[2] << 8) | (((response[5] >> 2) & 0x3) << 6)) / (float)ushort.MaxValue; // normalize accelerometer data to [-1, 1] accelerometer.Y = 2 * (short)((response[3] << 8) | (((response[5] >> 4) & 0x3) << 6)) / (float)ushort.MaxValue; accelerometer.Z = 2 * (short)((response[4] << 8) | (((response[5] >> 6) & 0x3) << 6)) / (float)ushort.MaxValue; ((DigitalInPeripheralPin)Z.Input).DigitalValue = (response[5] & 0x01) == 0; ((DigitalInPeripheralPin)C.Input).DigitalValue = (response[5] & 0x02) == 0; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Joystick))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Accelerometer))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(C))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Z))); }
/// <summary> /// Pollt alle 50ms den Joystick und generiert ein JoystickChanged Event, falls /// sich der Zustand des Joysticks (Taste gedrückt/losgelassen) verändert hat. /// </summary> private void Run() { Keys oldState = Keys; while (true) { Keys newState = Keys; if (!oldState.Equals(newState)) { JoystickChanged.Invoke(this, new KeyEventArgs(newState)); oldState = newState; } Thread.Sleep(50); } }