Skip to content

BME280 does not measure pressure/altitude correctly when SetPowerMode is not called #753

Closed

Description

@krwq

Test:

private static Bme280 CreateBme280()
{
    var settings = new I2cConnectionSettings(1, Bme280.DefaultI2cAddress);
    return new Bme280(I2cDevice.Create(settings));
}

const double SeaLevelPressure = 1013.25;
using (Bme280 bme280 = CreateBme280())
{
    Assert.True(bme280.TryReadTemperature(out Temperature temperature));
    Console.WriteLine($"Temperature: {temperature.Celsius} C");
    Assert.True(bme280.TryReadPressure(out double pressure));
    Console.WriteLine($"Pressure: {pressure} Pa");
    Assert.True(bme280.TryReadAltitude(SeaLevelPressure, out double altitudeMeters));
    Console.WriteLine($"Altitude: {altitudeMeters} meters");
    Assert.True(bme280.TryReadHumidity(out var relativeHumidity));
    Console.WriteLine($"Humidity: {relativeHumidity} %");
}

Output:

Temperature: 23.0049688216532 C
Pressure: 74116.26953125 Pa
Altitude: 2560.9681612177 meters
Humidity: 62.4485427633319 %

definitely Pressure and Altitude don't seem reasonable. I'm currently at around 15-100m above the sea level.

cc: @RobinTTY @georgemathieson

