Пример #1
1
        private async Task Initialize()
        {
            try
            {
                if (Interlocked.CompareExchange(ref _isInitialized, 1, 0) == 1)
                {
                    return;
                }

                // Get a selector string that will return all I2C controllers on the system
                string deviceSelector = I2cDevice.GetDeviceSelector();
                // Find the I2C bus controller device with our selector string
                var dis = await DeviceInformation.FindAllAsync(deviceSelector);
                if (dis.Count == 0)
                {
                    throw new Hdc100XInitializationException("No I2C controllers were found on the system");
                }

                var settings = new I2cConnectionSettings((int)_busAddress)
                {
                    BusSpeed = I2cBusSpeed.FastMode
                };
                _sensorDevice = await I2cDevice.FromIdAsync(dis[0].Id, settings);
                if (_sensorDevice == null)
                {
                    throw new Hdc100XInitializationException(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));
                }

                // Configure sensor:
                // - measure with 14bit precision
                // - measure both temperature and humidity
                _sensorDevice.Write(new byte[] { 0x02, 0x10, 0x00 });

                _initalizationCompletion.SetResult(true);
            }
            catch (Hdc100XInitializationException)
            {
                _initalizationCompletion.SetResult(false);
                throw;
            }
            catch (Exception exc)
            {
                _initalizationCompletion.SetResult(false);
                throw new Hdc100XInitializationException("Unexpected error during initialization", exc);
            }
        }
        internal async void InitializeSystem()
        {
            // initialize I2C communications
            string deviceSelector = I2cDevice.GetDeviceSelector();
            DeviceInformationCollection _i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);
            
            if (_i2cDeviceControllers.Count == 0)
            {
                throw new I2cControllerNotFoundException(); ;
            }

            I2cConnectionSettings ambientTempI2cSettings = new I2cConnectionSettings(AMBIENT_TEMP_BASE_ADDRESS);
            ambientTempI2cSettings.BusSpeed = I2cBusSpeed.StandardMode;

            _i2cTempDevice = await I2cDevice.FromIdAsync(_i2cDeviceControllers[0].Id, ambientTempI2cSettings);

            if (_i2cTempDevice == null)
            {
                throw new Exception(string.Format(
                    "Slave address {0} is currently in use on {1}. " +
                    "Please ensure that no other applications are using I2C.",
                    ambientTempI2cSettings.SlaveAddress,
                    _i2cDeviceControllers[0].Id));
            }

            HardwareReady = true;

            if (SensorReady != null)
                SensorReady(this, EventArgs.Empty);
        }
Пример #3
0
        public async Task Initialise(byte HardwareDeviceAddress)
        {
            System.Diagnostics.Debug.WriteLine("Initalise Started");


            System.Diagnostics.Debug.WriteLine("Finding Device");
            I2cConnectionSettings i2cSettings = new I2cConnectionSettings(HardwareDeviceAddress);
            i2cSettings.BusSpeed = I2cBusSpeed.FastMode;

            string DeviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);
            DeviceInformationCollection i2cDeviceControllers = await DeviceInformation.FindAllAsync(DeviceSelector);

            i2cDeviceChannel = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);

            System.Diagnostics.Debug.WriteLine("Device Found");


            byte[] writeBuffer;

            // Shutdown Register
            writeBuffer = new byte[] { 0x00, 0x01 };
            i2cDeviceChannel.Write(writeBuffer);
            Debug.WriteLine("Shutdown Register set");

            // Pin Enable Registers
            writeBuffer = new byte[] { 0x13, 0xff };
            i2cDeviceChannel.Write(writeBuffer);
            writeBuffer = new byte[] { 0x14, 0xff };
            i2cDeviceChannel.Write(writeBuffer);
            writeBuffer = new byte[] { 0x15, 0xff };
            i2cDeviceChannel.Write(writeBuffer);

            System.Diagnostics.Debug.WriteLine("Initalise Complete");

        }
