public async Task Init() { var deviceSelector = I2cDevice.GetDeviceSelector(); var controllers = await DeviceInformation.FindAllAsync(deviceSelector); _bme280 = await I2cDevice.FromIdAsync(controllers[0].Id, new I2cConnectionSettings(ADDR) { BusSpeed = I2cBusSpeed.FastMode }); ValidateChipId(); SetTrimmingParamaters(); _bme280.Write(new byte[] { REGISTER_CTRL_HUM, CTRL_HUM_OSRS_H }); _bme280.Write(new byte[] { REGISTER_CTRL_MEAS, CTRL_MEAS_OSRS_P | CTRL_MEAS_OSRS_T | CTRL_MEAS_MODE }); _bme280.Write(new byte[] { REGISTER_CONFIG, CONFIG_TSB | CONFIG_FILTER }); }
private async void InitI2CAccel() { 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 */ if (dis.Count == 0) { Text_Status.Text = "No I2C controllers were found on the system"; return; } var settings = new I2cConnectionSettings(ACCEL_I2C_ADDR); settings.BusSpeed = I2cBusSpeed.FastMode; 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; } /* * 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); }
public override void Execute(I2cDevice i2CDevice) { i2CDevice.Write(GenerateClearSignalCachePackage()); int offset = 0; while (offset < _signal.Length) { var buffer = _signal.Skip(offset).Take(30).ToArray(); offset += buffer.Length; i2CDevice.Write(GenerateFillSignalCachePackage(buffer)); } i2CDevice.Write(GenerateSendCachedSignalPackage()); }
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; } }
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); } }
private async Task InitializeAsync() { // Initializing the ADS 1115 // Initialisation du ADS 1115 var i2CSettings = new I2cConnectionSettings(0x48) { BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Shared }; var i2C1 = I2cDevice.GetDeviceSelector("I2C1"); var devices = await DeviceInformation.FindAllAsync(i2C1); _converter = await I2cDevice.FromIdAsync(devices[0].Id, i2CSettings); // Write in the config register. 0xc4 0Xe0 = 1100010011100000 // = listen to A0, default gain, continuous conversion, 860 SPS, assert after one conversion (= READY signal) // see http://www.adafruit.com/datasheets/ads1115.pdf p18 for details // Ecrit dans le registre config. 0xc4 0Xe0 = 1100010011100000 // = ecouter A0, gain par défaut, conversion continue, 860 SPS, signal READY après chaque conversion // see http://www.adafruit.com/datasheets/ads1115.pdf p18 for details _converter.Write(new byte[] { 0x01, 0xc4, 0xe0 }); // Configure the Lo_thresh (0x02) and Hi_Thresh (0x03) registers so the READY signal will be sent // Configure les registres Lo_thresh (0x02) et Hi_Thresh (0x03) pour que le signal READY soit envoyé _converter.Write(new byte[] { 0x02, 0x00, 0x00 }); _converter.Write(new byte[] { 0x03, 0xff, 0xff }); // Instanciate the READY pin and listen to change // Instancie la broche REASY et écoute les changements var gpio = GpioController.GetDefault(); _inGpioPin = gpio.OpenPin(READY_PIN); _inGpioPin.ValueChanged += InGpioPinOnValueChanged; }
private byte PCA9685_MODE1 = 0x00; // location for Mode1 register address #endregion Fields #region Constructors public PCA9685(I2cDevice device) { m_device = device; try { device.Write(new byte[] { PCA9685_MODE1, 0x21 }); AllOff(); } catch (Exception e) { Debug.WriteLine(e.Message); } }
/// <summary> /// Measures data from the HTU21D. /// </summary> /// <param name="device">The I2C device</param> /// <param name="command">MEASURE_TEMP or MEASURE_HUMIDITY</param> /// <param param name="gsl">The global sensor lock</param> /// <returns>The measured value in quids FS</returns> private async Task<int> Measure(I2cDevice device, int command, object gsl) { byte[] data = new byte[3]; // No Hold Master mode lock (gsl) { device.Write(new byte[] { (byte)command }); } await Task.Delay(30); // Max measurement time is 50 ms for temperature and 16 ms for humidity for (int i = 0; i < 3; i++) { await Task.Delay(15); try { lock (gsl) { device.Read(data); } // Data is MSB-first in the first 2 bytes int value = data[1] & 0xFC; return value | ((data[0] & 0xFF) << 8); } catch (IOException) { // Swallow the NACK and try again in 10 ms } } throw new IOException("Still measuring, increase delay!"); }
/// <summary> /// Writes a byte to the I2C device. /// </summary> /// <param name="data">The byte to be written to the I2C device.</param> public override void WriteByte(byte data) { _winI2cDevice.Write(new[] { data }); }
/// <summary> /// Initialize the Sparkfun Weather Shield /// </summary> /// <remarks> /// Setup and instantiate the I2C device objects for the HTDU21D and the MPL3115A2 /// and initialize the blue and green status LEDs. /// </remarks> internal async Task BeginAsync() { /* * Acquire the GPIO controller * MSDN GPIO Reference: https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.gpio.aspx * * Get the default GpioController */ GpioController gpio = GpioController.GetDefault(); /* * Test to see if the GPIO controller is available. * * If the GPIO controller is not available, this is * a good indicator the app has been deployed to a * computing environment that is not capable of * controlling the weather shield. Therefore we * will disable the weather shield functionality to * handle the failure case gracefully. This allows * the invoking application to remain deployable * across the Universal Windows Platform. */ if ( null == gpio ) { available = false; enable = false; return; } /* * Initialize the blue LED and set to "off" * * Instantiate the blue LED pin object * Write the GPIO pin value of low on the pin * Set the GPIO pin drive mode to output */ BlueLEDPin = gpio.OpenPin(STATUS_LED_BLUE_PIN, GpioSharingMode.Exclusive); BlueLEDPin.Write(GpioPinValue.Low); BlueLEDPin.SetDriveMode(GpioPinDriveMode.Output); /* * Initialize the green LED and set to "off" * * Instantiate the green LED pin object * Write the GPIO pin value of low on the pin * Set the GPIO pin drive mode to output */ GreenLEDPin = gpio.OpenPin(STATUS_LED_GREEN_PIN, GpioSharingMode.Exclusive); GreenLEDPin.Write(GpioPinValue.Low); GreenLEDPin.SetDriveMode(GpioPinDriveMode.Output); /* * Acquire the I2C device * MSDN I2C Reference: https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.i2c.aspx * * Use the I2cDevice device selector to create an advanced query syntax string * Use the Windows.Devices.Enumeration.DeviceInformation class to create a collection using the advanced query syntax string * Take the device id of the first device in the collection */ string advanced_query_syntax = I2cDevice.GetDeviceSelector("I2C1"); DeviceInformationCollection device_information_collection = await DeviceInformation.FindAllAsync(advanced_query_syntax); string deviceId = device_information_collection[0].Id; /* * Establish an I2C connection to the HTDU21D * * Instantiate the I2cConnectionSettings using the device address of the HTDU21D * - Set the I2C bus speed of connection to fast mode * - Set the I2C sharing mode of the connection to shared * * Instantiate the the HTDU21D I2C device using the device id and the I2cConnectionSettings */ I2cConnectionSettings htdu21d_connection = new I2cConnectionSettings(HTDU21D_I2C_ADDRESS); htdu21d_connection.BusSpeed = I2cBusSpeed.FastMode; htdu21d_connection.SharingMode = I2cSharingMode.Shared; htdu21d = await I2cDevice.FromIdAsync(deviceId, htdu21d_connection); /* * Establish an I2C connection to the MPL3115A2 * * Instantiate the I2cConnectionSettings using the device address of the MPL3115A2 * - Set the I2C bus speed of connection to fast mode * - Set the I2C sharing mode of the connection to shared * * Instantiate the the MPL3115A2 I2C device using the device id and the I2cConnectionSettings */ I2cConnectionSettings mpl3115a2_connection = new I2cConnectionSettings(MPL3115A2_I2C_ADDRESS); mpl3115a2_connection.BusSpeed = I2cBusSpeed.FastMode; mpl3115a2_connection.SharingMode = I2cSharingMode.Shared; mpl3115a2 = await I2cDevice.FromIdAsync(deviceId, mpl3115a2_connection); /* * Test to see if the I2C devices are available. * * If the I2C devices are not available, this is * a good indicator the weather shield is either * missing or configured incorrectly. Therefore we * will disable the weather shield functionality to * handle the failure case gracefully. This allows * the invoking application to remain deployable * across the Universal Windows Platform. * * NOTE: For a more detailed description of the I2C * transactions used for testing below, please * refer to the "Raw___" functions provided below. */ if (null == mpl3115a2) { available = false; enable = false; return; } else { byte[] reg_data = new byte[1]; try { mpl3115a2.WriteRead(new byte[] { CTRL_REG1 }, reg_data); reg_data[0] &= 0xFE; // ensure SBYB (bit 0) is set to STANDBY reg_data[0] |= 0x02; // ensure OST (bit 1) is set to initiate measurement mpl3115a2.Write(new byte[] { CTRL_REG1, reg_data[0] }); } catch { available = false; enable = false; return; } } if (null == htdu21d) { available = false; enable = false; return; } else { byte[] i2c_temperature_data = new byte[3]; try { htdu21d.WriteRead(new byte[] { SAMPLE_TEMPERATURE_HOLD }, i2c_temperature_data); } catch { available = false; enable = false; return; } } available = true; enable = true; }
public override string Init(I2cDevice device) { // Trigger a soft reset which will wipe the registers to defaults // This means that resolution is 12-bit RH/14-bit Temperature device.Write(new byte[] { 0xFE }); return "TEMP_C,REL_HUMID"; }
private async void InitI2C() { byte[] i2CWriteBuffer; byte[] i2CReadBuffer; byte bitMask; // Inicjalizacja I2C - urządzenie z RPI2 string deviceSelector = I2cDevice.GetDeviceSelector(); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); if (i2cDeviceControllers.Count == 0) { return; } //Ustawienia dla MCP230008 var i2cSettings = new I2cConnectionSettings(I2C_ADDR_MCP23008); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; i2cMCP23008 = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cMCP23008 == null) { return; } //Ustawienia dla PCF8591 i2cSettings.SlaveAddress = I2C_ADDR_PCF8591; i2cPCF8591 = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cPCF8591 == null) { return; } //Ustawienia dla Arduino i2cSettings.SlaveAddress = I2C_ADDR_ARDUINO; i2cArduino = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cArduino == null) { return; } // Inicjalizacja port Expander // Za: https://ms-iot.github.io/content/en-US/win10/samples/I2CPortExpander.htm try { i2CReadBuffer = new byte[1]; i2cMCP23008.WriteRead(new byte[] { MCP23008_IODIR }, i2CReadBuffer); iodirRegister = i2CReadBuffer[0]; i2cMCP23008.WriteRead(new byte[] { MCP23008_GPIO }, i2CReadBuffer); gpioRegister = i2CReadBuffer[0]; i2cMCP23008.WriteRead(new byte[] { MCP23008_OLAT }, i2CReadBuffer); olatRegister = i2CReadBuffer[0]; // Konfiguracja PIN-a z laserem na 1; reszta bez zmian olatRegister |= LED_GPIO_PIN; i2CWriteBuffer = new byte[] { MCP23008_OLAT, olatRegister }; i2cMCP23008.Write(i2CWriteBuffer); bitMask = (byte)(0xFF ^ LED_GPIO_PIN); // Tylko nasz PIN będzie miał maskę 0 - reszta będzie równa 1, co spowoduje że nie zmienią wartości iodirRegister &= bitMask; i2CWriteBuffer = new byte[] { MCP23008_IODIR, iodirRegister }; i2cMCP23008.Write(i2CWriteBuffer); } catch (Exception e) { return; } //Komunikacja z Arduino byte[] wbuffer = new byte[] { 1, 2, 3, 4, 5, 6 }; byte[] rbuffer = new byte[2]; //Wysłanie liczb do dodania i2cArduino.Write(wbuffer); await Task.Delay(1000); //Odczytanie wyniku var result = i2cArduino.ReadPartial(rbuffer); //Wyświetlenie int sum = (((int)rbuffer[1]) << 8) + (int)rbuffer[0]; Debug.WriteLine($"Suma:{sum}"); //Błyskanie laserem co sekundę m_timer = new DispatcherTimer(); m_timer.Interval = TimeSpan.FromMilliseconds(1000); m_timer.Tick += timer_Tick; m_timer.Start(); //Zapis "trójkąta" do PCF8591 (w pętli, nieskończonej) await WritePCF8591(); }
private void CommitLeds(I2cDevice device) { device.Write(new byte[] { 0x16, 0xFF }); }
private void SetArm(I2cDevice device, int arm, byte brightness) { for (int band = INNER_BAND; band <= OUTER_BAND; band++) { device.Write(new byte[] { _arms[arm][band], brightness }); } CommitLeds(device); }
/// <summary> /// Initialize I2C-Device (Gyroscope). /// </summary> private void InitGyroscope() { 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_pGyroscope = s.GetResults(); if(m_pGyroscope == null) throw new Exception("Error: m_pGyroscope == null"); //Reset Gyroscope: m_pGyroscope.Write(new byte[] { CTRL1_ADDRESS, 0x00 }); m_pGyroscope.Write(new byte[] { CTRL1_ADDRESS, 0x0F }); m_pGyroscope.Write(new byte[] { CTRL3_ADDRESS, 0x08 }); m_pGyroscope.Write(new byte[] { CTRL4_ADDRESS, 0x00 }); }
public override void Execute(I2cDevice i2CDevice) { i2CDevice.Write(ToPackage()); }
//private bool isLedOn = false; private async void StartI2C() { byte[] i2CWriteBuffer; byte[] i2CReadBuffer; byte bitMask; // initialize I2C communications try { var i2cSettings = new I2cConnectionSettings(PORT_EXPANDER_I2C_ADDRESS); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; string deviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); Debug.WriteLine(string.Format("i2cPortExander {0}", i2cPortExpander.DeviceId)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message); return; } // initialize I2C Port Expander registers try { // initialize local copies of the IODIR, GPIO, and OLAT registers i2CReadBuffer = new byte[1]; // read in each register value on register at a time (could do this all at once but // for example clarity purposes we do it this way) i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_IODIRA_REGISTER_ADDRESS }, i2CReadBuffer); iodirRegister = i2CReadBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_GPIOA_REGISTER_ADDRESS }, i2CReadBuffer); gpioRegister = i2CReadBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_OLATA_REGISTER_ADDRESS }, i2CReadBuffer); olatRegister = i2CReadBuffer[0]; // configure the LED pin output to be logic high, leave the other pins as they are. olatRegister |= LED_GPIO_PIN; i2CWriteBuffer = new byte[] { PORT_EXPANDER_OLATA_REGISTER_ADDRESS, olatRegister }; i2cPortExpander.Write(i2CWriteBuffer); // configure only the LED pin to be an output and leave the other pins as they are. // input is logic low, output is logic high bitMask = (byte)(0xFF ^ LED_GPIO_PIN); // set the LED GPIO pin mask bit to '0', all other bits to '1' iodirRegister &= bitMask; i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIRA_REGISTER_ADDRESS, iodirRegister }; i2cPortExpander.Write(i2CWriteBuffer); Debug.WriteLine(string.Format("iodirRegister: {0}", iodirRegister.ToString())); Debug.WriteLine(string.Format("gpioRegister: {0}", gpioRegister.ToString())); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(true); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(false); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(true); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(false); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(true); Debug.WriteLine(string.Format("olatRegister: {0}", olatRegister.ToString())); SetLED(false); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message); return; } }
private async void InitializeSystem(byte[] pinDirection, int inputCheckInterval) { byte[] readBuffer; byte bitMask0; byte bitMask1; // initialize I2C communications string deviceSelector = I2cDevice.GetDeviceSelector(); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); if (i2cDeviceControllers.Count == 0) { throw new NullReferenceException("No I2C controllers were found on this system. Maybe it isn't a Raspberry Pi?"); } var i2cSettings = new I2cConnectionSettings(_portExpanderAddress); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cPortExpander == null) { throw new Exception(string.Format( "Slave address {0} is currently in use on {1}. " + "Please ensure that no other applications are using I2C.", i2cSettings.SlaveAddress, i2cDeviceControllers[0].Id)); } // initialize I2C Port Expander registers try { // initialize local copies of the IODIR, GPIO, and OLAT registers readBuffer = new byte[1]; // read in each register value on register at a time. I'm doing this one at a time // to keep it straight in my head. i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_IODIR0_REGISTER_ADDRESS }, readBuffer); iodir0Register = readBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_IODIR1_REGISTER_ADDRESS }, readBuffer); iodir1Register = readBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_GPIO0_REGISTER_ADDRESS }, readBuffer); gpio0Register = readBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_GPIO1_REGISTER_ADDRESS }, readBuffer); gpio1Register = readBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_OLAT0_REGISTER_ADDRESS }, readBuffer); olat0Register = readBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_OLAT1_REGISTER_ADDRESS }, readBuffer); olat1Register = readBuffer[0]; // configure the output pins to be logic high, leave the other pins as they are. olat0Register |= pinDirection[0]; _i2CWriteBuffer = new byte[] { PORT_EXPANDER_OLAT0_REGISTER_ADDRESS, olat0Register }; i2cPortExpander.Write(_i2CWriteBuffer); olat1Register |= pinDirection[1]; _i2CWriteBuffer = new byte[] { PORT_EXPANDER_OLAT1_REGISTER_ADDRESS, olat1Register }; i2cPortExpander.Write(_i2CWriteBuffer); // configure the specified pins to be an output and leave the other pins as they are. // input is logic low, output is logic high bitMask0 = (byte)(0xFF ^ pinDirection[0]); // set the GPIO pin mask bit to '0' for bits that are set, all other bits to '1' iodir0Register &= bitMask0; _i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIR0_REGISTER_ADDRESS, iodir0Register }; i2cPortExpander.Write(_i2CWriteBuffer); bitMask1 = (byte)(0xFF ^ pinDirection[1]); // set the GPIO pin mask bit to '0' for bits that are set, all other bits to '1' iodir1Register &= bitMask1; _i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIR1_REGISTER_ADDRESS, iodir1Register }; i2cPortExpander.Write(_i2CWriteBuffer); } catch (Exception e) { throw new Exception("Failed to initialize I2C port expander: " + e.Message); } // setup our input checking timer inputStatusCheckTimer = new DispatcherTimer(); inputStatusCheckTimer.Interval = TimeSpan.FromMilliseconds(inputCheckInterval); inputStatusCheckTimer.Tick += InputStatusCheckTimer_Tick; inputStatusCheckTimer.Start(); }
public async void InitSPI() { String aqs = I2cDevice.GetDeviceSelector("I2C1"); var deviceInfo = await DeviceInformation.FindAllAsync(aqs); sensor = await I2cDevice.FromIdAsync(deviceInfo[0].Id, new I2cConnectionSettings(0x44)); byte[] resetCommand = { 0x30, 0xA2 }; sensor.Write(resetCommand); TPtimer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(ENVTime)); // .FromMilliseconds(1000)); }
private async void InitI2CAccel() { try { string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME); var dis = await DeviceInformation.FindAllAsync(aqs); var settings = new I2cConnectionSettings(ACCEL_I2C_ADDR); settings.BusSpeed = I2cBusSpeed.FastMode; // var aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME); // var dis = await DeviceInformation.FindAllAsync(aqs); I2CAccel = await I2cDevice.FromIdAsync(dis[0].Id, settings); byte[] WriteBuf_DataFormat = new byte[] { ACCEL_REG_DATA_FORMAT, 0x01 }; byte[] WriteBuf_PowerControl = new byte[] { ACCEL_REG_POWER_CONTROL, 0x08 }; I2CAccel.Write(WriteBuf_DataFormat); I2CAccel.Write(WriteBuf_PowerControl); } catch (Exception ex) { } }
private async Task Init() { var deviceSelector = I2cDevice.GetDeviceSelector(); var controllers = await DeviceInformation.FindAllAsync(deviceSelector); _mcp3425 = await I2cDevice.FromIdAsync(controllers[0].Id, new I2cConnectionSettings(0x68) { BusSpeed = I2cBusSpeed.FastMode }); _mcp3425.Write(new byte[] { 0x98 }); // 16bit _tsl2561 = await I2cDevice.FromIdAsync(controllers[0].Id, new I2cConnectionSettings(0x39) { BusSpeed = I2cBusSpeed.FastMode }); _tsl2561.Write(new byte[] { 0x80, 0x03 }); // power on :) // spi stuff var settings = new SpiConnectionSettings(0); settings.ClockFrequency = 10000000; settings.Mode = SpiMode.Mode0; string spiAqs = SpiDevice.GetDeviceSelector("SPI0"); var deviceInformation = await DeviceInformation.FindAllAsync(spiAqs); _spiDevice = await SpiDevice.FromIdAsync(deviceInformation[0].Id, settings); endFrame = new byte[(int)Math.Ceiling(leds / 16d)]; for (var i = 0; i < endFrame.Length; i++) { endFrame[i] = 0x0; } // start _spiDevice.Write(new byte[4]); // all off _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); _spiDevice.Write(new byte[] { 0xE0, 0x0, 0x0, 0x0 }); // end _spiDevice.Write(endFrame); }
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"); }
private void ClearLeds(I2cDevice device) { for (int band = INNER_BAND; band <= OUTER_BAND; band++) { device.Write(new byte[] { _arms[0][band], 0 }); device.Write(new byte[] { _arms[1][band], 0 }); device.Write(new byte[] { _arms[2][band], 0 }); } device.Write(new byte[] { 0x16, 0xFF }); }
private async void InitializeSystem() { byte[] i2CWriteBuffer; byte[] i2CReadBuffer; byte bitMask; // initialize I2C communications string deviceSelector = I2cDevice.GetDeviceSelector(); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); if (i2cDeviceControllers.Count == 0) { ButtonStatusText.Text = "No I2C controllers were found on this system."; return; } var i2cSettings = new I2cConnectionSettings(PORT_EXPANDER_I2C_ADDRESS); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); if (i2cPortExpander == null) { ButtonStatusText.Text = string.Format( "Slave address {0} is currently in use on {1}. " + "Please ensure that no other applications are using I2C.", i2cSettings.SlaveAddress, i2cDeviceControllers[0].Id); return; } // initialize I2C Port Expander registers try { // initialize local copies of the IODIR, GPIO, and OLAT registers i2CReadBuffer = new byte[1]; // read in each register value on register at a time (could do this all at once but // for example clarity purposes we do it this way) i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_IODIR_REGISTER_ADDRESS }, i2CReadBuffer); iodirRegister = i2CReadBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_GPIO_REGISTER_ADDRESS }, i2CReadBuffer); gpioRegister = i2CReadBuffer[0]; i2cPortExpander.WriteRead(new byte[] { PORT_EXPANDER_OLAT_REGISTER_ADDRESS }, i2CReadBuffer); olatRegister = i2CReadBuffer[0]; // configure the LED pin output to be logic high, leave the other pins as they are. olatRegister |= LED_GPIO_PIN; i2CWriteBuffer = new byte[] { PORT_EXPANDER_OLAT_REGISTER_ADDRESS, olatRegister }; i2cPortExpander.Write(i2CWriteBuffer); // configure only the LED pin to be an output and leave the other pins as they are. // input is logic low, output is logic high bitMask = (byte)(0xFF ^ LED_GPIO_PIN); // set the LED GPIO pin mask bit to '0', all other bits to '1' iodirRegister &= bitMask; i2CWriteBuffer = new byte[] { PORT_EXPANDER_IODIR_REGISTER_ADDRESS, iodirRegister }; i2cPortExpander.Write(i2CWriteBuffer); } catch (Exception e) { ButtonStatusText.Text = "Failed to initialize I2C port expander: " + e.Message; return; } // setup our timers, one for the LED blink interval, the other for checking button status ledTimer = new DispatcherTimer(); ledTimer.Interval = TimeSpan.FromMilliseconds(TIMER_INTERVAL); ledTimer.Tick += LedTimer_Tick; ledTimer.Start(); buttonStatusCheckTimer = new DispatcherTimer(); buttonStatusCheckTimer.Interval = TimeSpan.FromMilliseconds(BUTTON_STATUS_CHECK_TIMER_INTERVAL); buttonStatusCheckTimer.Tick += ButtonStatusCheckTimer_Tick; buttonStatusCheckTimer.Start(); }
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); }
private async Task Pulsate(I2cDevice device, byte brightness = 1, int numberOfPulses = 3, int speedOfPulses = 100) { for (int iteration = 0; iteration < numberOfPulses; iteration++) { for (int band = INNER_BAND; band <= OUTER_BAND; band++) { device.Write(new byte[] { _arms[0][band], brightness }); device.Write(new byte[] { _arms[1][band], brightness }); device.Write(new byte[] { _arms[2][band], brightness }); CommitLeds(device); await Task.Delay(TimeSpan.FromMilliseconds(speedOfPulses)); } for (int band = OUTER_BAND; band >= INNER_BAND; band--) { device.Write(new byte[] { _arms[0][band], 0 }); device.Write(new byte[] { _arms[1][band], 0 }); device.Write(new byte[] { _arms[2][band], 0 }); CommitLeds(device); await Task.Delay(TimeSpan.FromMilliseconds(speedOfPulses)); } } }
/// <summary> /// Writes a byte to the I2C device. /// </summary> /// <param name="value">The byte to be written to the I2C device.</param> public override void WriteByte(byte value) { _winI2cDevice.Write(new[] { value }); }
private async Task InitI2C() { try { var i2CSettings = new I2cConnectionSettings(0x48) { BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Shared }; var i2C1 = I2cDevice.GetDeviceSelector("I2C1"); _devices = await DeviceInformation.FindAllAsync(i2C1); _adc = await I2cDevice.FromIdAsync(_devices[0].Id, i2CSettings); } catch (Exception ex) { throw new Exception("I2C Initialization Failed", ex); } _adc.Write(new byte[] { 0x01, 0xc2, 0x20 }); _adc.Write(new byte[] { 0x02, 0x00, 0x00 }); _adc.Write(new byte[] { 0x03, 0xff, 0xff }); }
private async void initLedMatrixDevice() { try { // I2C bus settings // Address of device is 0x70 I2cConnectionSettings settings = new I2cConnectionSettings(0x70); // Using standard speed 100 kHZ settings.BusSpeed = I2cBusSpeed.StandardMode; // Get device on bus named I2C1 string aqs = I2cDevice.GetDeviceSelector("I2C1"); var dis = await DeviceInformation.FindAllAsync(aqs); _matrixDevice = await I2cDevice.FromIdAsync(dis[0].Id, settings); // diplay initialization _matrixDevice.Write(new byte[] { 0x21 }); _matrixDevice.Write(new byte[] { 0x81 }); // switch all LEDs off for (int i = 0; i < (MATRIX_SIZE * 2); i = i + 2) { _matrixDevice.Write(new byte[] { (byte)i, 0x00 }); } } catch { _matrixDevice = null; } }
// send movement command to all servos on the specified board // movement is controlled by the duration the duty cycle is high - i.e. off minus on private static void setAllPWM(I2cDevice board, int on, int off) { board.Write(new byte[] { PCA9685_REG_ALL_ON_L, (byte)((byte)on & 0xFF) }); board.Write(new byte[] { PCA9685_REG_ALL_ON_H, (byte)((byte)on >> 8) }); board.Write(new byte[] { PCA9685_REG_ALL_OFF_L, (byte)((byte)off & 0xFF) }); board.Write(new byte[] { PCA9685_REG_ALL_OFF_H, (byte)((byte)off >> 8) }); }