bme280-rs icon indicating copy to clipboard operation
bme280-rs copied to clipboard

called `Result::unwrap()` on an `Err` value: InvalidData

Open weiying-chen opened this issue 4 months ago • 10 comments

With this code (to read the weather with esp32-c3 and bm280):

use esp_idf_svc::hal::{
    delay,
    i2c::{I2cConfig, I2cDriver},
    peripherals::Peripherals,
    prelude::*,
};

use bme280::i2c::BME280;

fn main() {
    esp_idf_svc::sys::link_patches();
    esp_idf_svc::log::EspLogger::initialize_default();

    let peripherals = Peripherals::take().unwrap();
    let sda = peripherals.pins.gpio2;
    let scl = peripherals.pins.gpio3;
    let config = I2cConfig::new().baudrate(400_u32.kHz().into());
    let i2c = I2cDriver::new(peripherals.i2c0, sda, scl, &config).unwrap();
    let mut bme280 = BME280::new_primary(i2c);
    let mut delay = delay::Ets;

    bme280.init(&mut delay);

    loop {
        let measurements = bme280.measure(&mut delay).unwrap();

        log::info!("Relative Humidity = {}%", measurements.humidity);
        log::info!("Temperature = {} deg C", measurements.temperature);
        log::info!("Pressure = {} pascals", measurements.pressure);
        delay::FreeRtos::delay_ms(10000u32);
    }
}

And I get this error:

thread 'main' panicked at src/main.rs:40:55:
called `Result::unwrap()` on an `Err` value: InvalidData

It panics here:

let measurements = bme280.measure(&mut delay).unwrap();

It's strange because this almost identical code works:

#![no_std]
#![no_main]

use bme280::i2c::BME280;
use esp32c3_hal::{clock::ClockControl, i2c::I2C, peripherals::Peripherals, prelude::*, Delay, IO};
use esp_backtrace as _;
use esp_println::println;

#[entry]
fn main() -> ! {
    let peripherals = Peripherals::take();
    let system = peripherals.SYSTEM.split();
    let clocks = ClockControl::boot_defaults(system.clock_control).freeze();
    let mut delay = Delay::new(&clocks);
    let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
    let sda = io.pins.gpio2;
    let scl = io.pins.gpio3;
    let i2c = I2C::new(peripherals.I2C0, sda, scl, 400u32.kHz(), &clocks);
    let mut bme280 = BME280::new_primary(i2c);

    bme280.init(&mut delay).unwrap();

    loop {
        let measurements = bme280.measure(&mut delay).unwrap();
        println!("Relative Humidity = {}%", measurements.humidity);
        println!("Temperature = {} deg C", measurements.temperature);
        println!("Pressure = {} pascals", measurements.pressure);
        delay.delay_ms(1000u32);
    }
}

What could be the issue with the first code?

weiying-chen avatar Feb 17 '24 14:02 weiying-chen