Пример #4
0
        public async void Init()
        {
            try
            {
                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 device with our selector string           */

                var settings = new I2cConnectionSettings(I2CAddress)
                {
                    BusSpeed = I2cBusSpeed.FastMode
                };
                
                _device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
                if (_device == null)
                {
                    
                }
                else
                {
                    _isInited = true;
                }
            }
            catch
            {
                _isInited = false;
                throw;
            }
        }
        private async void initI2C()
        {
            try
            {
                var i2cSettings = new I2cConnectionSettings(I2C_ARDUINO);
                i2cSettings.BusSpeed = I2cBusSpeed.FastMode;
                string deviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);
                var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);
                var i2cdev = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings);
                byte[] wbuffer = new byte[] { 1, 2 };
                byte[] rbuffer = new byte[8];
                //var resutl = i2cdev.WriteReadPartial(wbuffer, rbuffer);
                //Debug.WriteLine(resutl.Status);
                //i2cdev.WriteRead(wbuffer, rbuffer);
                i2cdev.Write(wbuffer);
                await Task.Delay(10000);
                var resutl = i2cdev.ReadPartial(rbuffer);
                Debug.WriteLine(rbuffer[0]);

            }
            catch (Exception ex)
            {

                throw;
            }
        }
Пример #6
0
        /// <summary>
        /// Initializes the I2C connection and channels.
        /// </summary>
        /// <returns>A <see cref="Task"/> instance which can be awaited on for completion.</returns>
        public async Task Init()
        {
            if (SlaveAddress < 0) throw new Exception("Invalid SlaveAddress value configured. Please call the class constructor with a valid I2C bus slave address.");
            Debug.WriteLine("Initializing PCA9685 against slave address {0}.", SlaveAddress);

            string aqs = I2cDevice.GetDeviceSelector();
            var i2cDevices = await DeviceInformation.FindAllAsync(aqs);
            if (i2cDevices.Count == 0)
            {
                Debug.WriteLine("No I2C controllers were found on the system.");
                return;
            }

            var settings = new I2cConnectionSettings(GeneralCallSlaveAddress);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            GeneralCallDev = await I2cDevice.FromIdAsync(i2cDevices[0].Id, settings);
            if (GeneralCallDev == null)
            {
                var errorMessage =  string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by another application.",
                        settings.SlaveAddress,
                        i2cDevices[0].Id);

                throw new Exception(errorMessage);
            }

            SoftwareReset();

            settings = new I2cConnectionSettings(SlaveAddress);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            Dev = await I2cDevice.FromIdAsync(i2cDevices[0].Id, settings);
            if (Dev == null)
            {
                var errorMessage = string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by another application.",
                        settings.SlaveAddress,
                        i2cDevices[0].Id);

                throw new Exception(errorMessage);
            }

            Debug.WriteLine("PCA9685 I2C channels created.");

            SetAllChannelsDutyCycle(0.0f);

            // Output drive mode is totem-pole not open drain
            WriteReg(MODE2, OUTDRV);

            // Turn-off oscillator and acknowledge All-Call transfers
            WriteReg(MODE1, ALLCALL);
            await Task.Delay(1);

            byte mode1 = ReadReg(MODE1);
            // Turn on oscillator
            mode1 &= unchecked((byte)~SLEEP);
            WriteReg(MODE1, mode1);
            await Task.Delay(1);

            Debug.WriteLine("PCA9685 initialization complete.");
        }
Пример #7
0
        public async Task Initialize()
        {
            Debug.WriteLine("TCS34725::Initialize");

            try
            {
                var settings = new I2cConnectionSettings(TCS34725_Address);
                settings.BusSpeed = I2cBusSpeed.FastMode;

                string aqs = I2cDevice.GetDeviceSelector(I2CControllerName);
                var dis = await DeviceInformation.FindAllAsync(aqs);
                colorSensor = await I2cDevice.FromIdAsync(dis[0].Id, settings);

                // Now setup the LedControlPin
                gpio = GpioController.GetDefault();

                LedControlGPIOPin = gpio.OpenPin(LedControlPin);
                LedControlGPIOPin.SetDriveMode(GpioPinDriveMode.Output);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                throw;
            }

        }
Пример #8
0
        public static async Task<I2cDevice> GetDevice(int address, string controllerName)
        {
            var key = $"{address} - {controllerName}";

            if (_deviceCache.ContainsKey(key))
            {
                return _deviceCache[key];
            }

            using (var l = await _locker.LockAsync())
            {
                if (_deviceCache.ContainsKey(key))
                {
                    return _deviceCache[key];
                }

                var settings = new I2cConnectionSettings(address) { BusSpeed = I2cBusSpeed.FastMode };

                var aqs = I2cDevice.GetDeviceSelector(controllerName);

                var dis = await DeviceInformation.FindAllAsync(aqs);
                
                var i2Cdevice = await I2cDevice.FromIdAsync(dis[0].Id, settings);       
                
                if (i2Cdevice == null)
                {
                    return null;
                }

                _deviceCache.Add(key, i2Cdevice);

                return i2Cdevice;
            }
        }
Пример #9
0
        public async Task< List<byte> >  GetAvailableDevicesAddress()
        {
            // get aqs filter  to find i2c device
            string aqs = I2cDevice.GetDeviceSelector("I2C1");

            // Find the I2C bus controller with our selector string
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count == 0)
                throw new Exception("There is no I2C device"); // bus not found

            List<byte> devicesList = new List<byte>();

            for (byte i = 0; i < 127; i++)
            {
                I2cConnectionSettings settings = new I2cConnectionSettings(i);
                // Create an I2cDevice with our selected bus controller and I2C settings
                var device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
                var result = device.WritePartial(new byte[] { 0x00 });
                if (result.Status == I2cTransferStatus.SlaveAddressNotAcknowledged) continue;
                devicesList.Add(i);
                device.Dispose();
            }

            return devicesList;
        }
Пример #10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // 
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            var deferral = taskInstance.GetDeferral();
            var settings = new I2cConnectionSettings(I2C_ADDRESS);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            var 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             */
            _dht11 = await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings    */
            await begin();

            while (true)
            {
                var temp = await readTemperature();
                var hum = await readHumidity();
                Debug.WriteLine($"{temp} C & {hum}% humidity");
                await Task.Delay(2000);
            }

            deferral.Complete();
        }
Пример #11
0
        //Method to initialize the BMP280 sensor
        public async Task InitializeAsync()
        {
            Debug.WriteLine("BMP280::InitializeAsync");

            try
            {
                //Instantiate the I2CConnectionSettings using the device address of the BMP280
                var settings = new I2cConnectionSettings(Bmp280Address)
                {
                    BusSpeed = I2cBusSpeed.FastMode
                };
                //Set the I2C bus speed of connection to fast mode
                //Use the I2CBus device selector to create an advanced query syntax string
                var aqs = I2cDevice.GetDeviceSelector(I2CControllerName);
                //Use the Windows.Devices.Enumeration.DeviceInformation class to create a collection using the advanced query syntax string
                var dis = await DeviceInformation.FindAllAsync(aqs);
                //Instantiate the the BMP280 I2C device using the device id of the I2CBus and the I2CConnectionSettings
                _bmp280 = await I2cDevice.FromIdAsync(dis[0].Id, settings);
                //Check if device was found
                if (_bmp280 == null)
                {
                    Debug.WriteLine("Device not found");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }
        public async void Run()
        {
            var deviceSelector = I2cDevice.GetDeviceSelector("I2C1");

            var devices = await DeviceInformation.FindAllAsync(deviceSelector);

            if (devices.Count == 0)
            {
                return;
            }

            var settings = new I2cConnectionSettings(0x54); // 0x54 is the I2C device address for the PiGlow

            using (I2cDevice device = await I2cDevice.FromIdAsync(devices[0].Id, settings))
            {
                InitPyGlow(device);

                await Pulsate(
                    device,
                    brightness: 64,
                    numberOfPulses: 3,
                    speedOfPulses: 100);

                await Pinwheel(
                    device,
                    brightness: 64,
                    numberOfSpins: 5,
                    speedOfSpin: 300);

                ClearLeds(device);
            }
        }
        private async Task StartScenarioAsync()
        {
            string i2cDeviceSelector = I2cDevice.GetDeviceSelector();
            IReadOnlyList<DeviceInformation> devices = await DeviceInformation.FindAllAsync(i2cDeviceSelector);

            // 0x40 was determined by looking at the datasheet for the HTU21D sensor.
            var HTU21D_settings = new I2cConnectionSettings(0x40);

            // If this next line crashes with an ArgumentOutOfRangeException,
            // then the problem is that no I2C devices were found.
            //
            // If the next line crashes with Access Denied, then the problem is
            // that access to the I2C device (HTU21D) is denied.
            //
            // The call to FromIdAsync will also crash if the settings are invalid.
            //
            // FromIdAsync produces null if there is a sharing violation on the device.
            // This will result in a NullReferenceException in Timer_Tick below.
            htu21dSensor = await I2cDevice.FromIdAsync(devices[0].Id, HTU21D_settings);

            // Start the polling timer.
            timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(500) };
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        /// <summary>
        /// Moves servo to specified angle
        /// </summary>
        /// <param name="Angle">Angle to be moved</param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task<byte[]> MoveServo(byte Angle)
        {
            byte[] Response = new byte[1];

            /* Gateway's I2C SLAVE address */
            int SlaveAddress = 64;              // 0x40

            try
            {
                // Initialize I2C
                var Settings = new I2cConnectionSettings(SlaveAddress);
                Settings.BusSpeed = I2cBusSpeed.StandardMode;

                if (AQS == null || DIS == null)
                {
                    AQS = I2cDevice.GetDeviceSelector("I2C1");
                    DIS = await DeviceInformation.FindAllAsync(AQS);
                }

                using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings))
                {
                    /* Send byte to the gateway to move servo at specified position */
                    Device.Write(new byte[] { Angle });
                }
            }
            catch (Exception)
            {
                // SUPPRESS ANY ERROR
            }
            
            /* Return dummy or ZERO */
            return Response;
        }
