private async void InitI2CBerryIMU() { 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) { DisplayText_Status.Text = "No I2C controllers were found on the system"; return; } // Specify I2C slave addresses for the Gyro and Accelerometer on BerryIMU. // Note; the magenetormeter(compass) uses the same address as the accelerometer. // We will use the ACC I2C settings to access both the accelerometer and the magnetometer. var settingsGYR = new I2cConnectionSettings(berrryIMU.GYR_ADDRESS); var settingsACC = new I2cConnectionSettings(berrryIMU.ACC_ADDRESS); // Enable 400kHz I2C buss settingsGYR.BusSpeed = I2cBusSpeed.FastMode; settingsACC.BusSpeed = I2cBusSpeed.FastMode; // Create an I2cDevices with our selected bus controller and I2C settings I2CGYR = await I2cDevice.FromIdAsync(dis[0].Id, settingsGYR); I2CACC = await I2cDevice.FromIdAsync(dis[0].Id, settingsACC); // Enable the gyrscope writeByteGYR(berrryIMU.CTRL_REG1_G, 0x0F); // Normal power mode, all axes enabled) writeByteGYR(berrryIMU.CTRL_REG4_G, 0x30); // Continuos update, 2000 dps full scale //Enable the accelerometer writeByteACC(berrryIMU.CTRL_REG1_XM, 0x67); // z,y,x axis enabled, continuous update, 100Hz data rate writeByteACC(berrryIMU.CTRL_REG2_XM, 0x20); // +/- 16G full scale // Enable the magnetometer writeByteMAG(berrryIMU.CTRL_REG5_XM, 0xF0); // Temp enable, M data rate = 50Hz writeByteMAG(berrryIMU.CTRL_REG6_XM, 0x60); // +/-12gauss writeByteMAG(berrryIMU.CTRL_REG7_XM, 0x0); // Continuous - conversion mode // Now that everything is initialized, create a timer so we read data every DT periodicTimer = new Timer(this.TimerCallback, null, 0, DT); }
public ArduinoI2cDevice(ArduinoBoard board, ArduinoI2cBus bus, I2cConnectionSettings connectionSettings) { _board = board ?? throw new ArgumentNullException(nameof(board)); _bus = bus ?? throw new ArgumentNullException(nameof(bus)); if (connectionSettings == null) { throw new ArgumentNullException(nameof(connectionSettings)); } if (connectionSettings.BusId != 0) { throw new NotSupportedException("Only I2C Bus 0 is supported"); } if (connectionSettings.DeviceAddress > 127) { throw new NotSupportedException("The device address must be less than 128."); } ConnectionSettings = connectionSettings; // Ensure the corresponding pins are set to I2C (not strictly necessary, but consistent) foreach (SupportedPinConfiguration supportedPinConfiguration in _board.SupportedPinConfigurations.Where(x => x.PinModes.Contains(SupportedMode.I2c))) { _board.Firmata.SetPinMode(supportedPinConfiguration.Pin, SupportedMode.I2c); } _board.Firmata.SendI2cConfigCommand(); // Sometimes, the very first I2C command fails (nothing happens), so try reading a byte int retries = 3; while (retries-- > 0) { try { ReadByte(); break; } catch (Exception x) when(x is TimeoutException || x is IOException) { } } // If the above still failed, there's probably no device on the other end. But this shall not throw here but only if // the client calls ReadByte. }
private async void InitI2CAccel() { /* Initialize the I2C bus */ try { var settings = new I2cConnectionSettings(ACCEL_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 */ I2CAccel = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */ } /* If initialization fails, display the exception and stop running */ catch (Exception e) { Text_Status.Text = "Exception: " + e.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) { Text_Status.Text = "Status: Accelerometer initialization failed"; return; } /* Now that everything is initialized, create a timer so we read data every 100mS */ periodicTimer = new DispatcherTimer(); periodicTimer.Interval = TimeSpan.FromMilliseconds(100); periodicTimer.Tick += Timer_Tick; periodicTimer.Start(); }
private async void InitI2CHumtemp() { 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(HUMTEMP_I2C_ADDR); settings.BusSpeed = I2cBusSpeed.FastMode; I2CHumtemp = await I2cDevice.FromIdAsync(dis[0].Id, settings); // Create an I2C Device with our selected bus controller and I2C settings if (I2CHumtemp == 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 Humidity and Temperature Sensor * For this device, we create 1-byte write buffer * The byte is the content that we want to write to */ byte[] WriteBuf_ComByte = new byte[] { 0x80 }; // 0x80 Ends Command Mode and transits to Normal Operation Mode // Write the register settings try { I2CHumtemp.Write(WriteBuf_ComByte); } // If the write fails display the error and stop running catch (Exception ex) { Text_Status.Text = "Failed to communicate with device: " + ex.Message; return; } // Create a timer to read data every 100ms periodicTimer = new Timer(this.TimerCallback, null, 0, 100); }
/// <summary> /// Open a connection with the IO Pi /// </summary> /// <returns></returns> public async Task Connect() { /* Initialize the I2C bus */ try { string aqs = I2cDevice.GetDeviceSelector(helper.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 */ var settings = new I2cConnectionSettings(Address); settings.BusSpeed = I2cBusSpeed.FastMode; i2cbus = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */ if (i2cbus != null) { // i2c bus is connected so set up the initial configuration for the IO Pi helper.WriteI2CByte(i2cbus, IOCON, config); portaval = helper.ReadI2CByte(i2cbus, GPIOA); portbval = helper.ReadI2CByte(i2cbus, GPIOB); helper.WriteI2CByte(i2cbus, IODIRA, 0xFF); helper.WriteI2CByte(i2cbus, IODIRB, 0xFF); SetPortPullups(0, 0x00); SetPortPullups(1, 0x00); InvertPort(0, 0x00); InvertPort(1, 0x00); // Set IsConnected to true and fire the Connected event handler IsConnected = true; EventHandler handler = Connected; if (handler != null) { handler(this, EventArgs.Empty); } } else { IsConnected = false; } return; } /* If initialization fails, display the exception and stop running */ catch (Exception e) { IsConnected = false; throw e; } }
public override bool Configure(string jsonDeviceConfiguration) { var config = DeserializeDeviceConfig <Bme680Configuration>(jsonDeviceConfiguration); var i2CSettings = new I2cConnectionSettings(1, config.I2CAddress); var i2CDevice = I2cDevice.Create(i2CSettings); // TODO: probably requires try catch?! Check device availability _bme680 = new Bme680(i2CDevice); SetDefaultConfiguration(); SetPropertiesFromConfig(config); SetHeaterProfilesFromConfig(config); _measurementDuration = _bme680.GetMeasurementDuration(_bme680.HeaterProfile); return(true); }
public async Task InitializeAsync() { var settings = new I2cConnectionSettings(SLAVEADDRESS); settings.BusSpeed = I2cBusSpeed.FastMode; var controller = await I2cController.GetDefaultAsync(); this.sensor = controller.GetDevice(settings); this.ConnectionState = ConnectionStates.Connecting; this.OnStateChanged(); this.arduinoDataReadTimer.Tick += this.I2CReadTimer_Tick; // We will create an event handler this.arduinoDataReadTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // Timer_Tick is executed every 500 milli second this.arduinoDataReadTimer.Start(); }
/// <summary> /// Creates an I2c device with the given connection settings. /// </summary> /// <param name="connectionSettings">I2c connection settings. Only Bus 0 is supported.</param> /// <returns>An <see cref="I2cDevice"/> instance</returns> /// <exception cref="NotSupportedException">The firmware reports that no pins are available for I2C. Check whether the I2C module is enabled in Firmata. /// Or: An invalid Bus Id or device Id was specified</exception> public virtual I2cDevice CreateI2cDevice(I2cConnectionSettings connectionSettings) { Initialize(); if (connectionSettings == null) { throw new ArgumentNullException(nameof(connectionSettings)); } if (!SupportedPinConfigurations.Any(x => x.PinModes.Contains(SupportedMode.I2c))) { throw new NotSupportedException("No Pins with I2c support found. Is the I2c module loaded?"); } return(new ArduinoI2cDevice(this, connectionSettings)); }
public static async Task <Si7021> Open() { var result = new Si7021(); var i2cSettings = new I2cConnectionSettings(I2C_ADDRESS); var controller = await AsAsync(I2cController.GetDefaultAsync()); if (null == controller) { throw new ApplicationException("No I2C controller found on this machine."); } result.Device = controller.GetDevice(i2cSettings); result.Initialize(); return(result); }
public Accelerometer() { device = I2cDevice.FromId("I2C1", new I2cConnectionSettings(28) { BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Exclusive }); I2cConnectionSettings i2cConnectionSetting = new I2cConnectionSettings(28) { SharingMode = I2cSharingMode.Shared, BusSpeed = I2cBusSpeed.FastMode }; this.WriteRegister(42, 1); }
private async void InitializeTempPort() { string deviceQuery = I2cDevice.GetDeviceSelector("I2C1"); DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(deviceQuery); string deviceId = deviceCollection[0].Id; I2cConnectionSettings settings = new I2cConnectionSettings(0x4d); settings.BusSpeed = I2cBusSpeed.StandardMode; settings.SharingMode = I2cSharingMode.Shared; temperaturePort = await I2cDevice.FromIdAsync(deviceId, settings); getTemperature(); }
/// <summary> /// Initialize the device /// </summary> /// <returns></returns> private async Task InitializeI2CAsync() { var settings = new I2cConnectionSettings(SparkFun_APDS9960.APDS9960_I2C_ADDR); settings.BusSpeed = I2cBusSpeed.FastMode; settings.SharingMode = I2cSharingMode.Shared; var devices = await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector("I2C1")); if (devices.Count == 0) { throw new Exception("SparkFun APDS-9960 device not found"); } _i2CDevice = await I2cDevice.FromIdAsync(devices[0].Id, settings); }
/// <summary>Executes the command.</summary> /// <returns>The command's exit code.</returns> /// <remarks> /// NOTE: This test app uses the base class's <see cref="CreateI2cDevice"/> method to create a device.<br/> /// Real-world usage would simply create an instance of an <see cref="I2cDevice"/> implementation: /// <code>using (var i2c = new UnixI2cDevice(connectionSettings))</code> /// </remarks> public int Execute() { Console.WriteLine($"ByteCount={ByteCount}, BusId={BusId}, DeviceAddress={DeviceAddress}, Device={Device}"); var connectionSettings = new I2cConnectionSettings(BusId, DeviceAddress); using (var i2c = CreateI2cDevice(connectionSettings)) { // Read bytes of data var buffer = new byte[ByteCount]; i2c.Read(buffer.AsSpan()); Console.WriteLine($"Bytes read:{Environment.NewLine}{BitConverter.ToString(buffer)}"); } return(0); }
async void Init(int address, Action onComplete) { var advancedQuerySyntaxString = I2cDevice.GetDeviceSelector(); var controllerDeviceIds = await DeviceInformation.FindAllAsync(advancedQuerySyntaxString); I2cConnectionSettings connectionSettings = new I2cConnectionSettings(address); connectionSettings.BusSpeed = I2cBusSpeed.StandardMode; if (controllerDeviceIds.Count==0) return; _device = await I2cDevice.FromIdAsync(controllerDeviceIds[0].Id, connectionSettings); _initComplete = true; if (onComplete != null) { onComplete(); } }
private void EnsureInitialized() { try { var i2cSettings = new I2cConnectionSettings(1, I2C_ADDRESS); I2C = I2cDevice.Create(i2cSettings); PowerUp(); SetTiming(); IsInitialised = true; } catch (Exception ex) { throw new Exception("I2C Initialization Failed", ex); } }
static void GetTempDHTxx() { I2cConnectionSettings settings = new I2cConnectionSettings(1, Dht10.DefaultI2cAddress); I2cDevice device = I2cDevice.Create(settings); using (Dht10 dht = new Dht10(device)) { while (true) { Console.WriteLine( $"Temperature: {dht.Temperature.Celsius.ToString("0.0")} °C, Humidity: {dht.Humidity.ToString("0.0")} %"); Thread.Sleep(2000); } } }
public override bool Configure(string jsonDeviceConfiguration) { var config = DeserializeDeviceConfig <Si7021Configuration>(jsonDeviceConfiguration); var i2CSettings = new I2cConnectionSettings(1, config.I2CAddress); var i2CDevice = I2cDevice.Create(i2CSettings); // TODO: probably requires try catch?! Check device availability _si7021 = new Si7021(i2CDevice) { Heater = config.HeaterIsEnabled, Resolution = config.Resolution }; return(true); }
public async Task InitRGBSensor() { var selector = I2cDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); var settings = new I2cConnectionSettings(__TCS34725_ADDRESS); sensor = await I2cDevice.FromIdAsync(devices[0].Id, settings); // Make sure we are talking to a TCS34725 byte[] write_buffer = new byte[] { __TCS34725_ID | __TCS34725_COMMAND_BIT }; byte[] read_buffer = new byte[1]; sensor.WriteRead(write_buffer, read_buffer); if (read_buffer[0] != 0x44) { throw new Exception("not connected to TCS34725"); } // Send a few commands byte[] command_buffer = new byte[2]; // Turn on command_buffer[0] = __TCS34725_ENABLE | __TCS34725_COMMAND_BIT; command_buffer[1] = __TCS34725_ENABLE_PON; sensor.Write(command_buffer); command_buffer[0] = __TCS34725_ENABLE | __TCS34725_COMMAND_BIT; command_buffer[1] = __TCS34725_ENABLE_PON | __TCS34725_ENABLE_AEN; sensor.Write(command_buffer); // Integration Time command_buffer[0] = __TCS34725_ATIME | __TCS34725_COMMAND_BIT; command_buffer[1] = 0x00; sensor.Write(command_buffer); // Gain command_buffer[0] = __TCS34725_CONTROL | __TCS34725_COMMAND_BIT; command_buffer[1] = 0x01; sensor.Write(command_buffer); }
public async void Run(IBackgroundTaskInstance taskInstance) { m_Deferral = taskInstance.GetDeferral(); taskInstance.Canceled += TaskInstanceCanceled; // initialize I2C var i2cSettings = new I2cConnectionSettings(TSL2561.Address) { BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Shared, }; var selector = I2cDevice.GetDeviceSelector(m_DeviceSelector); var deviceInformation = await DeviceInformation.FindAllAsync(selector); m_Device = await I2cDevice.FromIdAsync(deviceInformation[0].Id, i2cSettings); // initialize sensor m_Sensor = new TSL2561(m_Device); m_Sensor.SetTiming(m_Gain, m_Timing); m_Sensor.PowerUp(); // initialize MQTT try { m_Client = new MqttClient(m_Host); m_Client.Connect(m_ClientId); } catch (MqttConnectionException ex) { // ignore connection exception and retry to connect later Debug.WriteLine("Cannot connect to MQTT broker: " + ex.Message); m_Client = null; } var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (appService != null && appService.Name == m_ServiceName) { m_AppServiceConnection = appService.AppServiceConnection; m_AppServiceConnection.RequestReceived += OnRequestReceived; } m_Client.Publish(m_ServiceTopic, Encoding.UTF8.GetBytes(DateTime.Now.ToUniversalTime().ToString("O")), m_QoS, true); // start timer m_Timer = new Timer(LuxProvider, null, m_TimerDueTime, m_TimerInterval); }
/// <summary> /// Create a FT4222 I2C Device /// </summary> /// <param name="settings">I2C Connection Settings</param> /// <param name="frequencyKbps">The speed of I2C transmission.</param> public Ft4222I2cEx(I2cConnectionSettings settings, uint frequencyKbps = I2cMasterFrequencyKbps) { _settings = settings ?? throw new ArgumentNullException(nameof(settings)); FrequencyKbps = frequencyKbps; // Check device var devInfos = FtCommon.GetDevices(); if (devInfos.Count == 0) { throw new IOException("No FTDI device available"); } // Select the one from bus Id // FT4222 propose depending on the mode multiple interfaces. Only the A is available for I2C or where there is none as it's the only interface var devInfo = devInfos.Where(m => m.Description == "FT4222 A" || m.Description == "FT4222").ToArray(); if ((devInfo.Length == 0) || (devInfo.Length < _settings.BusId)) { throw new IOException($"Can't find a device to open I2C on index {_settings.BusId}"); } DeviceInformation = devInfo[_settings.BusId]; // Open device var ftStatus = FtFunction.FT_OpenEx(DeviceInformation.LocId, FtOpenType.OpenByLocation, out _ftHandle); if (ftStatus != FtStatus.Ok) { throw new IOException($"Failed to open device {DeviceInformation.Description}, status: {ftStatus}"); } // Set the clock FtClockRate ft4222Clock = FtClockRate.Clock24MHz; ftStatus = FtFunction.FT4222_SetClock(_ftHandle, ft4222Clock); if (ftStatus != FtStatus.Ok) { throw new IOException($"Failed set clock rate {ft4222Clock} on device: {DeviceInformation.Description}, status: {ftStatus}"); } // Set the device as I2C Master ftStatus = FtFunction.FT4222_I2CMaster_Init(_ftHandle, frequencyKbps); if (ftStatus != FtStatus.Ok) { throw new IOException($"Failed to initialize I2C Master mode on device: {DeviceInformation.Description}, status: {ftStatus}"); } }
private static Mcp23xxx GetMcp23xxxDevice(Mcp23xxxDevice mcp23xxxDevice) { var i2cConnectionSettings = new I2cConnectionSettings(1, s_deviceAddress); var i2cDevice = I2cDevice.Create(i2cConnectionSettings); // I2C. switch (mcp23xxxDevice) { case Mcp23xxxDevice.Mcp23008: return(new Mcp23008(i2cDevice)); case Mcp23xxxDevice.Mcp23009: return(new Mcp23009(i2cDevice)); case Mcp23xxxDevice.Mcp23017: return(new Mcp23017(i2cDevice)); case Mcp23xxxDevice.Mcp23018: return(new Mcp23018(i2cDevice)); } var spiConnectionSettings = new SpiConnectionSettings(0, 0) { ClockFrequency = 1000000, Mode = SpiMode.Mode0 }; var spiDevice = SpiDevice.Create(spiConnectionSettings); // SPI. switch (mcp23xxxDevice) { case Mcp23xxxDevice.Mcp23S08: return(new Mcp23s08(spiDevice, s_deviceAddress)); case Mcp23xxxDevice.Mcp23S09: return(new Mcp23s09(spiDevice)); case Mcp23xxxDevice.Mcp23S17: return(new Mcp23s17(spiDevice, s_deviceAddress)); case Mcp23xxxDevice.Mcp23S18: return(new Mcp23s18(spiDevice)); } throw new Exception($"Invalid Mcp23xxxDevice: {nameof(mcp23xxxDevice)}"); }
public static void Main(string[] args) { var settings = new I2cConnectionSettings(0x00, 0x27); using var device = new UnixI2cDevice(settings); using var lcd = new Hd44780(new Size(20, 4), new I2C4Bit(device)); var name0 = File.ReadAllText("/sys/class/thermal/thermal_zone0/type").Substring(0, 3); var name1 = File.ReadAllText("/sys/class/thermal/thermal_zone1/type").Substring(0, 3); lcd.BacklightOn = true; ShowSpecialSymbols(lcd); for (var i = 0; i < 16 * 16; i++) { var temp0 = File.ReadAllText("/sys/class/thermal/thermal_zone0/temp"); var x0 = float.Parse(temp0); var y0 = x0 * 9.0f / 5000.0f + 32.0f; var msg0 = $"{name0}: {y0:F2}\xDF"; lcd.SetCursorPosition(0, 0); lcd.Write(msg0); var temp1 = File.ReadAllText("/sys/class/thermal/thermal_zone1/temp"); var x1 = float.Parse(temp1); var y1 = x1 * 9.0f / 5000.0f + 32.0f; var msg1 = $"{name1}: {y1:F2}\xDF"; lcd.SetCursorPosition(0, 1); lcd.Write(msg1); // Thread.Sleep(500); ShowSpecialSymbols(lcd); var build = new StringBuilder(); lcd.SetCursorPosition(0, 3); for (var j = 0; j < 20; j++) { build.Append($"{(char)(16 * (i / 16) + j)}"); } lcd.SetCursorPosition(0, 3); lcd.Write(build.ToString()); } lcd.BacklightOn = false; lcd.Clear(); }
//public TemperatureSensors() //{ // //InitSensors(); //} //Initilizes the I2C connection and starts the timer to read I2C Data public static async void InitSensors() { if (Device == null) { //Set up the I2C connection the Arduino var settings = new I2cConnectionSettings(0x40); // Arduino address settings.BusSpeed = I2cBusSpeed.StandardMode; string aqs = I2cDevice.GetDeviceSelector("I2C1"); var dis = await DeviceInformation.FindAllAsync(aqs); Device = await I2cDevice.FromIdAsync(dis[0].Id, settings); //Create a timer to periodicly read the temps from the Arduino periodicTimer = new Timer(TimerCallback, null, 0, ReadInterval); } return; }
public static void Main(string[] args) { I2cConnectionSettings settings = new I2cConnectionSettings(1, Mcp9808.DefaultI2cAddress); I2cDevice device = I2cDevice.Create(settings); using (Mcp9808 sensor = new Mcp9808(device)) { while (true) { // read temperature Console.WriteLine($"Temperature: {sensor.Temperature.DegreesCelsius} ℃"); Console.WriteLine(); Thread.Sleep(1000); } } }
static void Main(string[] args) { I2cConnectionSettings settings = new I2cConnectionSettings(1, (byte)I2cAddress.AddrLow); I2cDevice device = I2cDevice.Create(settings); using (Sht3x sensor = new Sht3x(device)) { while (true) { Console.WriteLine($"Temperature: {sensor.Temperature.Celsius} ℃"); Console.WriteLine($"Humidity: {sensor.Humidity} %"); Console.WriteLine(); Thread.Sleep(1000); } } }
public static void Main(string[] args) { I2cConnectionSettings settings = new I2cConnectionSettings(1, Mlx90614.DefaultI2cAddress); I2cDevice i2cDevice = I2cDevice.Create(settings); using (Mlx90614 sensor = new Mlx90614(i2cDevice)) { while (true) { Console.WriteLine($"Ambient: {sensor.ReadAmbientTemperature().Celsius} ℃"); Console.WriteLine($"Object: {sensor.ReadObjectTemperature().Celsius} ℃"); Console.WriteLine(); Thread.Sleep(1000); } } }
/** * Start I2C Communication **/ public async void startI2C(byte deviceAddress, string controllerName) { try { var i2cSettings = new I2cConnectionSettings(deviceAddress); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; string deviceSelector = I2cDevice.GetDeviceSelector(controllerName); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); this._i2cPortExpander = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message); return; } }
static void Main(string[] args) { I2cConnectionSettings settings = new I2cConnectionSettings(1, Si7021.DefaultI2cAddress); I2cDevice device = I2cDevice.Create(settings); using (Si7021 sensor = new Si7021(device, Resolution.Resolution1)) { while (true) { Console.WriteLine($"Temperature: {sensor.Temperature.Celsius}℃"); Console.WriteLine($"Humidity: {sensor.Humidity}%"); Console.WriteLine(); Thread.Sleep(1000); } } }
private const string I2C_CONTROLLER_NAME = "I2C1"; // For Raspberry Pi 2, use I2C1 public async Task <I2cDevice> GetI2cDeviceAsync(byte address) { string aqs = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME); /* Get a selector string that will return all I2C controllers on the system */ var _i2cBusControllers = await DeviceInformation.FindAllAsync(aqs); /* Find the I2C bus controller device with our selector string */ if (!_i2cBusControllers.Any()) { throw new InvalidOperationException("No I2C bus controllers were found on the system"); } var settings = new I2cConnectionSettings(address) { BusSpeed = I2cBusSpeed.FastMode }; return(await I2cDevice.FromIdAsync(_i2cBusControllers.First().Id, settings)); /* Create an I2cDevice with our selected bus controller and I2C settings */ }
//Method to initialize the BME280 sensor public async Task Initialize() { Debug.WriteLine("BME280::Initialize Attempt"); try { //Instantiate the I2CConnectionSettings using the device address of the BME280 I2cConnectionSettings settings = new I2cConnectionSettings(BME280_Address); //Set the I2C bus speed of connection to fast mode settings.BusSpeed = I2cBusSpeed.FastMode; //Use the I2CBus device selector to create an advanced query syntax string string aqs = I2cDevice.GetDeviceSelector(I2CControllerName); //Use the Windows.Devices.Enumeration.DeviceInformation class to create a collection using the advanced query syntax string DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs); //Instantiate the the BME280 I2C device using the device id of the I2CBus and the I2CConnectionSettings bme280 = await I2cDevice.FromIdAsync(dis[0].Id, settings); //Check if device was found if (bme280 == null) { Debug.WriteLine("BME280::Device not found"); } else { try { //Make sure the I2C device is initialized if (!init) { await Begin(); } } catch (Exception e) { init = false; Debug.WriteLine("BME280::Initialization Exception: " + e.Message + "\n" + e.StackTrace); } } } catch (Exception e) { Debug.WriteLine("BME280::Exception: " + e.Message + "\n" + e.StackTrace); throw; } }