public override void Execute(I2cDevice i2CDevice) { i2CDevice.Write(GenerateRegisterSensorPackage()); byte[] buffer = new byte[9]; i2CDevice.Read(buffer); ParseResponse(buffer); }
public static void Write(I2cDevice device, byte reg, byte command, string exceptionMessage) { try { byte[] buffer = { reg, command }; device.Write(buffer); } catch (Exception exception) { throw new SensorException(exceptionMessage, exception); } }
public static bool Write(I2cDevice device, byte reg, byte command) { byte[] val = new byte[2]; val[0] = reg; val[1] = command; try { device.Write(val); return true; } catch { return false; } }
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; } }
/// <summary> /// Displays the GPS data on the screen. /// </summary> /// <param name="device">The I2C device</param> /// <param name="index">0 for Venus, 1 for Copernicus</param> /// <param name="display">An array containing 4 text boxes - lat, lon, alt, vel</param> private void GPSFetch(I2cDevice device, int index, params TextBlock[] display) { byte[] data = new byte[17]; // Receive 17 bytes starting from lat register (0x10), where 0x30 is the second GPS byte address = (byte)(((index == 0) ? 0x00 : 0x20) + 0x10); device.WriteRead(new byte[] { address }, data); // Convert all to correct types double lat = BitConverter.ToInt32(data, 0) * 1E-6; double lon = BitConverter.ToInt32(data, 4) * 1E-6; double vel = BitConverter.ToInt16(data, 8) * 1E-1; double head = BitConverter.ToInt16(data, 10) * 1E-1; double alt = BitConverter.ToInt32(data, 12) * 1E-2; int satellites = (int)data[16]; // Write to the screen if (satellites > 0) { display[0].Text = lat.ToString("F6"); display[1].Text = lon.ToString("F6"); display[2].Text = alt.ToString("F1"); display[3].Text = vel.ToString("F1"); } else { display[0].Text = "NO FIX"; display[1].Text = satellites.ToString(); display[2].Text = ""; display[3].Text = ""; } }
internal GoPiGo(I2cDevice device) { if (device == null) throw new ArgumentNullException(nameof(device)); DirectAccess = device; _motorController = new MotorController(this); _encoderController = new EncoderController(this); }
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; } }
protected override void Dispose(bool disposing) { _winI2cDevice?.Dispose(); _winI2cDevice = null !; base.Dispose(disposing); }
//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 override void Dispose(bool disposing) { _winI2cDevice?.Dispose(); _winI2cDevice = null; base.Dispose(disposing); }
public async Task InitializeAsync() { var dis = await DeviceInformation.FindAllAsync(deviceSelector); /* Find the I2C bus controller device with our selector string */ Device = await I2cDevice.FromIdAsync(dis[0].Id, Settings); /* Create an I2cDevice with our selected bus controller and I2C settings */ await InitializeSensorAsync(); }
protected override Task DoSwitchOff() { RemoveDisposables(Device); Device = null; controller = null; return(Task.CompletedTask); }
/// <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."); }
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 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(); }
public static UInt16 Read16Bits(I2cDevice device, byte reg, ByteOrder byteOrder, string exceptionMessage) { try { byte[] addr = { reg }; byte[] data = new byte[2]; device.WriteRead(addr, data); switch (byteOrder) { case ByteOrder.BigEndian: return (UInt16)((data[0] << 8) | data[1]); case ByteOrder.LittleEndian: return (UInt16)((data[1] << 8) | data[0]); default: throw new SensorException($"Unsupported byte order {byteOrder}"); } } catch (Exception exception) { throw new SensorException(exceptionMessage, exception); } }
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(); }
public MMA8453(I2cDevice device) { this.device = device; this.write = new byte[1] { 0x01 }; this.read = new byte[6]; this.disposed = false; this.device.Write(new byte[] { 0x2A, 0x01 }); }
internal RgbLcdDisplay(I2cDevice rgbDevice, I2cDevice textDevice) { if (rgbDevice == null) throw new ArgumentNullException(nameof(rgbDevice)); if (textDevice == null) throw new ArgumentNullException(nameof(textDevice)); RgbDirectAccess = rgbDevice; TextDirectAccess = textDevice; }
private void InitPyGlow(I2cDevice device) { device.Write(new byte[] { 0x00, 0x01 }); device.Write(new byte[] { 0x13, 0xFF }); device.Write(new byte[] { 0x14, 0xFF }); device.Write(new byte[] { 0x15, 0xFF }); ClearLeds(device); }
//constructor public SSD1603Controller(I2cDevice device, GpioPin pinReset = null) { _busType = BusTypes.I2C; _i2cDevic = device; _pinReset = pinReset; Empty(); Debug.WriteLine(string.Format("SSD1603 controller on {0} created", _busType)); }
public async Task initializeAsync() { _device = await new I2CManager().initializeDevice(0x70); write8(__HT16K33_REGISTER_SYSTEM_SETUP | 0x01, 0x00); setBlinkRate(__HT16K33_BLINKRATE_OFF); setBrightness(15); clear(); }
protected Mb85rcvDevice(I2cDevice device, int size) { // Validate if (device == null) throw new ArgumentNullException(nameof(device)); // Initialize members Hardware = device; Size = size; }
public static bool Read(I2cDevice device, byte reg, byte[] data) { byte[] addr = new byte[1]; addr[0] = reg; try { device.WriteRead(addr, data); return true; } catch { return false; } }
public async Task<bool> Init(int address) { if (_i2Cdevice != null) { return true; } _i2Cdevice = await I2CDeviceCache.GetDevice(address, "I2C1"); return _i2Cdevice != null; }
public CY8C9560A(I2cDevice device, GpioPin interrupt) { this.device = device; this.interrupt = interrupt; this.disposed = false; this.interruptRegistrations = new Dictionary<Pin, Action<bool>>(); //this.shadowRegisters = new byte[0x2D - 0x08]; this.interrupt.ValueChanged += this.OnInterrupt; //this.i2c.ReadRegisters(0x08, this.shadowRegisters); }
public async void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); String aqs = I2cDevice.GetDeviceSelector("I2C1"); IReadOnlyList<DeviceInformation> dis = await DeviceInformation.FindAllAsync(aqs); //Ox40 was determined by looking at the datasheet for the device sensor = await I2cDevice.FromIdAsync(dis[0].Id, new I2cConnectionSettings(0x40)); timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500)); }
public async Task<bool> OpenConnection(string i2cMasterId) { //Establish I2C connection __connection = await I2cDevice.FromIdAsync(i2cMasterId, new I2cConnectionSettings(this.__i2cAddress)); // soft reset I2cTransferResult result = __connection.WritePartial(new byte[] { Registers.MPR121_SOFTRESET, 0x63 }); if (result.Status == I2cTransferStatus.SlaveAddressNotAcknowledged) { throw new Exception(string.Format("MPR121 at address {0} not responding.", this.__i2cAddress)); } await Task.Delay(1); writeRegister(Registers.MPR121_ECR, 0x0); byte c = readRegister8(Registers.MPR121_CONFIG2); if (c != 0x24) return false; SetThresholds(12, 6); //Section A Registers - Ref: AN3944, MPR121 Quick Start Guide //This group of setting controls the filtering of the system when the data is greater than the baseline. //Settings from Adafruit Libary.. Most probably callibrated for the Adafruit's MPR121 breakout board. writeRegister(Registers.MPR121_MHDR, 0x01); writeRegister(Registers.MPR121_NHDR, 0x01); writeRegister(Registers.MPR121_NCLR, 0x0E); writeRegister(Registers.MPR121_FDLR, 0x00); //Section B Registers - Ref: AN3944, MPR121 Quick Start Guide writeRegister(Registers.MPR121_MHDF, 0x01); writeRegister(Registers.MPR121_NHDF, 0x05); writeRegister(Registers.MPR121_NCLF, 0x01); writeRegister(Registers.MPR121_FDLF, 0x00); writeRegister(Registers.MPR121_NHDT, 0x00); writeRegister(Registers.MPR121_NCLT, 0x00); writeRegister(Registers.MPR121_FDLT, 0x00); writeRegister(Registers.MPR121_DEBOUNCE, 0); writeRegister(Registers.MPR121_CONFIG1, 0x10); // default, 16uA charge current writeRegister(Registers.MPR121_CONFIG2, 0x20); // 0.5uS encoding, 1ms period writeRegister(Registers.MPR121_ECR, 0x8F); // start with first 5 bits of baseline tracking InitMPR121TouchInterrupt(); return true; }
/* 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); }
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; } }
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); } }
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 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); } }
protected override async Task DoSwitchOn() { controller = await I2cController.GetDefaultAsync(); ArgumentValidation.NonNull(controller, nameof(I2cController)); var connectionSettings = new I2cConnectionSettings(Address) { BusSpeed = BusSpeed, SharingMode = SharingMode }; Device = controller.GetDevice(connectionSettings); AddDisposables(Device); }
/// <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."); } }