Activity

  1. added
    bug
    on Sep 30, 2019
  2. krwq commented on Sep 30, 2019

    @krwq
    MemberAuthor

    Seems this is working around the problem with pressure:

    bme280.SetPowerMode(Bmx280PowerMode.Forced);

    The pressure/altitude after this shows us:

    Pressure: 101477.66015625 Pa
    Altitude: -12.7022561440805 meters

    I'm definitely not under water right now so presumably sea level pressure or some other calculation is wrong as well

  3. RobinTTY commented on Sep 30, 2019

    @RobinTTY
    Contributor

    Yeah you will always need to perform a measurement by calling SetPowerMode (this is by design), I just tested this with a reference python library and basically got the same value for pressure:

    Capture

    My phones sensor is currently giving me a value of 981.0 so not far off. I'll take a look at the Altitude formula since I didn't tocuh it in my last PR, maybe something is wrong with that.

  4. krwq commented on Sep 30, 2019

    @krwq
    MemberAuthor

    @RobinTTY python's bug doesn't mean we have to repeat the same bug in here.

    If pressure cannot be read for whatever reason it should throw an exception or return false.
    Constructing BME280 should also provide sane defaults which means it should be usable.

    We cannot return bogus results unless hardware has gone bad.

  5. RobinTTY commented on Sep 30, 2019

    @RobinTTY
    Contributor

    Yeah currently we are providing the default configuration at construction (Things like sampling modes, etc.). The problem is that currently TryReadX has no check whether a measurement was already made since it only reads the register with the values of the last measurement (after device startup default register value). So we could just perform a single measurement on construction to avoid that.

  6. RobinTTY commented on Sep 30, 2019

    @RobinTTY
    Contributor

    Or probably a check whether a read has been performed is better and just return NaN if non was performed. Since if there is a long timespan between construction and first call of TryRead, the values would be out of date.

    Edit: The altitude formula seems to be correct but it's not taking temperature into account. But that shouldn't make a big difference. Also keep in mind you need to reference the current atmospheric pressure at sea level, a difference of 10hPa can make a difference of 100m.

    I will open a pull request to take temperature into account and to return NaN if no measurement was taken before reading the value.

  7. krwq commented on Sep 30, 2019

    @krwq
    MemberAuthor

    Cool, thank you @RobinTTY! Yes we should either return false+NaN or give correct answer.

    Also, I've actually tried sleeping for 2s before reading the value and it read the wrong value as well, do you also need to call something to initiate reading process?

  8. RobinTTY commented on Sep 30, 2019

    @RobinTTY
    Contributor

    @krwq: So I tried this piece of code:

    class Program
        {
            static void Main(string[] args)
            {
                var settings = new I2cConnectionSettings(1, Bme280.SecondaryI2cAddress);
                var i2c = I2cDevice.Create(settings);
    
                using (var sensor = new Bme280(i2c))
                {
                    var duration = sensor.GetMeasurementDuration();
    
                    for (var i = 0; i < 3; i++)
                    {
                        sensor.SetPowerMode(Bmx280PowerMode.Forced);
                        Task.Delay(duration).Wait();
                        sensor.TryReadTemperature(out var temperature);
                        sensor.TryReadHumidity(out var humidity);
                        sensor.TryReadPressure(out var pressure);
                        sensor.TryReadAltitude(1000, out var altitude);
    
                        Console.WriteLine($"Temperature: {temperature.Celsius}");
                        Console.WriteLine($"Humidity: {humidity}");
                        Console.WriteLine($"Pressure: {pressure}");
                        Console.WriteLine($"Altitude: {altitude}");
                    }
                }
            }
        }

    And I get correct values on the first read. What value was wrong for you?

  9. krwq commented on Oct 1, 2019

    @krwq
    MemberAuthor

    @RobinTTY I'm expecting everything to work without sensor.SetPowerMode(Bmx280PowerMode.Forced);

  10. RobinTTY commented on Oct 1, 2019

    @RobinTTY
    Contributor

    @krwq That would require a change in the current behavior of the driver. The way the sensor works is that you specify settings like sampling rate and filter (you can for instance skip the pressure meassurement and only measure temperature/humidity/gas). Then you trigger the actual measurement by setting the PowerMode.

    The Bmx280 has besides the forced power mode a normal power mode, where measurements are continously being made after setting the sensor to that mode. That is why you always have to set the power mode currently, before reading the results. We could instead change the behavior to something like this:

    // Single Measurement (power mode forced)
    PerformMeasurement(out Temperature temperature, out double pressure, out double humidity)
    {
        _bmx280.SetPowerMode(PowerMode.Forced);
        Task.Delay(measurementTime).Wait();
        temperature = CompensateTemperature(temp >> 4);
        ....
    }
    
    // Continuous measurements (power mode normal)
    PerformContinousMeasurements
    {
        _bmx280.SetPowerMode(PowerMode.Normal);
    }

    That would mean that you would still need the methods to read the registers for the case of the continous measurements but wouldn't need them for a single one. Is that what you would want?

  11. krwq commented on Oct 1, 2019

    @krwq
    MemberAuthor

    @RobinTTY changing the behavior is fine if it is well justified and in this case I think it is.

    I think by default users will expect constructing a class and reading temperature will just work without any extra knowledge and I think this should be the default option (if I understand correctly: PowerMode.Normal). For any advanced settings we should have a way of doing it but it should not be required to read the spec or all docs.

    Does the power mode need to be set before every measurement and cannot be set once globally? The current API shape suggests this is a one-time operation. If this is something you need to do every time the general rule of thumb suggest we should automate it.

    Perhaps something along the lines of (pseudo C#):

    struct ReadResult
    {
      double? Temperature { get; }
      double? Pressure { get; }
      double? Humidity { get; }
      DateTimeOffset Timestamp { get; } // optional: when the measurement was made
    }
    
    struct ReadMode
    {
      Continuous,
      Manual,
    }
    
    class Bme280
    {
      public Bme280(..., ReadMode readMode = ReadMode.Continuous);
      public ReadResult Read();
      public Task<ReadResult> ReadAsync();
    }

    basically for continuous mode Read() will always return immediately and is suggested method of use. For manual mode ReadAsync is suggested which will start measurement and wait for measurement to be completed.

  12. RobinTTY commented on Oct 1, 2019

    @RobinTTY
    Contributor

    @krwq Sounds good to me, I'll submit a PR along with the other changes in the next few days.

  13. krwq commented on Oct 1, 2019

    @krwq
    MemberAuthor

    Thank you @RobinTTY! To avoid extra work/refactoring in the PR it might be worth to write something resembling API proposal (no implementation) - just what you think everything should look like (i.e. just sample code from user perspective)

  14. changed the title [-]BME280 does not measure pressure/altitude correctly[/-] [+]BME280 does not measure pressure/altitude correctly when SetPowerMode is not called[/+] on Oct 1, 2019
  15. RobinTTY commented on Oct 1, 2019

    @RobinTTY
    Contributor

    Sure, I'll post the proposal here.

  16. 16 remaining items

  17. added this to the milestone on Oct 10, 2019
  18. MarkCiliaVincenti commented on Oct 11, 2019

    @MarkCiliaVincenti
    Contributor

    The altitude calculation can be improved. I'm working on a WeatherHelper (#783) and I'll be adding an altitude calculation there. However I'm trying to gather information on how to improve this calculation due to the fact that there is a missing input in the current formula: temperature. The current calculation is assuming 15C, but you can see that temperature affects the altitude calculation. Take a look at https://www.mide.com/pages/air-pressure-at-altitude-calculator for example.

  19. MarkCiliaVincenti commented on Oct 11, 2019

    @MarkCiliaVincenti
    Contributor

    @RobinTTY please take the changes in #783 into consideration when making these changes, because they will conflict otherwise.

  20. modified the milestones: , on Nov 27, 2020
  21. Ellerbach commented on Dec 22, 2020

    @Ellerbach
    Member

    I feel this has been fixed over time with the various PR. So closing it. Feel free to reopen if it's still not the case.

  22. ghost locked as resolved and limited conversation to collaborators on Jan 21, 2021
  23. krwq commented on Jun 14, 2021

    @krwq
    MemberAuthor

    still an issue in 1.4 (it keeps reading same value if you don't set it). I also need to wait around 100ms after setting power mode, otherwise I'm getting random errors ocasionally

  24. reopened this on Jun 14, 2021
  25. removed this from the milestone on Dec 15, 2022
  26. added
    Priority:2
    on Dec 15, 2022
  27. pgrawehr commented on Dec 15, 2022

    @pgrawehr
    Contributor

    Removing vNext, since not a blocker (there's an existing and well-known workaround)

  28. krwq commented on Apr 24, 2025

    @krwq
    MemberAuthor

    [Triage] It would need convenience method but since sample is doing the right thing we don't want to do extra operations. We don't track requests for convenience methods, PR is needed to further discuss this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority:2area-device-bindingsenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions