/// <summary> /// Entry point for example program /// </summary> /// <param name="args">Command line arguments</param> public static void Main(string[] args) { Console.WriteLine("Hello Bmp280!"); // bus id on the raspberry pi 3 const int busId = 1; // set this to the current sea level pressure in the area for correct altitude readings var defaultSeaLevelPressure = Pressure.MeanSeaLevel; var i2cSettings = new I2cConnectionSettings(busId, Bmp280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmp280 = new Bmp280(i2cDevice); using (i2CBmp280) { while (true) { // set higher sampling i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; // set mode forced so device sleeps after read i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed var measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out var tempValue); Console.WriteLine($"Temperature: {tempValue.Celsius} \u00B0C"); i2CBmp280.TryReadPressure(out var preValue); Console.WriteLine($"Pressure: {preValue.Hectopascal} hPa"); i2CBmp280.TryReadAltitude(defaultSeaLevelPressure, out var altValue); Console.WriteLine($"Altitude: {altValue} m"); Thread.Sleep(1000); // change sampling rate i2CBmp280.TemperatureSampling = Sampling.UltraHighResolution; i2CBmp280.PressureSampling = Sampling.UltraLowPower; i2CBmp280.FilterMode = Bmx280FilteringMode.X4; // set mode forced and read again i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out tempValue); Console.WriteLine($"Temperature {tempValue.Celsius} \u00B0C"); i2CBmp280.TryReadPressure(out preValue); Console.WriteLine($"Pressure {preValue.Hectopascal} hPa"); i2CBmp280.TryReadAltitude(defaultSeaLevelPressure, out altValue); Console.WriteLine($"Altitude: {altValue} m"); Thread.Sleep(5000); } } }
public void CalculationWithSampleValues() { Bmp280 sensor = new Bmp280(_i2cDevice); sensor.TemperatureSampling = Sampling.HighResolution; sensor.TryReadTemperature(out Temperature temperature); Assert.Equal(25.08, temperature.DegreesCelsius, 2); sensor.TryReadPressure(out Pressure pressure); Assert.Equal(100653.27, pressure.Pascals, 2); sensor.Dispose(); }
public override async Task Start() { switch (SelectedSensor) { case "BMP280/BME280": Sensor = (await Bmp280.ProbeAsync(Board.I2c, true))[0]; break; } Sensor.AutoUpdateWhenPropertyRead = false; OnPropertyChanged(nameof(Sensor)); }
internal void ReadFromDevice(Bmp280 bmp280) { // Read temperature calibration data DigT1 = bmp280.Read16BitsFromRegister((byte)Register.DIG_T1); DigT2 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_T2); DigT3 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_T3); // Read pressure calibration data DigP1 = bmp280.Read16BitsFromRegister((byte)Register.DIG_P1); DigP2 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P2); DigP3 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P3); DigP4 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P4); DigP5 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P5); DigP6 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P6); DigP7 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P7); DigP8 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P8); DigP9 = (short)bmp280.Read16BitsFromRegister((byte)Register.DIG_P9); }
static void Main(string[] args) { Console.WriteLine("You are modified"); using Lcd2004 lcdDisplay = new Lcd2004(22, 17, new int[] { 25, 24, 23, 18 }); using Bmp280 tempSensor = new Bmp280(I2cDevice.Create(new I2cConnectionSettings(1, 0x77))); tempSensor.SetTemperatureSampling(Sampling.UltraHighResolution); tempSensor.SetPowerMode(Bmx280PowerMode.Normal); using CancellationTokenSource cts = new CancellationTokenSource(); Task workTask = Task.Run(() => DoWorkAsync(lcdDisplay, tempSensor, cts.Token), cts.Token); Console.WriteLine("Press Enter to stop the program..."); // Run until user adds input Console.ReadLine(); cts.Cancel(); workTask.Wait(5000); lcdDisplay.Clear(); }
GetBmp280TemperatureAndPressure() { // bus id on the raspberry pi 3 and 4 const int busId = 1; // set this to the current sea level pressure in the area for correct altitude readings var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel; I2cConnectionSettings i2CSettings = new(busId, Bmx280Base.DefaultI2cAddress); var i2CDevice = I2cDevice.Create(i2CSettings); using var i2CBmp280 = new Bmp280(i2CDevice) { TemperatureSampling = Sampling.HighResolution, PressureSampling = Sampling.HighResolution }; // Perform a synchronous measurement var readResult = await i2CBmp280.ReadAsync(); var temperature = readResult.Temperature; Console.WriteLine($"Temperature: {Green($"{readResult.Temperature?.DegreesFahrenheit:0.#}\u00B0F")}"); var pressure = readResult.Pressure; Console.WriteLine($"Pressure: {Green($"{readResult.Pressure?.Millibars:0.##}mb")}"); if (temperature == null || pressure == null) { return(readResult.Temperature?.DegreesFahrenheit, readResult.Pressure?.Millibars); } var altitude = WeatherHelper.CalculateAltitude(pressure.Value, defaultSeaLevelPressure, temperature.Value); Console.WriteLine($"Calculated Altitude: {Green($"{altitude.Feet:0,000}")}"); return(readResult.Temperature?.DegreesFahrenheit, readResult.Pressure?.Millibars); }
private static void TestI2c(ArduinoBoard board) { var device = board.CreateI2cDevice(new I2cConnectionSettings(0, Bmp280.DefaultI2cAddress)); var bmp = new Bmp280(device); bmp.StandbyTime = StandbyTime.Ms250; bmp.SetPowerMode(Bmx280PowerMode.Normal); Console.WriteLine("Device open"); while (!Console.KeyAvailable) { bmp.TryReadTemperature(out var temperature); bmp.TryReadPressure(out var pressure); Console.Write($"\rTemperature: {temperature.DegreesCelsius:F2}°C. Pressure {pressure.Hectopascals:F1} hPa "); Thread.Sleep(100); } bmp.Dispose(); device.Dispose(); Console.ReadKey(); Console.WriteLine(); }
static async Task DoWorkAsync(Lcd2004 lcd, Bmp280 sensor, CancellationToken token) { string currentTemp = "Current temp:"; while (!token.IsCancellationRequested) { lcd.Clear(); try { Temperature temp = await sensor.ReadTemperatureAsync(); lcd.Write(currentTemp); lcd.SetCursorPosition(0, 1); lcd.Write($"{temp.Celsius.ToString("0.00")} degrees"); } catch (Exception e) { Console.WriteLine("Error when attempting to read the Bme280 sensor:"); Console.WriteLine($" {e.Message}"); Console.WriteLine($" {e.StackTrace}"); } Thread.Sleep(1000); } }
public static void Main() { Debug.WriteLine(".Net Nanoframework with BMP280 Sensor!"); // connect to wifi if (!ConnectToWifi()) { return; } // set up for LED and pin const int pin = 18; const int lightTime = 1000; const int dimTime = 4000; using GpioController led = new(); led.OpenPin(pin, PinMode.Output); // set up for BMP280 const int busId = 1; I2cConnectionSettings i2cSettings = new(busId, Bmp280.DefaultI2cAddress); I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); using var i2CBmp280 = new Bmp280(i2cDevice); // Create an X.509 certificate object and create device client for Azure IoT Hub X509Certificate2 deviceCert = new X509Certificate2(cert, privateKey, "1234"); DeviceClient azureIoTClient = new DeviceClient(IotBrokerAddress, DeviceID, deviceCert, azureCert: new X509Certificate(rootCA)); var isOpen = azureIoTClient.Open(); Debug.WriteLine($"Connection is open: {isOpen}"); while (true) { try { // set higher sampling and perform a synchronous measurement i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; var readResult = i2CBmp280.Read(); // led on led.Write(pin, PinValue.High); Thread.Sleep(lightTime); // print out the measured data string temperature = readResult.Temperature.DegreesCelsius.ToString("F"); string pressure = readResult.Pressure.Hectopascals.ToString("F"); Debug.WriteLine("-----------------------------------------"); Debug.WriteLine($"Temperature: {temperature}\u00B0C"); Debug.WriteLine($"Pressure: {pressure}hPa"); // send to Iot Hub string message = $"{{\"Temperature\":{temperature},\"Pressure\":{pressure},\"DeviceID\":\"{DeviceID}\"}}"; azureIoTClient.SendMessage(message); Debug.WriteLine($"Data is pushed to Iot Hub: {message}"); // led off led.Write(pin, PinValue.Low); Thread.Sleep(dimTime); } catch (Exception ex) { Debug.WriteLine($"An error occured: {ex.Message}"); } } }
public override async Task Stop() { Sensor = null; }
static async Task Main(string[] args) { Console.WriteLine("Hello Bmp280!"); //bus id on the raspberry pi 3 const int busId = 1; //set this to the current sea level pressure in the area for correct altitude readings const double defaultSeaLevelPressure = 1033.00; var i2cSettings = new I2cConnectionSettings(busId, Bmp280.DefaultI2cAddress); var i2cDevice = new UnixI2cDevice(i2cSettings); var i2CBmp280 = new Bmp280(i2cDevice); using (i2CBmp280) { while (true) { ////set mode forced so device sleeps after read i2CBmp280.SetPowerMode(PowerMode.Forced); //set samplings i2CBmp280.SetTemperatureSampling(Sampling.UltraLowPower); i2CBmp280.SetPressureSampling(Sampling.UltraLowPower); //read values Temperature tempValue = await i2CBmp280.ReadTemperatureAsync(); Console.WriteLine($"Temperature {tempValue.Celsius}"); double preValue = await i2CBmp280.ReadPressureAsync(); Console.WriteLine($"Pressure {preValue}"); double altValue = await i2CBmp280.ReadAltitudeAsync(defaultSeaLevelPressure); Console.WriteLine($"Altitude: {altValue}"); Thread.Sleep(1000); //set higher sampling i2CBmp280.SetTemperatureSampling(Sampling.LowPower); Console.WriteLine(i2CBmp280.ReadTemperatureSampling()); i2CBmp280.SetPressureSampling(Sampling.UltraHighResolution); Console.WriteLine(i2CBmp280.ReadPressureSampling()); //set mode forced and read again i2CBmp280.SetPowerMode(PowerMode.Forced); //read values tempValue = await i2CBmp280.ReadTemperatureAsync(); Console.WriteLine($"Temperature {tempValue.Celsius}"); preValue = await i2CBmp280.ReadPressureAsync(); Console.WriteLine($"Pressure {preValue}"); altValue = await i2CBmp280.ReadAltitudeAsync(defaultSeaLevelPressure); Console.WriteLine($"Altitude: {altValue}"); Thread.Sleep(5000); //set sampling to higher i2CBmp280.SetTemperatureSampling(Sampling.UltraHighResolution); Console.WriteLine(i2CBmp280.ReadTemperatureSampling()); i2CBmp280.SetPressureSampling(Sampling.UltraLowPower); Console.WriteLine(i2CBmp280.ReadPressureSampling()); } } }
public static void DisplayModes(ArduinoBoard board) { const int Gpio2 = 2; const int MaxMode = 10; Length stationAltitude = Length.FromMeters(650); int mode = 0; var gpioController = board.CreateGpioController(); gpioController.OpenPin(Gpio2); gpioController.SetPinMode(Gpio2, PinMode.Input); CharacterDisplay disp = new CharacterDisplay(board); Console.WriteLine("Display output test"); Console.WriteLine("The button on GPIO 2 changes modes"); Console.WriteLine("Press x to exit"); disp.Output.ScrollUpDelay = TimeSpan.FromMilliseconds(500); AutoResetEvent buttonClicked = new AutoResetEvent(false); void ChangeMode(object sender, PinValueChangedEventArgs pinValueChangedEventArgs) { mode++; if (mode > MaxMode) { // Don't change back to 0 mode = 1; } buttonClicked.Set(); } gpioController.RegisterCallbackForPinValueChangedEvent(Gpio2, PinEventTypes.Falling, ChangeMode); var device = board.CreateI2cDevice(new I2cConnectionSettings(0, Bmp280.DefaultI2cAddress)); Bmp280?bmp; try { bmp = new Bmp280(device); bmp.StandbyTime = StandbyTime.Ms250; bmp.SetPowerMode(Bmx280PowerMode.Normal); } catch (IOException) { bmp = null; Console.WriteLine("BMP280 not available"); } OpenHardwareMonitor hardwareMonitor = new OpenHardwareMonitor(); hardwareMonitor.EnableDerivedSensors(); TimeSpan sleeptime = TimeSpan.FromMilliseconds(500); string modeName = string.Empty; string previousModeName = string.Empty; int firstCharInText = 0; while (true) { if (Console.KeyAvailable && Console.ReadKey(true).KeyChar == 'x') { break; } // Default sleeptime = TimeSpan.FromMilliseconds(500); switch (mode) { case 0: modeName = "Display ready"; disp.Output.ReplaceLine(1, "Button for mode"); // Just text break; case 1: { modeName = "Time"; disp.Output.ReplaceLine(1, DateTime.Now.ToLongTimeString()); sleeptime = TimeSpan.FromMilliseconds(200); break; } case 2: { modeName = "Date"; disp.Output.ReplaceLine(1, DateTime.Now.ToShortDateString()); break; } case 3: modeName = "Temperature / Barometric Pressure"; if (bmp != null && bmp.TryReadTemperature(out Temperature temp) && bmp.TryReadPressure(out Pressure p2)) { Pressure p3 = WeatherHelper.CalculateBarometricPressure(p2, temp, stationAltitude); disp.Output.ReplaceLine(1, string.Format(CultureInfo.CurrentCulture, "{0:s1} {1:s1}", temp, p3)); }
/// <summary> /// Opens the data logger. /// </summary> /// <returns> /// <see langword="false"/> if any of the sensors failed to open, otherwise <see langword="true"/>. /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the data logger is already open. /// </exception> public bool Open() { if (IsOpen) { throw new InvalidOperationException("The data logger is already open"); } IsOpen = true; bool success = true; if (config.IsSensorEnabled(AwsSensor.AirTemperature)) { try { airTempSensor = new Mcp9808(); airTempSensor.Open(); } catch { gpio.Write(config.errorLedPin, PinValue.High); LogMessage("Failed to open airTemp sensor"); success = false; } } if (config.IsSensorEnabled(AwsSensor.RelativeHumidity)) { try { relHumSensor = new Htu21d(); relHumSensor.Open(); } catch { gpio.Write(config.errorLedPin, PinValue.High); LogMessage("Failed to open relHum sensor"); success = false; } } if (config.IsSensorEnabled(AwsSensor.Satellite)) { SatelliteConfiguration satConfig = new SatelliteConfiguration(); if (config.IsSensorEnabled(AwsSensor.WindSpeed)) { satConfig.WindSpeedEnabled = true; satConfig.WindSpeedPin = (int)config.sensors.satellite.windSpeed.pin; } if (config.IsSensorEnabled(AwsSensor.WindDirection)) { satConfig.WindDirectionEnabled = true; satConfig.WindDirectionPin = (int)config.sensors.satellite.windDir.pin; } if (config.IsSensorEnabled(AwsSensor.SunshineDuration)) { satConfig.SunshineDurationEnabled = true; satConfig.SunshineDurationPin = (int)config.sensors.satellite.sunDur.pin; } try { satellite = new Satellite((int)config.sensors.satellite.port, satConfig); satellite.Open(); } catch { gpio.Write(config.errorLedPin, PinValue.High); LogMessage("Failed to open satellite sensor"); success = false; } } if (config.IsSensorEnabled(AwsSensor.Rainfall)) { try { rainfallSensor = new RainwiseRainew111( (int)config.sensors.rainfall.pin, gpio); rainfallSensor.Open(); } catch { gpio.Write(config.errorLedPin, PinValue.High); LogMessage("Failed to open rainfall sensor"); success = false; } } if (config.IsSensorEnabled(AwsSensor.StationPressure)) { try { staPresSensor = new Bmp280(); staPresSensor.Open(); } catch { gpio.Write(config.errorLedPin, PinValue.High); LogMessage("Failed to open BMP280 sensor"); success = false; } } return(success); }
/// <summary> /// Entry point for example program /// </summary> /// <param name="args">Command line arguments</param> public static void StartBmp(string[] args) { Console.WriteLine("Hello Bmp280!"); Length stationHeight = Length.FromMeters(640); // Elevation of the sensor // bus id on the raspberry pi 3 and 4 const int busId = 1; // set this to the current sea level pressure in the area for correct altitude readings var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel; var i2cSettings = new I2cConnectionSettings(busId, Bmp280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmp280 = new Bmp280(i2cDevice); using (i2CBmp280) { while (true) { // set higher sampling i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; // set mode forced so device sleeps after read i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed var measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out var tempValue); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius} \u00B0C"); i2CBmp280.TryReadPressure(out var preValue); Console.WriteLine($"Pressure: {preValue.Hectopascals} hPa"); // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using // double altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant. i2CBmp280.TryReadAltitude(out var altValue); Console.WriteLine($"Calculated Altitude: {altValue} m"); Thread.Sleep(1000); // change sampling rate i2CBmp280.TemperatureSampling = Sampling.UltraHighResolution; i2CBmp280.PressureSampling = Sampling.UltraLowPower; i2CBmp280.FilterMode = Bmx280FilteringMode.X4; // set mode forced and read again i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out tempValue); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius} \u00B0C"); i2CBmp280.TryReadPressure(out preValue); Console.WriteLine($"Pressure: {preValue.Hectopascals} hPa"); // This time use altitude calculation altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue); Console.WriteLine($"Calculated Altitude: {altValue} m"); // Calculate the barometric (corrected) pressure for the local position. // Change the stationHeight value above to get a correct reading, but do not be tempted to insert // the value obtained from the formula above. Since that estimates the altitude based on pressure, // using that altitude to correct the pressure won't work. var correctedPressure = WeatherHelper.CalculateBarometricPressure(preValue, tempValue, stationHeight); Console.WriteLine($"Pressure corrected for altitude {stationHeight.Meters} m (with average humidity): {correctedPressure.Hectopascals} hPa"); Thread.Sleep(5000); } } }
public static void Main() { Console.WriteLine($".Net IoT with BMP280 Sensor!"); // set up for LED and pin using GpioController led = new(); led.OpenPin(pin, PinMode.Output); // setup for BMP280 I2cConnectionSettings i2cSettings = new(busId, Bmp280.DefaultI2cAddress); I2cDevice i2cDevice = I2cDevice.Create(i2cSettings); using var i2CBmp280 = new Bmp280(i2cDevice); // Create an X.509 certificate object. var cert = new X509Certificate2($"{DeviceID}.pfx", "1234"); var auth = new DeviceAuthenticationWithX509Certificate(DeviceID, cert); DeviceClient azureIoTClient = DeviceClient.Create(IotBrokerAddress, auth, TransportType.Mqtt); if (azureIoTClient == null) { Console.WriteLine("Failed to create DeviceClient!"); } else { Console.WriteLine("Successfully created DeviceClient!"); Console.WriteLine("Press CTRL+D to stop application"); } while (true) { try { // set higher sampling and perform a synchronous measurement i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; var readResult = i2CBmp280.Read(); // led on led.Write(pin, PinValue.High); Thread.Sleep(lightTime); // print out the measured data string temperature = readResult.Temperature?.DegreesCelsius.ToString("F"); string pressure = readResult.Pressure?.Hectopascals.ToString("F"); Console.WriteLine("-----------------------------------------"); Console.WriteLine($"Temperature: {temperature}\u00B0C"); Console.WriteLine($"Pressure: {pressure}hPa"); // send to Iot Hub string message = $"{{\"Temperature\":{temperature},\"Pressure\":{pressure},\"DeviceID\":\"{DeviceID}\"}}"; Message eventMessage = new Message(Encoding.UTF8.GetBytes(message)); azureIoTClient.SendEventAsync(eventMessage).Wait(); Console.WriteLine($"Data is pushed to Iot Hub: {message}"); // blink and led off led.Write(pin, PinValue.Low); Thread.Sleep(75); led.Write(pin, PinValue.High); Thread.Sleep(75); led.Write(pin, PinValue.Low); Thread.Sleep(75); led.Write(pin, PinValue.High); Thread.Sleep(75); led.Write(pin, PinValue.Low); Thread.Sleep(dimTime); } catch (Exception ex) { Console.WriteLine($"An error occured: {ex.Message}"); } } }