Пример #15
0
        /// <summary>
        /// Instanciate asyncronously a new PCF8591 object.
        /// As System.Threading.Tasks.Task are not valid Windows Runtime type supported, this method has been set to private and is publicly exposed through the IAsyncOperation method "Create".
        /// </summary>
        /// <param name="BusSpeed">The I2C Bus Speed. Default value: StandardMode </param>
        /// <param name="SharingMode">The I2C Sharing Mode. Default value is Exclusive. To use with caution </param>
        /// <returns></returns>
        async static private Task <PCF8591> CreateAsync(I2cBusSpeed BusSpeed, I2cSharingMode SharingMode)
        {
            PCF8591 newADC = new PCF8591();
            /// advanced query syntax used to find devices on the RaspberryPi.
            string AQS         = Windows.Devices.I2c.I2cDevice.GetDeviceSelector();
            var    DevicesInfo = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(AQS);

            if (DevicesInfo.Count == 0)
            {
                throw new Exception("No Device Information were found with query: " + AQS);
            }
            // I2C bus settings
            var settings = new Windows.Devices.I2c.I2cConnectionSettings(addr_PCF8591);

            settings.BusSpeed    = BusSpeed;
            settings.SharingMode = SharingMode;
            // Reteives the device from the I2C bus with the given ID.
            newADC.device = await Windows.Devices.I2c.I2cDevice.FromIdAsync(DevicesInfo[0].Id, settings);

            if (newADC.device == null)
            {
                throw new Exception("No I2C Device were found with ID " + DevicesInfo[0].Id);
            }
            return(newADC);
        }
Пример #16
0
        public async Task Initialize()
        {
            Debug.WriteLine("PCA9685::Initialize");

            try
            {
                var settings = new I2cConnectionSettings(PCA9685_Address);
                settings.BusSpeed = I2cBusSpeed.FastMode;

                string aqs = I2cDevice.GetDeviceSelector(I2CControllerName);
                var dis = await DeviceInformation.FindAllAsync(aqs);
                pca9685 = await I2cDevice.FromIdAsync(dis[0].Id, settings);
                if (pca9685 == null)
                {
                    Debug.WriteLine("PCA9685 failed to initialize");
                }

                await Begin();
                setPWMFreq(60);

            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace);
                throw;
            }

        }
