using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; 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; using Windows.Devices.Enumeration; using Windows.Devices.I2c; using System.Diagnostics; using System.Threading; using WinRTXamlToolkit.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace ArduinoSharpIR { /// /// An empty page that can be used on its own or navigated to within a Frame. /// public sealed partial class MainPage : Page { private I2cDevice Device; private Timer periodicTimer; private int sampleFrequency = 500; //0.5 Sec private int sampleNumber = 1; public MainPage() { this.InitializeComponent(); SetupI2C(); } private async void SetupI2C() { var settings = new I2cConnectionSettings(0x40);// arduino address settings.BusSpeed = I2cBusSpeed.StandardMode; string aqs = I2cDevice.GetDeviceSelector("I2C1"); var dis = await DeviceInformation.FindAllAsync(aqs); Device = await I2cDevice.FromIdAsync(dis[0].Id, settings); // start timer periodicTimer = new Timer(this.TimerGetAndDisplay, null, 0, sampleFrequency); } public void TimerGetAndDisplay(object state) { byte[] RegAddrBuf = new byte[] { 0x40 }; byte[] ReadBuf = new byte[9]; try { Device.Read(ReadBuf); } catch (Exception f) { Debug.WriteLine(f.Message); } //Decodes a sequence of bytes from the specified byte array into string //GetString: First parameter is the byte array // Second parameter is the index of the byte to decode // Third parameter is the number of bytes to decode char[] Distance_Array = System.Text.Encoding.UTF8.GetString(ReadBuf, 0, 4).ToCharArray();// distance char[] ADC_Array = System.Text.Encoding.UTF8.GetString(ReadBuf, 4, 5).ToCharArray();// ADC //convert the character array into string. String c = new string(Distance_Array); String a = new string(ADC_Array); string distance = c.Substring(0, 4); string ADC = a.Substring(0, 4); // start with specific location and specific length Debug.WriteLine("Sample: " + sampleNumber + " Distance " + distance + " cm"); Debug.WriteLine("ADC: " + ADC); sampleNumber++; var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ADCGauge.Value = Convert.ToDouble(ADC); //sending the ADC value to the designer to display Distance.Value = Convert.ToDouble(distance); //sending the distance value to the designer for display }); } } }