private Task InitializeAsync() { if (_initializeTask == null || !_initializeTask.IsCompletedSuccessfully) { _initializeTask = Task.Run(async() => { try { var devices = await DeviceInformation.FindAllAsync(I2cDevice.GetDeviceSelector()); var settings = new I2cConnectionSettings(118) { BusSpeed = I2cBusSpeed.FastMode }; _device = await I2cDevice.FromIdAsync(devices[0].Id, settings); _bme280 = await Bme280.CreateAsync(_device).ConfigureAwait(false); } catch { _device = null; _bme280 = null; _initializeTask = null; throw; } }); } return(_initializeTask); }
private void InitializeBme280() { Console.WriteLine("Temperature (BME280) Initializing..."); // configure our BME280 on the I2C Bus Meadow.Hardware.II2cBus i2c = Device.CreateI2cBus(); this.bme280 = new Bme280( i2c, Bme280.I2cAddress.Adddress0x77 //default ); this.bme280.Subscribe(new FilterableChangeObserver <AtmosphericConditionChangeResult, AtmosphericConditions>( h => this.OutputConditions(h.New), e => (Math.Abs(e.Delta.Temperature.Value) > 0.2) || (Math.Abs(e.Delta.Pressure.Value) > 5 || (Math.Abs(e.Delta.Humidity.Value) > 0.1f)) )); // classical .NET events can also be used: //this.bme280.Updated += this.AtmosphericConditionsChangedHandler; // get chip id Console.WriteLine($"ChipID: {this.bme280.GetChipID():X2}"); // get an initial reading this.ReadConditions().Wait(); // start updating continuously this.bme280.StartUpdating( temperatureSampleCount: Bme280.Oversample.OversampleX2, pressureSampleCount: Bme280.Oversample.OversampleX16, humiditySampleCount: Bme280.Oversample.OversampleX1); Console.WriteLine("Temperature (BME280) Initialized"); }
public void I2C_Bme280CanRead() { using (Bme280 bme280 = CreateBme280()) { TestBme280Reading(bme280); } }
private static async Task <Weather> GetWeatherAsync() { I2cConnectionSettings settings = new I2cConnectionSettings(0, Bme280.SecondaryI2cAddress); I2cDevice device = I2cDevice.Create(settings); using Bme280 bme = new Bme280(device); bme.SetPowerMode(Bmx280PowerMode.Normal); bme.SetTemperatureSampling(Sampling.UltraHighResolution); bme.SetPressureSampling(Sampling.UltraHighResolution); bme.SetHumiditySampling(Sampling.UltraHighResolution); double t = Math.Round((await bme.ReadTemperatureAsync()).Celsius, 2); double h = Math.Round(await bme.ReadHumidityAsync(), 2); double p = Math.Round(await bme.ReadPressureAsync(), 2); bme.SetPowerMode(Bmx280PowerMode.Sleep); //Console.WriteLine($"Temperature:{t} Humidity:{h} Pressure:{p}"); return(new Weather { DateTime = DateTime.Now, WeatherName = await WeatherHelper.GetXinzhiWeatherAsync(ConfigHelper.Get("Xinzhi:Key"), ConfigHelper.Get("Xinzhi:Location")), Temperature = t, Humidity = h, Pressure = p, ImageBase64 = GetImageBase64() }); }
public static Bme280 CreateBme280(I2cBus i2cBus) { var bme280 = new Bme280(i2cBus.CreateDevice(Bme280.DefaultI2cAddress)); SetupBme280(bme280); return(bme280); }
static async Task App() { var board = await ConnectionService.Instance.GetFirstDeviceAsync(); await board.ConnectAsync(); var sensor = new Bme280(board.I2c); //var sensor = new Bmp280(board.I2c); sensor.AutoUpdateWhenPropertyRead = false; Console.WriteLine("Press any key to disconnect"); while (!Console.KeyAvailable) { await sensor.UpdateAsync(); Console.WriteLine($"Pressure: {sensor.Atm:0.00} Atm"); Console.WriteLine($"Altitude: {sensor.Altitude:0.00} m"); Console.WriteLine($"Temperature: {sensor.Celsius:0.00} Celsius"); // comment this line out if you're not using a sensor with humidity measurement Console.WriteLine($"Humidity: {sensor.RelativeHumidity:0.00} % RH"); Console.WriteLine(); await Task.Delay(1000); } Console.WriteLine("Board disconnected"); }
/// <summary> /// Main constructor. Takes in the DeviceClient connection with Azure IoT Hub. /// </summary> /// <param name="deviceClient">Azure IoT Hub DeviceClient connection.</param> public BuildSample(DeviceClient deviceClient) { // Setting the Azure method handlers for C2D communication _deviceClient = deviceClient; _deviceClient.SetMethodHandlerAsync("ChangeLightBulbState", ChangeLightBulbState, null).Wait(); _deviceClient.SetMethodHandlerAsync("GetLightBulbStatus", GetLightBulbStatus, null).Wait(); _deviceClient.SetMethodHandlerAsync("GetTemperatureAndPreassure", GetTemperatureAndPreassure, null).Wait(); // Setting up the temperature sensor var i2cDevice = new UnixI2cDevice(new I2cConnectionSettings(1, 0x77)); _temperatureSensor = new Bme280(i2cDevice); // Setting up Gpio Pins _gpioController = new GpioController(); _gpioController.OpenPin(26, PinMode.Output); _gpioController.OpenPin(20, PinMode.Output); _gpioController.OpenPin(21, PinMode.Output); _gpioController.Write(26, true); _gpioController.Write(20, true); _gpioController.Write(21, true); // Setting up Dictionary of light bulb state _lightsStatus = new Dictionary <int, bool>(); _lightsStatus.Add(1, false); _lightsStatus.Add(2, false); _lightsStatus.Add(3, false); }
private static void Main(string[] args) { // Initialize the GPIO controller s_gpio = new GpioController(); s_gpio.OpenPin(s_pin, PinMode.Output); // Get a reference to a device on the I2C bus var i2cSettings = new I2cConnectionSettings(1, Bme280.DefaultI2cAddress); s_i2cDevice = I2cDevice.Create(i2cSettings); // Create a reference to the BME280 s_bme280 = new Bme280(s_i2cDevice); colorMessage("Cheese Cave device app.\n", ConsoleColor.Yellow); // Create the device client and connect to the IoT hub using the MQTT protocol. s_deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, TransportType.Mqtt); // Create a handler for the direct method call s_deviceClient.SetMethodHandlerAsync("SetFanState", SetFanState, null).Wait(); MonitorConditionsAndUpdateTwinAsync(); Console.ReadLine(); s_gpio.ClosePin(s_pin); }
public static Bme280 CreateBme280() { var settings = new I2cConnectionSettings(Bme280I2cBusId, Bme280.DefaultI2cAddress); var bme280 = new Bme280(I2cDevice.Create(settings)); SetupBme280(bme280); return(bme280); }
public void I2C_I2cBus_Bme280CanRead() { using (I2cBus i2cBus = CreateI2cBusForBme280()) using (Bme280 bme280 = CreateBme280(i2cBus)) { TestBme280Reading(bme280); } }
public MeadowApp() { Console.WriteLine("Initializing..."); // create a trigger for the LA trigger = Device.CreateDigitalOutputPort(Device.Pins.D13); Console.WriteLine("Trigger on D02"); trigger.State = true; // configure our BME280 on the I2C Bus var i2c = Device.CreateI2cBus(); bme280 = new Bme280( i2c, Bme280.I2cAddress.Adddress0x76 //default //Bme280.I2cAddress.Adddress0x77 //default ); // TODO: SPI version // Example that uses an IObersvable subscription to only be notified // when the temperature changes by at least a degree, and humidty by 5%. // (blowing hot breath on the sensor should trigger) bme280.Subscribe(new FilterableChangeObserver <AtmosphericConditionChangeResult, AtmosphericConditions>( h => { Console.WriteLine($"Temp and pressure changed by threshold; new temp: {h.New.Temperature}, old: {h.Old.Temperature}"); }, e => { return( (Math.Abs(e.Delta.Temperature.Value) > 1) && (Math.Abs(e.Delta.Pressure.Value) > 5) ); } )); // classical .NET events can also be used: bme280.Updated += (object sender, AtmosphericConditionChangeResult e) => { Console.WriteLine($" Temperature: {e.New.Temperature}°C"); Console.WriteLine($" Pressure: {e.New.Pressure}hPa"); Console.WriteLine($" Relative Humidity: {e.New.Humidity}%"); }; // just for funsies. Console.WriteLine($"ChipID: {bme280.GetChipID():X2}"); //Thread.Sleep(1000); //// is this necessary? if so, it should probably be tucked into the driver //Console.WriteLine("Reset"); //bme280.Reset(); // get an initial reading ReadConditions().Wait(); // start updating continuously bme280.StartUpdating(); }
public HumidityTemperatureAltitudePressureClient( SensorReadingByGpioI2COptions options ) { //Bme280.DefaultI2cAddress var i2cSettings = new I2cConnectionSettings(1, Bme280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); _sensor = new Bme280(i2cDevice); }
public Bme280Controller() { var i2CSettings = new I2cConnectionSettings(1, Bmx280Base.SecondaryI2cAddress); var i2CDevice = I2cDevice.Create(i2CSettings); _bme280 = new Bme280(i2CDevice); SetDefaultConfiguration(); _measurementDuration = _bme280.GetMeasurementDuration(); }
public static Bme280 CreateBme280() { var settings = new I2cConnectionSettings(1, Bme280.DefaultI2cAddress); var bme280 = new Bme280(I2cDevice.Create(settings)); // https://github.com/dotnet/iot/issues/753 bme280.SetPowerMode(Bmx280PowerMode.Forced); return(bme280); }
public static void Main() { //Setup I2C pins for ESP32 board Configuration.SetPinFunction(21, DeviceFunction.I2C1_DATA); Configuration.SetPinFunction(22, DeviceFunction.I2C1_CLOCK); CancellationTokenSource cs = new(sleepTimeMinutes); var success = NetworkHelper.ConnectWifiDhcp(wifiSSID, wifiApPASSWORD, setDateTime: true, token: cs.Token); if (!success) { Debug.WriteLine($"Can't connect to wifi: {NetworkHelper.ConnectionError.Error}"); if (NetworkHelper.ConnectionError.Exception != null) { Debug.WriteLine($"NetworkHelper.ConnectionError.Exception"); } GoToSleep(); } // Reset the time counter if the previous date was not valid if (allupOperation.Year < 2018) { allupOperation = DateTime.UtcNow; } Debug.WriteLine($"Date and time is now {DateTime.UtcNow}"); const int busId = 1; //If SDO pin connected to the 3V,Bmp280.DefaultI2cAddress if SDO pin connected to the GND then Bmp280.SecondaryI2cAddress I2cConnectionSettings i2cSettings = new(busId, Bmp280.SecondaryI2cAddress); I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); bme280Sensor = new Bme280(i2cDevice); if (!SetupThingsBoard()) { Debug.WriteLine("Error connecting to the server"); return; } // launch telemetry thread Thread telemetryThread = new Thread(new ThreadStart(TelemetryLoop)); telemetryThread.Start(); Debug.WriteLine("Connected to the server."); while (true) { Thread.Sleep(10000); } }
static async Task Main(string[] args) { //LED setup var pin = 17; var lightTimeInMilliseconds = 1000; var dimTimeInMilliseconds = 800; //bus id on the raspberry pi 3 const int busId = 1; var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmpe80 = new Bme280(i2cDevice); using (i2CBmpe80) { while (true) { //set mode forced so device sleeps after read i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced); //set samplings i2CBmpe80.SetTemperatureSampling(Sampling.UltraLowPower); i2CBmpe80.SetHumiditySampling(Sampling.UltraLowPower); //read values Temperature tempValue = await i2CBmpe80.ReadTemperatureAsync(); Console.WriteLine($"Temperature: {tempValue.Celsius} C"); double humValue = await i2CBmpe80.ReadHumidityAsync(); Console.WriteLine($"Humidity: {humValue} %"); // Sleeping it so that we have a chance to get more measurements. Thread.Sleep(500); humValue = await i2CBmpe80.ReadHumidityAsync(); if (humValue > 50.00) { using (GpioController controller = new GpioController()) { controller.OpenPin(pin, PinMode.Output); Console.WriteLine($"GPIO pin enabled for use: {pin}"); Console.WriteLine($"Light for {lightTimeInMilliseconds}ms"); controller.Write(pin, PinValue.High); Thread.Sleep(lightTimeInMilliseconds); Console.WriteLine($"Dim for {dimTimeInMilliseconds}ms"); controller.Write(pin, PinValue.Low); Thread.Sleep(dimTimeInMilliseconds); } } } } }
/// <summary> /// Dispose method. /// </summary> public void Dispose() { // Dispose the connection with Azure IoT Hub. _deviceClient?.Dispose(); _deviceClient = null; // Dispose the Raspberry Pi controller. _gpioController?.Dispose(); _gpioController = null; // Dispose temperature sensor. _temperatureSensor?.Dispose(); _temperatureSensor = null; }
public EnvironmentService() { I2cConnectionSettings i2cSettings = new(busId, Bme280.DefaultI2cAddress); i2cDevice = I2cDevice.Create(i2cSettings); bme280 = new Bme280(i2cDevice) { TemperatureSampling = Sampling.LowPower, PressureSampling = Sampling.UltraHighResolution, HumiditySampling = Sampling.Standard }; }
public TelemetryService(IOutboundEventBus outboundEventBus, SparkFunAnemometerDriver anemometerDriver, SparkFunWindVaneDriver windVaneDriver, SparkFunRainGaugeDriver rainGaugeDriver, Bme280 bme280Driver, Bh1750 lightSensorDriver) { _outboundEventBus = outboundEventBus; _anemometerDriver = anemometerDriver; _windVaneDriver = windVaneDriver; _rainGaugeDriver = rainGaugeDriver; _bme280Driver = bme280Driver; _lightSensorDriver = lightSensorDriver; }
void Initialize() { Console.WriteLine("Initialize hardware..."); Console.WriteLine("Onboard LED"); onboardLed = new RgbPwmLed(device: Device, redPwmPin: Device.Pins.OnboardLedRed, greenPwmPin: Device.Pins.OnboardLedGreen, bluePwmPin: Device.Pins.OnboardLedBlue, 3.3f, 3.3f, 3.3f, Meadow.Peripherals.Leds.IRgbLed.CommonType.CommonAnode); // configure our BME280 on the I2C Bus Console.WriteLine("BME280"); var i2c = Device.CreateI2cBus(); bme280 = new Bme280( i2c, Bme280.I2cAddress.Adddress0x76 ); // configure our AnalogTemperature sensor Console.WriteLine("Analog Temp"); anlgTemp = new AnalogTemperature( device: Device, analogPin: Device.Pins.A02, sensorType: AnalogTemperature.KnownSensorType.TMP35 ); //a02 = Device.CreateAnalogInputPort(Device.Pins.A02); Console.WriteLine("Relays"); relays[0] = new Relay(Device, Device.Pins.D04); // Fan relays[1] = new Relay(Device, Device.Pins.D09); // Heat 1 relays[2] = new Relay(Device, Device.Pins.D10); // Heat 2 relays[3] = new Relay(Device, Device.Pins.D06); // Cool 1 relays[4] = new Relay(Device, Device.Pins.D05); // Cool 2 Console.WriteLine("Display"); var config = new SpiClockConfiguration(48000, SpiClockConfiguration.Mode.Mode3); var spiBus = Device.CreateSpiBus(Device.Pins.SCK, Device.Pins.MOSI, Device.Pins.MISO, config); display = new St7789( device: Device, spiBus: spiBus, chipSelectPin: null, dcPin: Device.Pins.D00, resetPin: Device.Pins.D02, width: 240, height: 240); canvas = new GraphicsLibrary(display); }
public override bool Configure(string jsonDeviceConfiguration) { var config = DeserializeDeviceConfig <Bme280Configuration>(jsonDeviceConfiguration); var i2CSettings = new I2cConnectionSettings(1, config.I2CAddress); var i2CDevice = I2cDevice.Create(i2CSettings); // TODO: probably requires try catch?! Check device availability _bme280 = new Bme280(i2CDevice); SetDefaultConfiguration(); SetPropertiesFromConfig(config); _measurementDuration = _bme280.GetMeasurementDuration(); return(true); }
public TemperatureMonitor(II2cBus i2CBus, Logger logger) { _logger = logger; _bme280 = new Bme280(i2CBus, Bme280.I2cAddress.Adddress0x77); _bme280.Subscribe(new FilterableChangeObserver <AtmosphericConditionChangeResult, AtmosphericConditions>( h => ProcessAtmosphericChange(h.New), e => Math.Abs(e.Delta.Temperature.GetValueOrDefault()) > 0.1 )); // get chip id _logger.LogMessage(() => $"BME280 ChipID: {_bme280.GetChipID():X2}"); // get an initial reading ReadConditions().ContinueWith(t => _bme280.StartUpdating()); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { //IHostedService is a singleton. It cannot consume scopped services. //Using the IServiceProvider, and a 'using' create a scope and a GetRequiredServices to create the scoped service using (var scope = Services.CreateScope()) { var _db = scope.ServiceProvider.GetRequiredService <climatepiDBContext>(); var i2cSettings = new I2cConnectionSettings(1, Bme280.SecondaryI2cAddress); using I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); using var bme280 = new Bme280(i2cDevice); int measurementTime = bme280.GetMeasurementDuration(); while (true) { bme280.SetPowerMode(Bmx280PowerMode.Forced); Thread.Sleep(measurementTime); bme280.TryReadTemperature(out var tempValue); bme280.TryReadPressure(out var preValue); bme280.TryReadHumidity(out var humValue); bme280.TryReadAltitude(out var altValue); var condition = new Server.Database.Condition() { LoggedAt = DateTime.UtcNow, DegreesCelsius = tempValue.DegreesCelsius, PressureMillibars = preValue.Millibars, HumidityPercentage = humValue.Percent }; _db.Conditions.Add(condition); await _db.SaveChangesAsync(); //Thread.Sleep(1000); //This works, but it is more often than I need Thread.Sleep(60000); //New reading every 1 minute } } } catch (Exception ex) { } }
public async Task <Bme280.Measurement> GetMeasurementAsync() { try { await InitializeAsync().ConfigureAwait(false); var measurement = await _bme280.GetMeasurementAsync().ConfigureAwait(false); return(measurement); } catch { _device = null; _bme280 = null; _initializeTask = null; throw; } }
private static void TestBme280Reading(Bme280 bme280) { Assert.True(bme280.TryReadTemperature(out Temperature temperature)); // assuming that tests are run in the room temperature // worst case scenario: it's very hot outside Assert.InRange(temperature.DegreesCelsius, 15, 40); Assert.True(bme280.TryReadPressure(out Pressure pressure)); // https://en.wikipedia.org/wiki/List_of_weather_records // Min and max are extremes recorded on land double pressureHPa = pressure.Hectopascals; Assert.InRange(pressureHPa, 892, 1084); Assert.True(bme280.TryReadHumidity(out RelativeHumidity relativeHumidity)); Assert.InRange(relativeHumidity.Percent, 0, 100); }
static void Main(string[] args) { /// DispatcherTimer setup DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer(); DispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); DispatcherTimer.Interval = new TimeSpan(0, 0, 5); DispatcherTimer.Start(); /// Fragment used to create connection between BME sensor and the programm. var i2cSettings = new I2cConnectionSettings(1, Bme280.DefaultI2cAddress); using I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); using var bme280 = new Bme280(i2cDevice); AcquireData Acquire = new AcquireData(); double[] tablica = new double[3]; tablica = Acquire.ReadBME(); double [] tab = new double [2]; double temperature = tablica[0]; double preassure = tablica[1]; double humidity = tablica[2]; double COtwo = Acquire.ReadCOtwo(); /// Alarm constant values. double TempALM_HH = 0; double TempALM_LL = 0; double Pres_ALM_HH = 0; double Pres_ALM_LL = 0; double Hum_ALM_HH = 0; double Hum_ALM_LL = 0; double COtwo_ALM_HH = 0; double COtwo_ALM_LL = 0; SetAlarmValues(TempALM_HH, TempALM_LL, Pres_ALM_HH, Pres_ALM_LL, Hum_ALM_HH, Hum_ALM_LL, COtwo_ALM_HH, COtwo_ALM_LL); ShowData(temperature, preassure, humidity, COtwo); ActivateAlarm(TempALM_HH, TempALM_LL, Pres_ALM_HH, Pres_ALM_LL, Hum_ALM_HH, Hum_ALM_LL, COtwo_ALM_HH, COtwo_ALM_LL, temperature, preassure, humidity, COtwo); }
public async Task <double> GetPressure() { using (var sensor = new Bme280(_bmp280)) { sensor.SetPowerMode(PowerMode.Forced); double pressure = await sensor.ReadPressureAsync(); var temp = await sensor.ReadTemperatureAsync(); var alt = await sensor.ReadAltitudeAsync(pressure); double humid = await sensor.ReadHumidityAsync(); _logger.LogDebug( $"Pressure value: {pressure}; PowerMode: {sensor.ReadPowerMode()}; Temperature: {temp.Celsius}; Altitude: {alt}; Humidity: {humid}"); return(pressure); } }
public void I2C_Bme280CanRead() { using (Bme280 bme280 = CreateBme280()) { Assert.True(bme280.TryReadTemperature(out Temperature temperature)); // assuming that tests are run in the room temperature // worst case scenario: it's very hot outside Assert.InRange(temperature.Celsius, 15, 40); Assert.True(bme280.TryReadPressure(out Pressure pressure)); // https://en.wikipedia.org/wiki/List_of_weather_records // Min and max are extremes recorded on land double pressureHPa = pressure.Hectopascal; Assert.InRange(pressureHPa, 892, 1084); Assert.True(bme280.TryReadHumidity(out double relativeHumidity)); Assert.InRange(relativeHumidity, 0, 100); } }
static async Task Main(string[] args) { // bus id on the raspberry pi 3 const int busId = 1; // Setup i2C device (BME280) var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmpe80 = new Bme280(i2cDevice); using (i2CBmpe80) { while (true) { // set mode forced so device sleeps after read i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced); // Get sampling accuracy i2CBmpe80.SetHumiditySampling(Sampling.Standard); i2CBmpe80.SetTemperatureSampling(Sampling.Standard); i2CBmpe80.SetPressureSampling(Sampling.Standard); // Get variables Iot.Units.Temperature tempValue = await i2CBmpe80.ReadTemperatureAsync(); double humValue = await i2CBmpe80.ReadHumidityAsync(); double preValue = await i2CBmpe80.ReadPressureAsync(); // Print to screen Console.WriteLine($"Weather at time: {DateTime.Now}"); Console.WriteLine($"Temperature: {tempValue.Celsius:0.#}\u00B0C"); Console.WriteLine($"Pressure: {preValue/100:0.##}hPa"); Console.WriteLine($"Relative humidity: {humValue:0.#}%\n"); Thread.Sleep(2000); } } }
private void CreateSensor() { var i2cSettings = new I2cConnectionSettings(busId, Bmx280Base.SecondaryI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); _bme280 = new Bme280(i2cDevice); try { // set higher sampling _bme280.TemperatureSampling = Sampling.LowPower; _bme280.PressureSampling = Sampling.UltraHighResolution; _bme280.HumiditySampling = Sampling.Standard; // set mode forced so device sleeps after read _bme280.SetPowerMode(Bmx280PowerMode.Forced); } catch (Exception ex) { _logger.Error(ex, "Error creating the sensor"); } }