Пример #17
0
        public async Task Init()
        {
            Debug.WriteLine("Initializing PCA9685");

            string aqs = I2cDevice.GetDeviceSelector();
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count == 0)
            {
                Debug.WriteLine("No I2C controllers were found on the system");
                return;
            }

            var settings = new I2cConnectionSettings(GeneralCallSlaveAddress);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            GeneralCallDev = await I2cDevice.FromIdAsync(dis[0].Id, settings);
            if (GeneralCallDev == null)
            {
                Debug.WriteLine(
                    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;
            }

            SoftwareReset();

            settings = new I2cConnectionSettings(SlaveAddress);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            Dev = await I2cDevice.FromIdAsync(dis[0].Id, settings);
            if (Dev == null)
            {
                Debug.WriteLine(
                    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;
            }

            Debug.WriteLine("PCA9685 I2C channels created");

            SetAllChannelsDutyCycle(0.0f);
            // Output drive mode is totem-pole not open drain
            WriteReg(MODE2, OUTDRV);
            // Turn-offi oscillator and acknowledge All-Call transfers
            WriteReg(MODE1, ALLCALL);
            await Task.Delay(1);

            byte mode1 = ReadReg(MODE1);
            // Trun-on oscillator
            mode1 &= unchecked((byte)~SLEEP);
            WriteReg(MODE1, mode1);
            await Task.Delay(1);

            Debug.WriteLine("PCA9685 initialization complete");
        }
Пример #18
0
		/// <summary>
		/// Opens a connection to the specified I2C device address.
		/// </summary>
		/// <param name="address">The 7-bit right aligned slave address (should not have 0x80
		/// bit set!)</param>
		/// <returns>A reference to the device</returns>
		/// <exception cref="IOException">If I2C1 cannot be opened</exception>
		private async Task<I2cDevice> OpenI2CConnection(int address) {
			I2cConnectionSettings settings = new I2cConnectionSettings(address);
			// Create settings to address device
			settings.BusSpeed = I2cBusSpeed.FastMode;
			settings.SharingMode = I2cSharingMode.Exclusive;
			if (i2cID == null)
				throw new IOException("Failed to find I2C controller matching " +
					I2C_CONTROLLER);
			return await I2cDevice.FromIdAsync(i2cID, settings);
		}
        private async static Task<I2cDevice> GetDevice(int slaveAddress)
        {
            string deviceSelector = I2cDevice.GetDeviceSelector();
            var deviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);

            if (deviceControllers.Count == 0) throw new InvalidOperationException("No i2c controller found.");
            var i2cSettings = new I2cConnectionSettings(0x20);
            i2cSettings.BusSpeed = I2cBusSpeed.FastMode;
            var device = await I2cDevice.FromIdAsync(deviceControllers[0].Id, i2cSettings);
            return device;
        }
Пример #20
0
 public virtual async Task Init(int n=0)
 {
     var i2CSettings = new I2cConnectionSettings(0x77)
     {
         BusSpeed = I2cBusSpeed.FastMode,
         SharingMode = I2cSharingMode.Shared
     };
     var i2c1 = I2cDevice.GetDeviceSelector("I2C1");
     var devices = await DeviceInformation.FindAllAsync(i2c1);
     sensor = await I2cDevice.FromIdAsync(devices[n].Id, i2CSettings);
 }
Пример #21
0
        public I2cDeviceBase(int slaveAddress, I2cBusSpeed busSpeed = I2cBusSpeed.FastMode, I2cSharingMode sharingMode = I2cSharingMode.Shared, string i2cControllerName = RaspberryPiI2cControllerName)
        {
            // Initialize I2C device
            Settings = new I2cConnectionSettings(slaveAddress)
            {
                BusSpeed = busSpeed,
                SharingMode = sharingMode
            };

            deviceSelector = I2cDevice.GetDeviceSelector(i2cControllerName);    /* Find the selector string for the I2C bus controller */
        }
        public async Task<I2cDevice> InitializeAsync()
        {
            string advanced_query_syntax = I2cDevice.GetDeviceSelector("I2C1");
            DeviceInformationCollection device_information_collection = await DeviceInformation.FindAllAsync(advanced_query_syntax);
            string deviceId = device_information_collection[0].Id;

            I2cConnectionSettings htdu21d_connection = new I2cConnectionSettings(HTDU21D_I2C_ADDRESS);
            htdu21d_connection.BusSpeed = I2cBusSpeed.FastMode;
            htdu21d_connection.SharingMode = I2cSharingMode.Shared;

            return await I2cDevice.FromIdAsync(deviceId, htdu21d_connection);
        }
Пример #23
0
        /* 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;
                }
            }
            catch (Exception ex)
            {
                Text_Status.Text = "I2C Initialization failed. Exception: " + ex.Message;
                return;
            }

            /* 
             * 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);
        }
Пример #24
0
        private async void InitializeSystem()
        {
            // initialize I2C communications
            try
            {
                string deviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);
                var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);

                //Port expander controlling the Button Panel
                var buttonPanelSettings = new I2cConnectionSettings(BUTTON_PANEL_I2C_ADDRESS);
                buttonPanelSettings.BusSpeed = I2cBusSpeed.FastMode;
                i2cButtonPanel = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, buttonPanelSettings);

                //Port expander controlling the LCD Screen
                var lcdSettings = new I2cConnectionSettings(LCD_SCREEN_I2C_ADDRESS);
                lcdSettings.BusSpeed = I2cBusSpeed.FastMode;
                i2cLcdScreen = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, lcdSettings);

                Screen = new LcdScreen(i2cLcdScreen);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message);
                return;
            }

            // initialize I2C Port Expander registers
            try
            {
                InitializeButtonPanel();
                InitializeLcd();

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message);
                return;
            }

            try
            {
                buttonStatusCheckTimer = new DispatcherTimer();
                buttonStatusCheckTimer.Interval = TimeSpan.FromMilliseconds(BUTTON_STATUS_CHECK_TIMER_INTERVAL);
                buttonStatusCheckTimer.Tick += ButtonStatusCheckTimer_Tick;
                buttonStatusCheckTimer.Start();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message);
                return;
            }
        }
Пример #25
0
		public async Task InitializeAsync()
		{
			string selector = I2cDevice.GetDeviceSelector();
			IReadOnlyList<DeviceInformation> i2cDevices = await DeviceInformation.FindAllAsync( selector );

			I2cConnectionSettings connectionSettings = new I2cConnectionSettings( ARDUINO_ADDRESS );
			this.arduino = await I2cDevice.FromIdAsync( i2cDevices[ 0 ].Id, connectionSettings );

			if( this.arduino == null )
			{
				throw new InvalidOperationException( $"The I2C device on address {ARDUINO_ADDRESS} cannot be found or is currently in use by another application." );
			}
		}
        private async Task InitI2CDevice() {
            try {
                var settings = new I2cConnectionSettings(I2C_ADDRESS);
                settings.BusSpeed = I2cBusSpeed.StandardMode;

                string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);  /* Find the selector string for the I2C bus controller                   */
                var dis = await DeviceInformation.FindAllAsync(aqs);            /* Find the I2C bus controller device with our selector string           */
                I2CDevice = await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings */
            }
            catch (Exception ex) {
                throw new Exception("I2C Initialization Failed", ex);
            }
        }
Пример #27
0
        public async void I2CInit()
        {
            var settings = new I2cConnectionSettings(0x40); // Arduino address
            settings.BusSpeed = I2cBusSpeed.StandardMode;
            settings.SharingMode = I2cSharingMode.Shared;
            settings.SlaveAddress = 0x40;
            string aqs = I2cDevice.GetDeviceSelector("I2C1");

            var dis = await DeviceInformation.FindAllAsync(aqs);
            Device = await I2cDevice.FromIdAsync(dis[0].Id, settings);

            // periodicTimer = new Timer(this.TimerCallback, null, 0, 500); // Create a timmer 
        }
        private async Task I2cConnect() {
            try {
                var settings = new I2cConnectionSettings(I2C_ADDR);
                settings.BusSpeed = I2cBusSpeed.FastMode;

                string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);  /* Find the selector string for the I2C bus controller                   */
                var dis = await DeviceInformation.FindAllAsync(aqs);            /* Find the I2C bus controller device with our selector string           */
                i2cDevice = await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings */
            }
            catch (Exception e) {
                throw new Exception("ht16k33 initisation problem: " + e.Message);
            }
        }
