First pass at the accelerometer sample port
|
@ -77,6 +77,7 @@ For additional Windows samples, see [Windows on GitHub](http://microsoft.github.
|
|||
</tr>
|
||||
<tr>
|
||||
<td><a href="Samples/I2CCompass">I2CCompass</a></td>
|
||||
<td><a href="Samples/I2CAccelerometer">I2CAccelerometer</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
<!--
|
||||
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
|
||||
The MIT License(MIT)
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files(the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions :
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<Application
|
||||
x:Class="I2CAccelerometer.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="using:I2CAccelerometer">
|
||||
|
||||
</Application>
|
|
@ -0,0 +1,111 @@
|
|||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using Windows.ApplicationModel;
|
||||
using Windows.ApplicationModel.Activation;
|
||||
using Windows.Foundation;
|
||||
using Windows.Foundation.Collections;
|
||||
using Windows.UI.Xaml;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
using Windows.UI.Xaml.Controls.Primitives;
|
||||
using Windows.UI.Xaml.Data;
|
||||
using Windows.UI.Xaml.Input;
|
||||
using Windows.UI.Xaml.Media;
|
||||
using Windows.UI.Xaml.Navigation;
|
||||
|
||||
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
|
||||
|
||||
namespace I2CAccelerometer
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides application-specific behavior to supplement the default Application class.
|
||||
/// </summary>
|
||||
sealed partial class App : Application
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the singleton application object. This is the first line of authored code
|
||||
/// executed, and as such is the logical equivalent of main() or WinMain().
|
||||
/// </summary>
|
||||
public App()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
this.Suspending += OnSuspending;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked when the application is launched normally by the end user. Other entry points
|
||||
/// will be used such as when the application is launched to open a specific file.
|
||||
/// </summary>
|
||||
/// <param name="e">Details about the launch request and process.</param>
|
||||
protected override void OnLaunched(LaunchActivatedEventArgs e)
|
||||
{
|
||||
|
||||
#if DEBUG
|
||||
if (System.Diagnostics.Debugger.IsAttached)
|
||||
{
|
||||
this.DebugSettings.EnableFrameRateCounter = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
Frame rootFrame = Window.Current.Content as Frame;
|
||||
|
||||
// Do not repeat app initialization when the Window already has content,
|
||||
// just ensure that the window is active
|
||||
if (rootFrame == null)
|
||||
{
|
||||
// Create a Frame to act as the navigation context and navigate to the first page
|
||||
rootFrame = new Frame();
|
||||
// Set the default language
|
||||
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
|
||||
|
||||
rootFrame.NavigationFailed += OnNavigationFailed;
|
||||
|
||||
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
|
||||
{
|
||||
//TODO: Load state from previously suspended application
|
||||
}
|
||||
|
||||
// Place the frame in the current Window
|
||||
Window.Current.Content = rootFrame;
|
||||
}
|
||||
|
||||
if (rootFrame.Content == null)
|
||||
{
|
||||
// When the navigation stack isn't restored navigate to the first page,
|
||||
// configuring the new page by passing required information as a navigation
|
||||
// parameter
|
||||
rootFrame.Navigate(typeof(MainPage), e.Arguments);
|
||||
}
|
||||
// Ensure the current window is active
|
||||
Window.Current.Activate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked when Navigation to a certain page fails
|
||||
/// </summary>
|
||||
/// <param name="sender">The Frame which failed navigation</param>
|
||||
/// <param name="e">Details about the navigation failure</param>
|
||||
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
|
||||
{
|
||||
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked when application execution is being suspended. Application state is saved
|
||||
/// without knowing whether the application will be terminated or resumed with the contents
|
||||
/// of memory still intact.
|
||||
/// </summary>
|
||||
/// <param name="sender">The source of the suspend request.</param>
|
||||
/// <param name="e">Details about the suspend request.</param>
|
||||
private void OnSuspending(object sender, SuspendingEventArgs e)
|
||||
{
|
||||
var deferral = e.SuspendingOperation.GetDeferral();
|
||||
//TODO: Save application state and stop any background activity
|
||||
deferral.Complete();
|
||||
}
|
||||
}
|
||||
}
|
После Ширина: | Высота: | Размер: 1.4 KiB |
После Ширина: | Высота: | Размер: 7.5 KiB |
После Ширина: | Высота: | Размер: 2.9 KiB |
После Ширина: | Высота: | Размер: 1.6 KiB |
Двоичные данные
Samples/I2CAccelerometer/CS/Assets/Square44x44Logo.targetsize-24_altform-unplated.png
Normal file
После Ширина: | Высота: | Размер: 1.2 KiB |
После Ширина: | Высота: | Размер: 1.4 KiB |
После Ширина: | Высота: | Размер: 3.1 KiB |
|
@ -0,0 +1,147 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">ARM</Platform>
|
||||
<ProjectGuid>{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}</ProjectGuid>
|
||||
<OutputType>AppContainerExe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>I2CAccelerometer</RootNamespace>
|
||||
<AssemblyName>I2CAccelerometer</AssemblyName>
|
||||
<DefaultLanguage>en-US</DefaultLanguage>
|
||||
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
|
||||
<TargetPlatformVersion>10.0.15063.0</TargetPlatformVersion>
|
||||
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
|
||||
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
|
||||
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<AppxPackageSigningEnabled>true</AppxPackageSigningEnabled>
|
||||
<PackageCertificateKeyFile>I2CAccelerometer_TemporaryKey.pfx</PackageCertificateKeyFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\ARM\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
|
||||
<OutputPath>bin\ARM\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>ARM</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
||||
<OutputPath>bin\x64\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<NoWarn>;2008</NoWarn>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- A reference to the entire .Net Framework and Windows SDK are automatically included -->
|
||||
<None Include="project.json" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<SDKReference Include="WindowsIoT, Version=10.0.15063.0">
|
||||
<Name>Windows IoT Extension SDK</Name>
|
||||
</SDKReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="MainPage.xaml.cs">
|
||||
<DependentUpon>MainPage.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<AppxManifest Include="Package.appxmanifest">
|
||||
<SubType>Designer</SubType>
|
||||
</AppxManifest>
|
||||
<None Include="I2CAccelerometer_TemporaryKey.pfx" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="Properties\Default.rd.xml" />
|
||||
<Content Include="Assets\LockScreenLogo.scale-200.png" />
|
||||
<Content Include="Assets\SplashScreen.scale-200.png" />
|
||||
<Content Include="Assets\Square150x150Logo.scale-200.png" />
|
||||
<Content Include="Assets\Square44x44Logo.scale-200.png" />
|
||||
<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
|
||||
<Content Include="Assets\StoreLogo.png" />
|
||||
<Content Include="Assets\Wide310x150Logo.scale-200.png" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="MainPage.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' < '14.0' ">
|
||||
<VisualStudioVersion>14.0</VisualStudioVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
|
@ -0,0 +1,43 @@
|
|||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.26730.10
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "I2CAccelerometer", "I2CAccelerometer.csproj", "{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|ARM = Debug|ARM
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|ARM = Release|ARM
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|ARM.ActiveCfg = Debug|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|ARM.Build.0 = Debug|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|ARM.Deploy.0 = Debug|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x64.Build.0 = Debug|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x64.Deploy.0 = Debug|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x86.Build.0 = Debug|x86
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Debug|x86.Deploy.0 = Debug|x86
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|ARM.ActiveCfg = Release|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|ARM.Build.0 = Release|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|ARM.Deploy.0 = Release|ARM
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x64.ActiveCfg = Release|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x64.Build.0 = Release|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x64.Deploy.0 = Release|x64
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x86.ActiveCfg = Release|x86
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x86.Build.0 = Release|x86
|
||||
{8201FF3E-1F44-4D3E-B438-8E0DD5EA1BDB}.Release|x86.Deploy.0 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {50A288DB-7885-44FB-8CFE-D0CD25930B4D}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
|
@ -0,0 +1,21 @@
|
|||
Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -0,0 +1,37 @@
|
|||
<!--
|
||||
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
|
||||
The MIT License(MIT)
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files(the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions :
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<Page
|
||||
x:Class="I2CAccelerometer.MainPage"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="using:I2CAccelerometer"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
|
||||
<TextBlock x:Name="Title" HorizontalAlignment="Center" Margin="0,250,0,0" TextWrapping="Wrap" Text="ADXL345 Accelerometer Data" VerticalAlignment="Top" Height="67" Width="640" FontSize="48" TextAlignment="Center"/>
|
||||
<TextBlock x:Name="Text_X_Axis" HorizontalAlignment="Center" Margin="0,322,0,0" TextWrapping="Wrap" Text="X Axis: Not Initialized" VerticalAlignment="Top" Width="312" FontSize="26.667" Foreground="#FFC71818" TextAlignment="Center"/>
|
||||
<TextBlock x:Name="Text_Y_Axis" HorizontalAlignment="Center" Margin="0,362,0,0" TextWrapping="Wrap" Text="Y Axis: Not Initialized" VerticalAlignment="Top" Width="312" FontSize="26.667" Foreground="#FF14D125" TextAlignment="Center"/>
|
||||
<TextBlock x:Name="Text_Z_Axis" HorizontalAlignment="Center" Margin="0,407,0,0" TextWrapping="Wrap" Text="Z Axis: Not Initialized" VerticalAlignment="Top" Width="312" FontSize="26.667" Foreground="#FF1352C1" TextAlignment="Center"/>
|
||||
<TextBlock x:Name="Text_Status" HorizontalAlignment="Center" Margin="10,452,10,0" TextWrapping="Wrap" Text="Status: Initializing ..." VerticalAlignment="Top" Width="1346" FontSize="32" TextAlignment="Center"/>
|
||||
</Grid>
|
||||
</Page>
|
|
@ -0,0 +1,150 @@
|
|||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
using Windows.Devices.Enumeration;
|
||||
using Windows.Devices.I2c;
|
||||
|
||||
namespace I2CAccelerometer
|
||||
{
|
||||
struct Acceleration
|
||||
{
|
||||
public double X;
|
||||
public double Y;
|
||||
public double Z;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Sample app that reads data over I2C from an attached ADXL345 accelerometer
|
||||
/// </summary>
|
||||
public sealed partial class MainPage : Page
|
||||
{
|
||||
private const byte ACCEL_I2C_ADDR = 0x53; /* 7-bit I2C address of the ADXL345 with SDO pulled low */
|
||||
private const byte ACCEL_REG_POWER_CONTROL = 0x2D; /* Address of the Power Control register */
|
||||
private const byte ACCEL_REG_DATA_FORMAT = 0x31; /* Address of the Data Format register */
|
||||
private const byte ACCEL_REG_X = 0x32; /* Address of the X Axis data register */
|
||||
private const byte ACCEL_REG_Y = 0x34; /* Address of the Y Axis data register */
|
||||
private const byte ACCEL_REG_Z = 0x36; /* Address of the Z Axis data register */
|
||||
|
||||
private I2cDevice I2CAccel;
|
||||
private Timer periodicTimer;
|
||||
|
||||
public MainPage()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
|
||||
/* Register for the unloaded event so we can clean up upon exit */
|
||||
Unloaded += MainPage_Unloaded;
|
||||
|
||||
/* Initialize the I2C bus, accelerometer, and timer */
|
||||
InitI2CAccel();
|
||||
}
|
||||
|
||||
private async void InitI2CAccel()
|
||||
{
|
||||
|
||||
var settings = new I2cConnectionSettings(ACCEL_I2C_ADDR);
|
||||
settings.BusSpeed = I2cBusSpeed.FastMode;
|
||||
var controller = await I2cController.GetDefaultAsync();
|
||||
I2CAccel = controller.GetDevice(settings); /* Create an I2cDevice with our selected bus controller and I2C settings */
|
||||
|
||||
|
||||
/*
|
||||
* Initialize the accelerometer:
|
||||
*
|
||||
* For this device, we create 2-byte write buffers:
|
||||
* The first byte is the register address we want to write to.
|
||||
* The second byte is the contents that we want to write to the register.
|
||||
*/
|
||||
byte[] WriteBuf_DataFormat = new byte[] { ACCEL_REG_DATA_FORMAT, 0x01 }; /* 0x01 sets range to +- 4Gs */
|
||||
byte[] WriteBuf_PowerControl = new byte[] { ACCEL_REG_POWER_CONTROL, 0x08 }; /* 0x08 puts the accelerometer into measurement mode */
|
||||
|
||||
/* Write the register settings */
|
||||
try
|
||||
{
|
||||
I2CAccel.Write(WriteBuf_DataFormat);
|
||||
I2CAccel.Write(WriteBuf_PowerControl);
|
||||
}
|
||||
/* If the write fails display the error and stop running */
|
||||
catch (Exception ex)
|
||||
{
|
||||
Text_Status.Text = "Failed to communicate with device: " + ex.Message;
|
||||
return;
|
||||
}
|
||||
|
||||
/* Now that everything is initialized, create a timer so we read data every 100mS */
|
||||
periodicTimer = new Timer(this.TimerCallback, null, 0, 100);
|
||||
}
|
||||
|
||||
private void MainPage_Unloaded(object sender, object args)
|
||||
{
|
||||
/* Cleanup */
|
||||
I2CAccel.Dispose();
|
||||
}
|
||||
|
||||
private void TimerCallback(object state)
|
||||
{
|
||||
string xText, yText, zText;
|
||||
string statusText;
|
||||
|
||||
/* Read and format accelerometer data */
|
||||
try
|
||||
{
|
||||
Acceleration accel = ReadI2CAccel();
|
||||
xText = String.Format("X Axis: {0:F3}G", accel.X);
|
||||
yText = String.Format("Y Axis: {0:F3}G", accel.Y);
|
||||
zText = String.Format("Z Axis: {0:F3}G", accel.Z);
|
||||
statusText = "Status: Running";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
xText = "X Axis: Error";
|
||||
yText = "Y Axis: Error";
|
||||
zText = "Z Axis: Error";
|
||||
statusText = "Failed to read from Accelerometer: " + ex.Message;
|
||||
}
|
||||
|
||||
/* UI updates must be invoked on the UI thread */
|
||||
var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
|
||||
{
|
||||
Text_X_Axis.Text = xText;
|
||||
Text_Y_Axis.Text = yText;
|
||||
Text_Z_Axis.Text = zText;
|
||||
Text_Status.Text = statusText;
|
||||
});
|
||||
}
|
||||
|
||||
private Acceleration ReadI2CAccel()
|
||||
{
|
||||
const int ACCEL_RES = 1024; /* The ADXL345 has 10 bit resolution giving 1024 unique values */
|
||||
const int ACCEL_DYN_RANGE_G = 8; /* The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G */
|
||||
const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G; /* Ratio of raw int values to G units */
|
||||
|
||||
byte[] RegAddrBuf = new byte[] { ACCEL_REG_X }; /* Register address we want to read from */
|
||||
byte[] ReadBuf = new byte[6]; /* We read 6 bytes sequentially to get all 3 two-byte axes registers in one read */
|
||||
|
||||
/*
|
||||
* Read from the accelerometer
|
||||
* We call WriteRead() so we first write the address of the X-Axis I2C register, then read all 3 axes
|
||||
*/
|
||||
I2CAccel.WriteRead(RegAddrBuf, ReadBuf);
|
||||
|
||||
/*
|
||||
* In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes from the I2C read for each axis.
|
||||
* We accomplish this by using the BitConverter class.
|
||||
*/
|
||||
short AccelerationRawX = BitConverter.ToInt16(ReadBuf, 0);
|
||||
short AccelerationRawY = BitConverter.ToInt16(ReadBuf, 2);
|
||||
short AccelerationRawZ = BitConverter.ToInt16(ReadBuf, 4);
|
||||
|
||||
/* Convert raw values to G's */
|
||||
Acceleration accel;
|
||||
accel.X = (double)AccelerationRawX / UNITS_PER_G;
|
||||
accel.Y = (double)AccelerationRawY / UNITS_PER_G;
|
||||
accel.Z = (double)AccelerationRawZ / UNITS_PER_G;
|
||||
|
||||
return accel;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<Package
|
||||
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
|
||||
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
|
||||
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
|
||||
IgnorableNamespaces="uap mp">
|
||||
|
||||
<Identity
|
||||
Name="I2CAccelerometer"
|
||||
Publisher="CN=MSFT"
|
||||
Version="1.0.0.0" />
|
||||
|
||||
<mp:PhoneIdentity PhoneProductId="0fa3457d-302c-434a-89f2-8f310529a81c" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
|
||||
|
||||
<Properties>
|
||||
<DisplayName>I2CAccelerometer</DisplayName>
|
||||
<PublisherDisplayName>MSFT</PublisherDisplayName>
|
||||
<Logo>Assets\StoreLogo.png</Logo>
|
||||
</Properties>
|
||||
|
||||
<Dependencies>
|
||||
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
|
||||
</Dependencies>
|
||||
|
||||
<Resources>
|
||||
<Resource Language="x-generate"/>
|
||||
</Resources>
|
||||
|
||||
<Applications>
|
||||
<Application Id="App"
|
||||
Executable="$targetnametoken$.exe"
|
||||
EntryPoint="I2CAccelerometer.App">
|
||||
<uap:VisualElements
|
||||
DisplayName="I2CAccelerometer"
|
||||
Square150x150Logo="Assets\Square150x150Logo.png"
|
||||
Square44x44Logo="Assets\Square44x44Logo.png"
|
||||
Description="I2CAccelerometer"
|
||||
BackgroundColor="transparent">
|
||||
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
|
||||
<uap:SplashScreen Image="Assets\SplashScreen.png" />
|
||||
</uap:VisualElements>
|
||||
</Application>
|
||||
</Applications>
|
||||
|
||||
<Capabilities>
|
||||
<Capability Name="internetClient" />
|
||||
<DeviceCapability Name="lowLevel" />
|
||||
</Capabilities>
|
||||
</Package>
|
|
@ -0,0 +1,31 @@
|
|||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("I2CAccelerometer")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("I2CAccelerometer")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
[assembly: ComVisible(false)]
|
|
@ -0,0 +1,31 @@
|
|||
<!--
|
||||
This file contains Runtime Directives used by .NET Native. The defaults here are suitable for most
|
||||
developers. However, you can modify these parameters to modify the behavior of the .NET Native
|
||||
optimizer.
|
||||
|
||||
Runtime Directives are documented at http://go.microsoft.com/fwlink/?LinkID=391919
|
||||
|
||||
To fully enable reflection for App1.MyClass and all of its public/private members
|
||||
<Type Name="App1.MyClass" Dynamic="Required All"/>
|
||||
|
||||
To enable dynamic creation of the specific instantiation of AppClass<T> over System.Int32
|
||||
<TypeInstantiation Name="App1.AppClass" Arguments="System.Int32" Activate="Required Public" />
|
||||
|
||||
Using the Namespace directive to apply reflection policy to all the types in a particular namespace
|
||||
<Namespace Name="DataClasses.ViewModels" Seralize="All" />
|
||||
-->
|
||||
|
||||
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
|
||||
<Application>
|
||||
<!--
|
||||
An Assembly element with Name="*Application*" applies to all assemblies in
|
||||
the application package. The asterisks are not wildcards.
|
||||
-->
|
||||
<Assembly Name="*Application*" Dynamic="Required All" />
|
||||
|
||||
|
||||
<!-- Add your application specific runtime directives here. -->
|
||||
|
||||
|
||||
</Application>
|
||||
</Directives>
|
|
@ -0,0 +1,326 @@
|
|||
# I2C Accelerometer
|
||||
|
||||
|
||||
|
||||
We'll connect an I2C accelerometer to your Raspberry Pi 2 or 3/MinnowBoard Max/DragonBoard and create a simple app to read data from it. We'll walk you through step-by-step, so no background knowledge of I2C is needed.
|
||||
However, if you're curious, SparkFun provides a great [tutorial on I2C](https://learn.sparkfun.com/tutorials/i2c){:target="_blank"}.
|
||||
|
||||
This is a headed sample. To better understand what headed mode is and how to configure your device to be headed, follow the instructions [here](https://docs.microsoft.com/en-us/windows/iot-core/learn-about-hardware/HeadlessMode).
|
||||
|
||||
### Load the project in Visual Studio
|
||||
|
||||
You can find the source code for this sample by downloading a zip of all of our samples [here](https://github.com/Microsoft/Windows-iotcore-samples/archive/master.zip) and navigating to the `samples\I2CAccelerometer`. Make a copy of the folder on your disk and open the project from Visual Studio.
|
||||
|
||||
### Connect the I2C Accelerometer to your device
|
||||
|
||||
You'll need a few components:
|
||||
|
||||
* <a name="I2C_Accelerometer"></a>an [ADXL345 accelerometer board from Sparkfun](https://www.sparkfun.com/products/9836){:target="_blank"} with pin headers soldered on
|
||||
|
||||
* a breadboard and a couple of male-to-female connector wires
|
||||
|
||||
* If you are using a MinnowBoard Max, you'll need a 100 Ω resistor (this is a workaround for a [known I2C hardware issue](https://docs.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsmbm)
|
||||
|
||||
Visit the **Raspberry Pi 2 or 3/MinnowBoard Max** sections below depending on which device you have:
|
||||
|
||||
![Electrical Components](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/components.png)
|
||||
|
||||
#### Raspberry Pi 2 or 3
|
||||
If you have a Raspberry Pi 2 or 3, we need to hook up power, ground, and the I2C lines to the accelerometer.
|
||||
Those familiar with I2C know that normally pull-up resistors need to be installed. However, the Raspberry Pi 2 or 3 already has pull-up resistors on its I2C pins, so we don't need to add any additional external pull-ups here.
|
||||
See the [Raspberry Pi 2 or 3 pin mapping page](https://docs.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsrpi) for more details on the RPi2 and RPi3 IO pins.
|
||||
|
||||
**Note: Make sure to power off the RPi2 or RPi3 when connecting your circuit. This is good practice to reduce the chance of an accidental short circuit during construction.**
|
||||
|
||||
The ADXL345 breakout board has 8 IO pins, connect them as follows:
|
||||
|
||||
1. **GND:** Connect to ground on the RPi2 or RPi3 (Pin 6)
|
||||
2. **VCC:** Connect to 3.3V on the RPi2 or RPi3 (Pin 1)
|
||||
3. **CS:** Connect to 3.3V (The ADXL345 actually supports both SPI and I2C protocols. To select I2C, we keep this pin tied to 3.3V. The [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"} contains much more information about the pin functions)
|
||||
4. **INT1:** Leave unconnected, we're not using this pin
|
||||
5. **INT2:** Leave unconnected, we're not using this pin
|
||||
6. **SDO:** Connect to ground (In I2C mode, this pin is used to select the device address. You can attach two ADXL345 to the same I2C bus if you connect this pin to 3.3V on the second device. See the [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"} for more details)
|
||||
7. **SDA:** Connect to SDA on the RPi2 or RPi3 (Pin 3). This is the data line for the I2C bus.
|
||||
8. **SCL:** Connect to SCL on the RPi2 or RPi3 (Pin 5). This is the clock line for the I2C bus.
|
||||
|
||||
Here are the connections shown on a breadboard:
|
||||
|
||||
![Breadboard connections](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/breadboard_assembled_rpi2.png)
|
||||
|
||||
<sub>*Image made with [Fritzing](http://fritzing.org/)*</sub>
|
||||
|
||||
Here are the schematics:
|
||||
|
||||
![Accelerometer schematics](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/schematics_rpi2.png)
|
||||
|
||||
#### MinnowBoard Max
|
||||
If you have a MinnowBoard Max, we need to hook up power, ground, and the I2C lines to the accelerometer. Those familiar with I2C know that normally pull-up resistors need to be installed. However, the MBM already has 10K pull-up resistors on its IO pins, so we don't need to add any additional external pull-ups here.
|
||||
See the [MBM pin mapping page](https://docs.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsmbm) for more details on the MBM IO pins.
|
||||
|
||||
**Note: Make sure to power off the MBM when connecting your circuit. This is good practice to reduce the chance of an accidental short circuit during construction.**
|
||||
|
||||
The ADXL345 breakout board has 8 IO pins, connect them as follows:
|
||||
|
||||
1. **GND:** Connect to ground on the MBM (Pin 2)
|
||||
2. **VCC:** Connect to 3.3V on the MBM (Pin 4)
|
||||
3. **CS:** Connect to 3.3V (The ADXL345 actually supports both SPI and I2C protocols. To select I2C, we keep this pin tied to 3.3V. The [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"} contains much more information about the pin functions)
|
||||
4. **INT1:** Leave unconnected, we're not using this pin
|
||||
5. **INT2:** Leave unconnected, we're not using this pin
|
||||
6. **SDO:** Connect to ground (In I2C mode, this pin is used to select the device address. You can attach two ADXL345 to the same I2C bus if you connect this pin to 3.3V on the second device. See the [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf) for more details)
|
||||
7. **SDA:** Connect to SDA on the MBM (Pin 15). This is the data line for the I2C bus.
|
||||
8. **SCL:** Connect to SCL on the MBM (Pin 13) through the 100 Ω resistor. This is the clock line for the I2C bus.
|
||||
|
||||
Here are the connections shown on a breadboard:
|
||||
|
||||
![Breadboard connections](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/breadboard_assembled_mbm.png)
|
||||
|
||||
<sub>*Image made with [Fritzing](http://fritzing.org/)*</sub>
|
||||
|
||||
Here are the schematics:
|
||||
|
||||
![Accelerometer schematics](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/schematics_mbm.png)
|
||||
|
||||
#### DragonBoard 410c
|
||||
|
||||
For the DragonBoard 410c, connections need to be made from the single board computer to the power, ground, and I2C lines of the accelerometer.
|
||||
Those familiar with I2C know that normally pull-up resistors need to be installed. However, the DragonBoard already has 2kΩ resistors for its I2C capabilities.
|
||||
|
||||
**Note: Make sure to power off the DragonBoard when connecting your circuit. This is good practice to reduce the change of an accidental short circuit during construction.**
|
||||
|
||||
You'll also need a LM317 voltage regulator along with 2x 120 Ω resistors to provide power to the accelerometer.
|
||||
The regulator will output 2.5V when configured as shown in the breadboard diagram, which allows the ADXL345 board to interface with the 1.8V DragonBoard 410c.
|
||||
|
||||
The LM317 has 3 pins that need to be wired:
|
||||
|
||||
1. **Adj:** Connect to ground through a 120 Ω resistor
|
||||
2. **Output:** Connect to **Adj** through a 120 Ω resistor. This pin will output 2.5V once the LM317 is wired up.
|
||||
3. **Input:** Connect to 5V on the DragonBoard (Pin 37)
|
||||
|
||||
The ADXL345 breakout board has 8 IO pins which are connected to the DragonBoard as follows:
|
||||
|
||||
1. **GND:** Connect to ground on the DragonBoard (Pin 2)
|
||||
2. **VCC:** Connect to the LM317 2.5v output rail
|
||||
3. **CS:** Connect to 2.5V (The ADXL345 actually supports both SPI and I2C protocols. To select I2C, we keep this pin tied to 2.5V. The [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"} contains much more information about the pin functions)
|
||||
4. **INT1:** Leave unconnected, we're not using this pin
|
||||
5. **INT2:** Leave unconnected, we're not using this pin
|
||||
6. **SDO:** Connect to ground (In I2C mode, this pin is used to select the device address. You can attach two ADXL345 to the same I2C bus if you connect this pin to 3.3V on the second device. See the [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf) for more details)
|
||||
7. **SDA:** Connect to SDA on the DragonBoard (Pin 17). This is the data line for the I2C bus.
|
||||
8. **SCL:** Connect to SCL on the DragonBoard (Pin 15). This is the clock line for the I2C bus.
|
||||
|
||||
Here is a diagram showing what your breadboard might look like with the circuit assembled:
|
||||
|
||||
![DragonBoard I2C Accelerometer Breadboard](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/breadboard_assembled_db410c.png)
|
||||
|
||||
### Deploy and run the app
|
||||
|
||||
When everything is set up, power your device back on, and open up the sample app in Visual Studio. Open the file **MainPage.xaml.cs** and change the following line from **Protocol.NONE** to **Protocol.I2C**:
|
||||
|
||||
```C++
|
||||
public sealed partial class MainPage : Page
|
||||
{
|
||||
/* Important! Change this to either Protocol.I2C or Protocol.SPI based on how your accelerometer is wired */
|
||||
private Protocol HW_PROTOCOL = Protocol.I2C;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Follow the instructions to [setup remote debugging and deploy the app](https://docs.microsoft.com/en-us/windows/iot-core/develop-your-app/AppDeployment).
|
||||
The I2CAccelerometer app will deploy and start, and you should see accelerometer data show up on screen.
|
||||
If you have your accelerometer flat on a surface, the Z axis should read close to 1.000G, while X and Y are close to 0.000G. The values will fluctuate a little even if the device is standing still.
|
||||
This is normal and is due to minute vibrations and electrical noise. If you tilt or shake the sensor, you should see the values change in response. Note that this sample configures the device in 4G mode,
|
||||
so you wont be able to see G readings higher than 4Gs.
|
||||
|
||||
![I2C Accelerometer running](https://az835927.vo.msecnd.net/sites/iot/Resources/images/I2CAccelerometer/i2caccelerometer_screenshot.png)
|
||||
|
||||
Congratulations! You've connected an I2C accelerometer.
|
||||
|
||||
### Let's look at the code
|
||||
The code in this sample performs two main tasks:
|
||||
|
||||
1. First the code initializes the I2C bus and the accelerometer
|
||||
|
||||
2. Secondly, we read from the accelerometer at defined intervals and update the display
|
||||
|
||||
Let's start by digging into the initializations.
|
||||
|
||||
### Initialize the I2C bus
|
||||
To use the accelerometer, we need to initialize the I2C bus first. Here is the C# code.
|
||||
|
||||
```C#
|
||||
using Windows.Devices.Enumeration;
|
||||
using Windows.Devices.I2c;
|
||||
|
||||
/* Initialization for I2C accelerometer */
|
||||
private async void InitI2CAccel()
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = new I2cConnectionSettings(ACCEL_I2C_ADDR);
|
||||
settings.BusSpeed = I2cBusSpeed.FastMode; /* 400KHz bus speed */
|
||||
|
||||
string aqs = I2cDevice.GetDeviceSelector(); /* Get a selector string that will return all I2C controllers on the system */
|
||||
var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the I2C bus controller devices with our selector string */
|
||||
I2CAccel = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */
|
||||
if (I2CAccel == null)
|
||||
{
|
||||
Text_Status.Text = string.Format(
|
||||
"Slave address {0} on I2C Controller {1} is currently in use by " +
|
||||
"another application. Please ensure that no other applications are using I2C.",
|
||||
settings.SlaveAddress,
|
||||
dis[0].Id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Here's an overview of what's happening:
|
||||
|
||||
* First, we get the selector strings for all I2C controllers on the device.
|
||||
|
||||
* Next, we find all the I2C bus controllers on the system and check that at least one bus controller exists.
|
||||
|
||||
* We then create an **I2CConnectionSettings** object with the accelerometer address "ACCEL_I2C_ADDR" (0x53) and bus speed set to "FastMode" (400KHz)
|
||||
|
||||
* Finally, we create a new **I2cDevice** and check that it's available for use.
|
||||
|
||||
### Initialize the accelerometer
|
||||
|
||||
Now that we have the **I2cDevice** accelerometer instance, we're done with the I2C bus initialization. We can now write data over I2C to start up the accelerometer. We do this with the **Write()** function.
|
||||
For this particular accelerometer, there are two internal registers we need to configure before we can start using the device: The data format register, and the power control register.
|
||||
|
||||
1. We first write a 0x01 to the data format register. This configures the device range into +-4G mode. If you consult the [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"}, you'll see that the device can be configured in a variety of measurement modes ranging from 2G to 16G.
|
||||
Higher G settings provide you with greater range at the expense of reduced resolution. We choose 4G as a reasonable trade off between the two.
|
||||
|
||||
2. We write a 0x08 to the power control register, which wakes the device from standby and starts measuring acceleration. Again, the [datasheet](https://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf){:target="_blank"} contains additional information about the device settings and capabilities.
|
||||
|
||||
```C#
|
||||
private async void InitI2CAccel()
|
||||
{
|
||||
// ...
|
||||
|
||||
/*
|
||||
* Initialize the accelerometer:
|
||||
*
|
||||
* For this device, we create 2-byte write buffers:
|
||||
* The first byte is the register address we want to write to.
|
||||
* The second byte is the contents that we want to write to the register.
|
||||
*/
|
||||
byte[] WriteBuf_DataFormat = new byte[] { ACCEL_REG_DATA_FORMAT, 0x01 }; /* 0x01 sets range to +- 4Gs */
|
||||
byte[] WriteBuf_PowerControl = new byte[] { ACCEL_REG_POWER_CONTROL, 0x08 }; /* 0x08 puts the accelerometer into measurement mode */
|
||||
|
||||
/* Write the register settings */
|
||||
try
|
||||
{
|
||||
I2CAccel.Write(WriteBuf_DataFormat);
|
||||
I2CAccel.Write(WriteBuf_PowerControl);
|
||||
}
|
||||
/* If the write fails display the error and stop running */
|
||||
catch (Exception ex)
|
||||
{
|
||||
Text_Status.Text = "Failed to communicate with device: " + ex.Message;
|
||||
return;
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Timer code
|
||||
After all the initializations are complete, we start a timer to read from the accelerometer periodically. Here is how you set up the timer to trigger every 100mS.
|
||||
```C#
|
||||
private async void InitI2CAccel()
|
||||
{
|
||||
// ...
|
||||
|
||||
/* Now that everything is initialized, create a timer so we read data every 100mS */
|
||||
periodicTimer = new Timer(this.TimerCallback, null, 0, 100);
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
private void TimerCallback(object state)
|
||||
{
|
||||
string xText, yText, zText;
|
||||
string statusText;
|
||||
|
||||
/* Read and format accelerometer data */
|
||||
try
|
||||
{
|
||||
Acceleration accel = ReadAccel();
|
||||
xText = String.Format("X Axis: {0:F3}G", accel.X);
|
||||
yText = String.Format("Y Axis: {0:F3}G", accel.Y);
|
||||
zText = String.Format("Z Axis: {0:F3}G", accel.Z);
|
||||
statusText = "Status: Running";
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Read data from the accelerometer
|
||||
With the I2C bus and accelerometer initialized, we can start reading data from the accelerometer. Our **ReadAccel()** function gets called every 100mS by the timer:
|
||||
|
||||
```C#
|
||||
private Acceleration ReadAccel()
|
||||
{
|
||||
const int ACCEL_RES = 1024; /* The ADXL345 has 10 bit resolution giving 1024 unique values */
|
||||
const int ACCEL_DYN_RANGE_G = 8; /* The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G */
|
||||
const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G; /* Ratio of raw int values to G units */
|
||||
|
||||
byte[] ReadBuf;
|
||||
byte[] RegAddrBuf;
|
||||
|
||||
/*
|
||||
* Read from the accelerometer
|
||||
* We first write the address of the X-Axis register, then read all 3 axes into ReadBuf
|
||||
*/
|
||||
switch (HW_PROTOCOL)
|
||||
{
|
||||
case Protocol.SPI:
|
||||
// ...
|
||||
case Protocol.I2C:
|
||||
ReadBuf = new byte[6]; /* We read 6 bytes sequentially to get all 3 two-byte axes */
|
||||
RegAddrBuf = new byte[] { ACCEL_REG_X }; /* Register address we want to read from */
|
||||
I2CAccel.WriteRead(RegAddrBuf, ReadBuf);
|
||||
break;
|
||||
default: /* Code should never get here */
|
||||
// ...
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
/* In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes for each axis */
|
||||
short AccelerationRawX = BitConverter.ToInt16(ReadBuf, 0);
|
||||
short AccelerationRawY = BitConverter.ToInt16(ReadBuf, 2);
|
||||
short AccelerationRawZ = BitConverter.ToInt16(ReadBuf, 4);
|
||||
|
||||
/* Convert raw values to G's */
|
||||
Acceleration accel;
|
||||
accel.X = (double)AccelerationRawX / UNITS_PER_G;
|
||||
accel.Y = (double)AccelerationRawY / UNITS_PER_G;
|
||||
accel.Z = (double)AccelerationRawZ / UNITS_PER_G;
|
||||
|
||||
return accel;
|
||||
}
|
||||
```
|
||||
Here's how this works:
|
||||
|
||||
* We begin by reading data from the accelerometer with the WriteRead() function. As the name suggests, this function first performs a write, followed by a read.
|
||||
|
||||
* The initial write specifies the register address we want to read from (which in this case is the X-Axis data register). This write ensures that a subsequent read will start from this register address.
|
||||
We provide the function with a one-byte byte array representing the register address we want to write
|
||||
|
||||
* Next we provide the function with a read buffer of size 6 so we read 6 bytes over I2C. Since this device supports sequential reads,
|
||||
**and** the X, Y, and Z data registers are next to each other, reading 6 bytes give us all of our data in one go. This ensures acceleration values don't change between reads as well.
|
||||
|
||||
* We get back 6 bytes of data from our read. These represent the data in the X, Y, and Z data registers respectively.
|
||||
We separate out the data into their respective axes and concatenate the bytes using **BitConverter.ToInt16()**.
|
||||
|
||||
* The raw data is formatted as a 16-bit integer, which contains 10-bit data from the accelerometer. It can take on values ranging from -512 to 511. A reading of -512 corresponds to -4G while 511 is +4G.
|
||||
To convert this to G units, we divide by the ratio of full-scale range (8G) to the resolution (1024)
|
||||
|
||||
* Now that we have the G unit values, we can display the data on screen. This process is repeated every 100mS so the information is constantly updated.
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"dependencies": {
|
||||
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
|
||||
},
|
||||
"frameworks": {
|
||||
"uap10.0": {}
|
||||
},
|
||||
"runtimes": {
|
||||
"win10-arm": {},
|
||||
"win10-arm-aot": {},
|
||||
"win10-x86": {},
|
||||
"win10-x86-aot": {},
|
||||
"win10-x64": {},
|
||||
"win10-x64-aot": {}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
layout: sample
|
||||
title: IC Accelerometer
|
||||
description: An app to read data from the I2C Accelerometer attached to RPI2/RPI3/MinnowBoradMax/DragonBoard
|
||||
keyword: iot, wiring, uwp
|
||||
deviceName: RPI2, RPI3, MinnowBoardMax, DragonBoard
|
||||
lang: en-US
|
||||
---
|
||||
# AppServiceBlinky
|
||||
|
||||
These are the available versions of this Windows 10 IoT Core sample:
|
||||
|
||||
* [C#](./CS/README.md)
|
||||
|
||||
## Additional resources
|
||||
* [Windows 10 IoT Core home page](https://developer.microsoft.com/en-us/windows/iot/)
|
||||
|
||||
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact <opencode@microsoft.com> with any additional questions or comments.
|