Facebook Twitter Instagram Pinterest YouTube
    Trending
    • Pi Pico W Launched
    • Add Kodi to RetroPie Menu
    • Disable Auto-login in Raspberry Pi OS
    • Raspberry Pi Cloud Storage with MEGA
    • RetroPie Temperature Monitor from Menu
    • Pi Pico Pinout and Power Pins
    • Install Arduino IDE on Raspberry Pi
    • Raspberry Pi 400 SSD Upgrade
    Facebook Twitter Instagram Pinterest YouTube RSS
    Raspberry Pi SpyRaspberry Pi Spy
    • Home
    • Categories
      • General
      • Hardware
      • Programming
      • Python
      • Software
      • Tutorials & Help
    • BerryClip
      • BerryClip Instructions
      • BerryClip Plus Instructions
      • Videos & Reviews
    • Buy
      • Buy Pi
      • Buy Pi Accessories
      • Buy Books
    • Tools
      • Ultimate Raspberry Pi Alexa Skill
      • Pi Power Estimator App
      • Pi-Lite 14×9 LED Matrix Sprite Editor
      • RPiREF Pin-out Reference App
      • Simple Ohm’s Law Calculator
      • Web Sites & Links
    • Tutorials & Help
        Featured
        November 9, 20200

        Raspberry Pi Temperature Monitoring

        Recent
        May 6, 2022

        Add Kodi to RetroPie Menu

        February 26, 2022

        Disable Auto-login in Raspberry Pi OS

        February 2, 2022

        Raspberry Pi Cloud Storage with MEGA

      1. Contact Us
      2. Site Map
      Raspberry Pi SpyRaspberry Pi Spy
      You are at:Home»Hardware»Interfaces»I2C»Using the BME280 I2C Temperature and Pressure Sensor in Python
      BME280 Temperature Sensor

      Using the BME280 I2C Temperature and Pressure Sensor in Python

      43
      By Matt on July 21, 2016 I2C, Sensors, Tutorials & Help

      The BME280 device is a digital barometric pressure sensor and is a slightly upgraded version of the BMP180. This is available on a small module which provides access to the sensor via the I2C interface. This allows us to easily connect it to the Raspberry Pi and read the data using Python. The BME280 provides temperature, pressure and humidity.

      BME280 Temperature Pressure SensorThe BME280 is made by Bosch and the official BME280 datasheet includes all the technical details. Their device can offer both SPI and I2C interfaces so you need to make sure your module provides the interface you prefer.

      My module is a small pcb measuring 14x10mm with a 4 pin I2C header. The order of the pins may vary on other modules so keep an eye on the labels so you connect up the correct wires from the Pi.

      Configure I2C Interface

      In order to use this module you must enable the I2C interface on the Raspberry Pi as it is not enabled by default. This is a fairly easy process and is described in my Enabling The I2C Interface On The Raspberry Pi tutorial.

      Connecting Hardware

      The table below shows how the module is connected to the Raspberyr Pi’s GPIO header (P1). Please refer to my GPIO header guide for a diagram.

      Module PCBDescGPIO Header Pins
      VCC3.3VP1-01
      GNDGroundP1-06
      SCLI2C SCLP1-05
      SDAI2C SDAP1-03

      Here is a diagram of a breadboard setup. If you are connecting the module’s four pins directly to the Pi you only need four female-female wires.

      BME280 Module Setup

      Other modules are available which have different pin arrangements so make sure you are connecting the correct pins to the Pi if yours is different to the one shown in this tutorial.

      With the device connected and the Pi powered up the “i2cdetect” command should show the device with address 0x76 or 0x77.

      Download BME280 Script

      To download the BME280 Python script from my Bitbucket repository you can use :

      wget -O bme280.py http://bit.ly/bme280py

      or

      wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/bme280.py

      or right-click on this link in your browser and save locally.

      Run the Script

      Before running the script you should check that your device is connected. If you installed the i2c-tools package as part of the i2c setup you should use the i2cdetect command to check it returns an address for your device. The script assumes the address is 0x76. You can change that by editing the DEVICE variable in bme280,py using your favourite text editor.

      Run the script using :

      python bme280.py

      Here is the output I see on my Pi :

      BME280 Sensor Setup

      Script Breakdown

      The script is fairly straight forward but has some scary looking maths in it. This is defined in the datasheet and you will be forgiven for not worrying too much how it works! I rough summary of the script is given below if you want to follow it through in a bit more detail :

      • imports some libraries
      • defines some functions
      • function main uses the readBME280ID function to get the ID of the device
      • function main then calls readBME280All which …
        • sets the oversampling and mode
        • reads calibration data from the device that was preset in the factory
        • reads the raw temperature, pressure and humidity data
        • refines the data using the maths from the datasheet
        • returns the values to main()

      Include In Your Own Script

      You could just modify the main function in my script but you may want to include the functionality in your own. To do this you can import my script and then reference the readBME280ID and readBME280All functions as in the example below :

      import bme280
      
      (chip_id, chip_version) = bme280.readBME280ID()
      print "Chip ID :", chip_id
      print "Version :", chip_version
      
      temperature,pressure,humidity = bme280.readBME280All()
      
      print "Temperature : ", temperature, "C"
      print "Pressure : ", pressure, "hPa"
      print "Humidity : ", humidity, "%"

      The rest is down to your imagination.

      Troubleshooting

      • If the i2cdetect command results in an error you have either not installed i2c-tools or you need to use 0 rather than 1
      • If your device is not detected and you don’t see the address you have either not connected the device properly or have not correctly enabled the i2c interface
      • Double check your wiring and reboot the Pi

      In most cases i2c experiments fail to work because :

      • i2c is not enabled
      • The device is not connected properly
      • i2c-tools has not been installed so the i2cdetect command is not available

      In rare cases your device may be faulty but it is far more likely to be one of the above issues.


      The module is available from Amazon and many other online electronics shops. You can also find .

      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous Article12 inch GPIO Zero Ruler from RasPi.TV
      Next Article Mini NES Classic Raspberry Pi Games Console

      Related Posts

      Add Kodi to RetroPie Menu

      Disable Auto-login in Raspberry Pi OS

      Raspberry Pi Cloud Storage with MEGA

      43 Comments

      1. willie on August 8, 2016 8:36 pm

        thank you! the script works great and i used your example as a ‘library’ – all i needed to do was import one function and i had a working display showing ambient conditions! great work!

        Reply
      2. Phil on August 31, 2016 10:10 am

        Hi, will this also work with the BMP280 which appears to have an extra pin? Thank you.

        Reply
      3. TheoryX on September 7, 2016 8:43 am

        Hey. What is the wire length limit for BME280 because of the I2C? I’ve read some time ago that I2C has aproblem with long wires, do you know anything about this?

        Reply
        • Matt on September 15, 2016 4:53 pm

          I think the limit for i2c is a few metres but it depends on a number of factors including resistance and the i2c clock frequency.

          Reply
      4. Stephen on September 12, 2016 4:48 pm

        My BME280 module doesn’t have an SDA connection, but has two labeled as SDI and SDO – should I be using the SDO for output data? Because of this, I’m receiving I/O errors (IOError: [Errno 5] Input/output error).

        Reply
        • Matt on September 15, 2016 4:52 pm

          Do you have a SCK pin as well? SDO/SDI is usually for an SPI interface but some modules let you do i2c using the SCK/SDI pins.

          Reply
        • Scott on November 11, 2016 4:59 pm

          I had the same problem. Fixed it by connecting SDO to GND.

          Reply
          • Thi Tran on January 30, 2021 5:28 am

            THANK YOU SO MUCH

            Reply
      5. PedroKV on October 8, 2016 8:23 am

        I realized that the first reading is not accurate, only second and next.

        Reply
      6. Al on October 16, 2016 12:06 pm

        Hi,

        Working fine for now.

        Next steps to be:
        1. Log details to file so I can export manual to excel
        2. Future export auto to exel and make graph’s for it
        3. Getting the BME280 working in OpenPlotter

        But as greenhorn in Python I want to do step by step so I also will get some understanding about Python.

        Can someone point me in good direction for next step, the logging script?

        Thanks
        Al

        Reply
      7. James on October 17, 2016 9:58 pm

        Thank you, Matt. I struggled to find information about how to use this module before finding your blog post.

        Reply
      8. Paul on November 5, 2016 2:09 pm

        Hi, great site, noticed a problem in this BME280 code in that you are not configuring the oversample mode for the humidity so does not read accurately. I added the following 3 lines to your code before the write of the BMP180 (REG_CONTROL) register,

        # add configuration of humidity register
        OVERSAMPLE_HUM = 2
        REG_CONTROL_HUM = 0xF2
        bus.write_byte_data(addr, BME280_REG_CONTROL_HUM, OVERSAMPLE_HUM)

        also need to add a delay after the write of read command, adafruit did it like this where self._mode is the oversampling mode of each unit humid,temp,pressure, or the first reading will be duff.

        sleep_time = 0.00125 + 0.0023 * (1 << self._mode)
        sleep_time = sleep_time + 0.0023 * (1 << self._mode) + 0.000575
        sleep_time = sleep_time + 0.0023 * (1 << self._mode) + 0.000575
        time.sleep(sleep_time) # Wait the required time

        Reply
      9. Niccolo Rigacci on November 13, 2016 5:46 pm

        Hello!
        I was comparing the code with the datasheet and I wonder if there is a typo at line 140: may be the 16384.8 should be 16384.0 instead?

        I’m also a bit confused because the refine calculation uses different formulas than the ones in the datasheet. I’m investigating about humidity and I get different values (about 0.001 on the final % value). May be the bit shift (as per datasheet) performs round-up differently than converting early to float (as your code do)?

        Thank you very much for your code!

        Reply
      10. Steve on December 19, 2016 10:57 am

        I was puzzled by the humidity data coming out of my BME280 using this code, as the values were constantly in the 72% area. Investigation showed that you are not initialising register 0xF2 wich sets the humidity oversampling. When I added a couple of lines to correct this, I started receiving values that matched an HTU21D.

        Reply
        • Chris on January 2, 2017 10:26 pm

          Steve

          I am new at all this and very confused.
          can you be more specific about the lines you added to correct this please.

          Thanks

          Reply
          • Matt on January 3, 2017 11:39 pm

            The script has already been updated. The two lines after “# Oversample setting for humidity register – page 26” initialise the humidity register.

            Reply
      11. Simon Maddox on January 13, 2017 1:16 pm

        I am having difficulties with this script. I made 2 changes in order to round the pressure value and to output the raw_hum value (for debug). The Humidity is always 0.0% and raw_hum never changes from 35152. Has anyone else had this issue, or is it a problem with my sensor?

        pi@raspberrypi:~ $ python bme280.py
        Chip ID : 88
        Version : 0
        Temperature : 27.38 C
        Pressure : 997.71 mbar
        Humidity : 0.0 %
        Raw Humidity : 35152

        Reply
        • Matt on January 14, 2017 7:17 pm

          Are you definitely using a BME280? Lots of people who have trouble with humidity are using a BMP280 which doesn’t support it.

          Reply
          • Stephen Lovatt on October 23, 2018 12:43 pm

            I had exactly this problem. I only just noticed that I had the BMP20 not the BME280.

            !!! BOTHER !!!

            Reply
      12. Niccolo Rigacci on January 22, 2017 7:26 pm

        After many weeks of data acquisition with BME280 sensor, I confirmed that Matt’s software has a problem with humidity reading. Strangely, the graph of temperature and humidity have the same identical shape. The problem was solved when I installed the Adafruit library. Having checked the source code, it seems that the only difference is in the pause that the Adafruit library performs between writing to the registry and reading the humidity value, where the Matt’s code does not pause at all. From BME datasheet, Appendix B “Measurement time and current calculation” it seems indeed that a pause is required.

        Reply
        • Matt on January 29, 2017 12:16 pm

          Thanks Niccolo. You are correct. I’ve added the wait just before the “read” based on the equation given in the datasheet under “Appendix B: Measurement time and current calculation”.

          Reply
      13. Alain Gioanni on March 20, 2017 3:29 pm

        Hi

        1 – I would like to adapt this script to use it on microPython MCU (Lopy), how do i deal with the ctypes library ?
        2 – I need to switch to SPI because of a to too long wire cable any idea ?

        Thanks for help
        Alain

        Reply
      14. Jan on September 13, 2017 11:28 am

        HI it works fine, but since yesterday it stops reading anything. After a quick check I just get this message as response of the script:

        Traceback (most recent call last):
        File “/usr/lib/python2.7/site.py”, line 68, in
        import os
        File “/usr/lib/python2.7/os.py”, line 400, in
        import UserDict
        ValueError: bad marshal data (string ref out of range)

        but I did nothing on the pi… is my device broken?

        Reply
        • Matt on September 14, 2017 10:26 pm

          Delete the .pyc files. This error can occur if they are corrupt. When you run the .py script the .pyc file will be re-created.

          Reply
      15. Glitch on September 16, 2017 9:18 pm

        Hi Matt, would like to say thank you for your work, it made my life easy!
        Im using bme280 on orange-pi-pc, and works fine as imported module /smbus0/
        Really great job, im grateful!

        Reply
      16. Avioza on October 7, 2017 12:00 am

        Thank you for sharing. This worked great for me and saved a lot of time. I appreciate it!

        Reply
      17. Christian on November 18, 2017 12:25 am

        Thank you Matt! You saved me hours of work. Thank you so much!!

        Matt on January 3, 2017 11:39 pm
        Delete the .pyc files. This error can occur if they are corrupt. When you run the .py script the .pyc file will be re-created.

        Reply
      18. Chris Jones on March 1, 2018 1:59 pm

        Im interested in measuring outdoor humidity and temperature – could I use this outside? Would I need to protect it from the elements in some way (assuming the pi itself was in a waterproof box)

        Reply
        • Matt on March 13, 2018 7:30 pm

          I think the pressure sensor is a tiny hole in the device. So it would need protection from rain and dust.

          Reply
      19. Henk Oegema on July 16, 2018 7:35 pm

        I have this device:
        bottum : https://i.imgur.com/epDTAf1.jpg
        top: https://i.imgur.com/mEgQxZN.jpg

        Is this a BMP280 or a BME280 ?

        It doesn’t read humidity. (??)
        ===================================
        pi@raspberrypi2:~/test $ python bme280.py
        Chip ID : 88
        Version : 1
        Temperature : 26.9 C
        Pressure : 1012.39631211 hPa
        Humidity : 0.0 % <———-?????
        =================================

        Does the chip id (88) give any clarification ?

        Reply
        • Matt on July 16, 2018 8:56 pm

          I think the BMP280 is chip ID 88 (0x58) but the BME280 is 96 (0x60). So I suspect your device is a BMP280.

          Reply
      20. Andre on November 1, 2018 2:24 pm

        Hello,
        your python script is working great ! I extended it to two sensors for measurement of humidity at intake and outlet of a air-dehumidifier. I would like to use it for instructional purposes in my class on applied thermodynamics. Would you allow me to use your script and to publish it when I cite your reference ?

        best regards,
        Andre

        Reply
        • Matt on November 1, 2018 2:36 pm

          Hi Andre, glad you found the script useful. Happy for you to use it in your class instruction material.

          Reply
      21. Richie on December 8, 2018 2:04 pm

        This is the the best way to read bme280! I tried many other options, and this works well, thank you for sharing!!!

        Reply
      22. Willem on December 30, 2018 3:17 pm

        Great! Thanks a lot. Good job.

        Reply
      23. Tiziano Binda on January 6, 2019 9:51 am

        Great! Thanks a lot. Good job.
        The script run out the box. I’ll make a class for my purposes.
        Enjoy!

        Reply
      24. zonediver on February 15, 2019 12:08 pm

        I tried also many other “ways” to read this sensor, but your script is by far the best!
        Thanks a lot for sharing – good work

        Reply
      25. Maximo on July 5, 2019 10:42 pm

        Thank you!!!!

        Reply
      26. MIKE on November 1, 2019 9:03 pm

        Worked like a charm! Thanks for this straightforward tutorial.

        Reply
      27. Walter on November 20, 2019 10:50 am

        Hi Matt, great work! The temperature and humidity reading is fine, but the pressure allways shows around 948 – 952 hPa. Might this be a sensor problem?

        Reply
      28. Catalin on February 4, 2020 9:04 pm

        Hi,

        What to do in order to let this running into a loop?

        Thank you,
        Catalin

        Reply
      29. AG on March 28, 2020 8:20 am

        Great script! Thank you for sharing and for the step-by-step instructions.

        Worked perfectly after I finally managed to connect the sensor properly.

        Reply
      30. Martin M on May 31, 2020 4:03 pm

        Hi,
        Great Job!
        Is there a way to add the data to Influx/Grafana?

        Reply

      Leave A Reply Cancel Reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Recent Posts
      June 30, 2022

      Pi Pico W Launched

      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      February 2, 2022

      Raspberry Pi Cloud Storage with MEGA

      January 7, 2022

      RetroPie Temperature Monitor from Menu

      Categories
      • 1-wire
      • 3D Printing
      • Add-ons
      • BBC Micro:bit
      • BerryClip
      • Books
      • Camera Module
      • Cases
      • Events
      • General
      • Hardware
      • I2C
      • Infographics
      • Interfaces
      • Minecraft
      • Model A+
      • Model B+
      • News
      • Pi Models
      • Pi Pico
      • Pi Zero
      • Power
      • Programming
      • Python
      • Raspberry Pi OS
      • Raspbian
      • RetroGaming
      • Robotics
      • Sensors
      • Software
      • SPI
      • Tutorials & Help
      Tags
      3D Printing Arduino audio battery berryclip Birthday bluetooth cambridge camera CamJam DigiMakers display games GPIO I2C interface Kickstarter LCD LED Linux media Minecraft Model A Model B motionEyeOS PCB photography photos Pi-Lite portable power python Raspberry Jam Raspberry Pi Bootcamp raspbian Retrogaming retroPie screen SD card security sensor SPI temperature ultrasonic video
      Raspberry PI Related
      • Adafruit Blog
      • Average Maker
      • Official RaspBerry Pi Site
      • Raspberry Pi Pod
      • RasPi.tv
      • RaspTut
      • Stuff About Code
      Tech Resources
      • MattsBits – Pi Resources
      • Microbit Spy
      • Technology Spy
      Archives
      About

      Unofficial site devoted to the Raspberry Pi credit card sized computer offering tutorials, guides, resources,scripts and downloads. We hope to help everyone get the most out of their Pi by providing clear, simple articles on configuring, programming and operating it.

      Popular Posts
      September 19, 2014

      Top 5 Reasons The Raspberry Pi Sucks

      July 27, 2012

      16×2 LCD Module Control Using Python

      October 20, 2013

      Analogue Sensors On The Raspberry Pi Using An MCP3008

      Recent Posts
      June 30, 2022

      Pi Pico W Launched

      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      Facebook Twitter Instagram Pinterest YouTube RSS

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2022 - All Rights Reserved - Matt Hawkins

      Type above and press Enter to search. Press Esc to cancel.