Пример #29
0
        private const string I2C_CONTROLLER_NAME = "I2C1";        // For Raspberry Pi 2, use I2C1

        public async Task<I2cDevice> GetI2cDevice(byte address)
        {
            string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);                     /* Get a selector string that will return all I2C controllers on the system */
            var dis = await DeviceInformation.FindAllAsync(aqs);            /* Find the I2C bus controller device with our selector string           */
            if (dis.Count == 0)
            {
                throw new InvalidOperationException("No I2C controllers were found on the system");
            }

            var settings = new I2cConnectionSettings(address);
            settings.BusSpeed = I2cBusSpeed.FastMode;

            return await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings */
        }
Пример #30
0
        private void InitAccelerometer()
        {
            var settings = new I2cConnectionSettings(SLAVE_ADDRESS) { BusSpeed = I2cBusSpeed.FastMode };
            var aqs = I2cDevice.GetDeviceSelector();
            var dis = DeviceInformation.FindAllAsync(aqs);

            //Get DeviceInformation:
            while (dis.Status != AsyncStatus.Completed) { }
            var d = dis.GetResults()[0];

            //Get I2cDevice:
            var s = I2cDevice.FromIdAsync(d.Id, settings);
            while (s.Status != AsyncStatus.Completed) { }
            m_pAccelerometer = s.GetResults();
        }
Пример #31
0
		private static async Task<MainI2CDevice> CreateDisplayJoystickI2CDevice()
		{
			string aqsFilter = I2cDevice.GetDeviceSelector();

			DeviceInformationCollection collection = await DeviceInformation.FindAllAsync(aqsFilter);

			I2cConnectionSettings settings = new I2cConnectionSettings(DeviceAddress)
			{
				BusSpeed = I2cBusSpeed.StandardMode
			};

			I2cDevice i2CDevice = await I2cDevice.FromIdAsync(collection[0].Id, settings);

			return new MainI2CDevice(i2CDevice);
		}
Пример #32
0
        internal I2cDevice(string i2cBus, I2cConnectionSettings settings)
        {
            // generate a unique ID for the device by joining the I2C bus ID and the slave address, should be pretty unique
            // the encoding is (I2C bus number x 1000 + slave address)
            // i2cBus is an ASCII string with the bus name in format 'I2Cn'
            // need to grab 'n' from the string and convert that to the integer value from the ASCII code (do this by subtracting 48 from the char value)
            var controllerId = i2cBus[3] - 48;
            var deviceId     = (controllerId * deviceUniqueIdMultiplier) + settings.SlaveAddress;

            I2cController controller = I2cController.FindController(controllerId);

            if (controller == null)
            {
                // this controller doesn't exist yet, create it...
                controller = new I2cController(i2cBus);
            }

            // check if this device ID already exists
            var device = FindDevice(controller, deviceId);

            if (device == null)
            {
                // device doesn't exist, create it...
                _connectionSettings = new I2cConnectionSettings(settings.SlaveAddress)
                {
                    BusSpeed    = settings.BusSpeed,
                    SharingMode = settings.SharingMode
                };

                // save device ID
                _deviceId = deviceId;

                // call native init to allow HAL/PAL inits related with I2C hardware
                NativeInit();

                // ... and add this device
                controller.DeviceCollection.Add(this);

                _syncLock = new object();
            }
            else
            {
                // this device already exists, throw an exception
                throw new I2cDeviceAlreadyInUseException();
            }
        }
Пример #33
0
        /// <summary>
        /// Initializes new instance of Windows10I2cDevice that will use the specified settings to communicate with the I2C device.
        /// </summary>
        /// <param name="settings">The connection settings of a device on an I2C bus.</param>
        public Windows10I2cDevice(I2cConnectionSettings settings)
        {
            _settings = settings;
            var winSettings = new WinI2c.I2cConnectionSettings(settings.DeviceAddress);

            string busFriendlyName = $"I2C{settings.BusId}";
            string deviceSelector  = WinI2c.I2cDevice.GetDeviceSelector(busFriendlyName);

            DeviceInformationCollection deviceInformationCollection = DeviceInformation.FindAllAsync(deviceSelector).WaitForCompletion();

            if (deviceInformationCollection.Count == 0)
            {
                throw new ArgumentException($"No I2C device exists for bus ID {settings.BusId}.", $"{nameof(settings)}.{nameof(settings.BusId)}");
            }

            _winI2cDevice = WinI2c.I2cDevice.FromIdAsync(deviceInformationCollection[0].Id, winSettings).WaitForCompletion();
            if (_winI2cDevice == null)
            {
                throw new PlatformNotSupportedException($"I2C devices are not supported.");
            }
        }
Пример #34
0
        /// <summary>
        /// Constructs a new I2cDevice object.
        /// </summary>
        /// <param name="slaveAddress">The bus address of the I²C device. Only 7-bit addressing is supported, so the
        ///     range of valid values is from 8 to 119.</param>
        /// <param name="busSpeed"></param>
        internal I2cDevice(string deviceId, I2cConnectionSettings settings)
        {
            m_deviceId = deviceId.Substring(0, deviceId.Length);
            m_settings = new I2cConnectionSettings(settings);

            int clockRateKhz = 100;

            if (settings.BusSpeed == I2cBusSpeed.FastMode)
            {
                clockRateKhz = 400;
            }

            m_configuration = new I2CDevice.Configuration((ushort)settings.SlaveAddress, clockRateKhz);

            lock (s_deviceLock)
            {
                if (s_device == null)
                {
                    s_device = new I2CDevice(m_configuration);
                }

                ++s_deviceRefs;
            }
        }
 /// <summary>
 /// Construct a copy of an I2cConnectionSettings object.
 /// </summary>
 /// <param name="source">Source object to copy from.</param>
 internal I2cConnectionSettings(I2cConnectionSettings source)
 {
     m_slaveAddress = source.m_slaveAddress;
     m_busSpeed     = source.m_busSpeed;
     m_sharingMode  = source.m_sharingMode;
 }
Пример #36
0
 /// <summary>
 /// Retrieves an <see cref="I2cDevice"/> object for the inter-integrated circuit (I2C) bus controller that has the specified plug and play device identifier, using the specified connection settings.
 /// </summary>
 /// <param name="i2cBus">The plug and play device identifier of the I2C bus controller for which you want to create an <see cref="I2cDevice"/> object.</param>
 /// <param name="settings">The connection settings to use for communication with the I2C bus controller that deviceId specifies.</param>
 /// <returns>An operation that returns the I2cDevice object.</returns>
 /// <remarks>
 /// This method is specific to nanoFramework. The equivalent method in the UWP API is: FromIdAsync.
 /// </remarks>
 /// <exception cref="I2cDeviceAlreadyInUseException">T</exception>
 public static I2cDevice FromId(String i2cBus, I2cConnectionSettings settings)
 {
     return(new I2cDevice(i2cBus, settings));
 }
 /// <summary>
 /// Initializes a copy of a <see cref="I2cConnectionSettings"/> object.
 /// </summary>
 /// <param name="settings">Object to copy from.</param>
 internal I2cConnectionSettings(I2cConnectionSettings settings)
 {
     _slaveAddress = settings.SlaveAddress;
     _busSpeed     = settings.BusSpeed;
     _sharingMode  = settings.SharingMode;
 }
 /// <summary>
 /// Gets the I2C device with the specified settings.
 /// </summary>
 /// <param name="settings"></param>
 /// <returns>The desired connection settings.</returns>
 public I2cDevice GetDevice(I2cConnectionSettings settings)
 {
     //TODO: fix return value. Should return an existing device (if any)
     return(new I2cDevice(String.Empty, settings));
 }