ESP32 MicroPython MS5611 Pressure Sensor

This tutorial instructs you how to use the MS5611 pressure sensor with the ESP32 and MicroPython. The weather news always gives the lowest and the highest temperature of the day, but almost never the lowest and the highest air pressure. Yet a large gap between these two pressure numbers shows that the weather has changed. So we will build a weather diary: the ESP32 measures the air about once per second and remembers both numbers. In detail, we will learn:

ESP32 MicroPython with MS5611 barometric pressure sensor, module pinout and I2C jumper wiring

Overview of MS5611 Pressure Sensor

Air is light, but there are many kilometers of it above us, and all of it presses down. The DIYables MS5611 module measures this pressure. Other names for the same module are GY-63, barometer, barometric pressure sensor, altimeter and altitude sensor. The chip is the MS5611-01BA03 from TE Connectivity, the small metal can with two tiny holes. Under the holes is a thin silicon membrane. The air pushes on it, so it bends a tiny bit, and the chip measures this bend with a 24-bit converter.

We get the pressure in hPa (hectopascal), which is the same number as in mbar. The standard value at sea level is 1013.25 hPa. At your home the number is often lower, because higher ground has less air above it.

Item MS5611 Module
Module size about 19 x 13 mm
Power 3.3V to 5V, the board has its own 3.3V regulator
Bus I2C (up to 400 kHz) as delivered, SPI possible
Address on I2C 0x77, or 0x76 with CSB on 3.3V
Smallest pressure step 0.012 hPa, the same as about 10 cm of height
Pressure error up to ±1.5 hPa between 700 and 1100 hPa at 25°C
Measures pressure from 10 to 1200 hPa (best between 450 and 1100 hPa)
Time for a pressure conversion about 9 ms at the best resolution
Temperature error up to ±0.8°C at 25°C
Works between -40°C and 85°C

Pinout

MS5611 module pinout for ESP32 MicroPython, four I2C pins and three free pins

Four pins get a wire:

  • VCC pin: connect to 3.3V (3.3 volts) of the ESP32. The module accepts 3.3 to 5 volts, but on the ESP32 it must be 3.3 volts.
  • GND pin: connect to GND (0 volts).
  • SCL pin: the I2C clock. Connect to GPIO22 of the ESP32.
  • SDA pin: the I2C data. Connect to GPIO21 of the ESP32.

Three pins stay empty:

  • CSB pin: the address switch for I2C. With nothing or GND on it, the sensor has 0x77. With 3.3 volts on it, the sensor has 0x76. SPI uses it as chip select.
  • SDO pin: only for SPI, where the data comes out here.
  • PS pin: the protocol switch. The module itself pulls it HIGH with a resistor, and HIGH is I2C. GND would be SPI.

CSB and PS lead to the 3.3 volts chip, so never put 5 volts on them.

What Changes the Pressure

Two things change the number: the weather, and the height of the module.

What Happens Effect on the Pressure
You lift the module by 1 meter about 0.12 hPa lower
You carry it one floor up (3 meters) about 0.36 hPa lower
You carry it 83 meters up a hill about 10 hPa lower
Clouds, wind or rain are coming it often falls by some hPa in a few hours
Fair weather is coming it often rises slowly, or it stays high

In a weather diary, only the last two rows should count. That is why the module stays in one place the whole day.

Wiring Diagram

You need four jumper wires and no extra part. Even the I2C pull-up resistors are on the module.

The wiring diagram between ESP32 MicroPython MS5611 pressure sensor

This image is created using Fritzing. Click to enlarge image

MS5611 Pin ESP32 Pin
VCC 3.3V (3V3 on the board)
GND GND
SCL GPIO22
SDA GPIO21
CSB, SDO, PS not connected

※ NOTE THAT:

Use 3.3V for VCC, not VIN and not 5V. On this module, SCL and SDA always get the voltage of VCC. With 5 volts on VCC, GPIO22 and GPIO21 would see 5 volts too. The ESP32 is a 3.3 volts chip, and that can damage it.

Other GPIOs are possible. Then change SCL_PIN and SDA_PIN at the top of both scripts. Do not take GPIO34 to GPIO39 (they are inputs only) or GPIO6 to GPIO11 (the flash memory uses them).

A good place for the module:

  • In the shade, with no wind, because sun and moving air make the number jump. You can lay some open foam over the metal can.
  • Dry. Keep water and tape away from the two holes of the can.
  • Some centimeters away from the ESP32, because the board gets a little warm.

Do not use it in water or in a tire: the MS5611 is an air pressure sensor only.

MS5611 Driver for the ESP32 with MicroPython

MicroPython has no ready driver for the MS5611, so this tutorial brings its own. It is one file. It sends the commands over I2C, checks the memory of the chip, and does the math that turns the raw numbers into hPa and °C. You do not have to change anything in it:

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-ms5611-pressure-sensor """ # DIYables MS5611 (GY-63) driver for MicroPython on the ESP32 # Save this file on the ESP32 with exactly this name: DIYables_MicroPython_MS5611.py # Nothing needs to be changed here. Sensor: https://diyables.io/ms5611 from time import sleep_ms _CMD_RESET = 0x1E _CMD_CONVERT_D1 = 0x40 # pressure _CMD_CONVERT_D2 = 0x50 # temperature _CMD_READ_ADC = 0x00 _CMD_READ_PROM = 0xA0 # oversampling: (command offset, conversion time in ms) _OSR = { 256: (0, 2), 512: (2, 3), 1024: (4, 4), 2048: (6, 6), 4096: (8, 11), } def _crc4(prom): # 4-bit CRC of the calibration data (application note AN520) remainder = 0 for i in range(16): word = prom[i >> 1] if i % 2 == 0: remainder ^= word >> 8 elif i < 15: # the low byte of the last word holds the CRC itself remainder ^= word & 0x00FF for _ in range(8): if remainder & 0x8000: remainder = ((remainder << 1) ^ 0x3000) & 0xFFFF else: remainder = (remainder << 1) & 0xFFFF return (remainder >> 12) & 0x0F class MS5611: ADDRESS_77 = 0x77 # CSB not connected or connected to GND ADDRESS_76 = 0x76 # CSB connected to 3.3V STANDARD_SEA_LEVEL = 1013.25 # hPa def __init__(self, i2c, address=None, oversampling=4096, ms5607=False): self._i2c = i2c self._ms5607 = ms5607 self._smoothing = 1 self._reference = None self.temperature = None # degree Celsius self.pressure = None # hPa self.set_oversampling(oversampling) if address is not None: found = self._connect(address) else: found = self._connect(self.ADDRESS_77) if not found: error = self._error found = self._connect(self.ADDRESS_76) if not found and "not found" in self._error: self._error = error if not found: raise RuntimeError(self._error) def set_oversampling(self, value): # 256, 512, 1024, 2048 or 4096: higher = less noise, but slower if value not in _OSR: raise ValueError("oversampling must be 256, 512, 1024, 2048 or 4096") self._offset, self._wait = _OSR[value] def set_smoothing(self, level): # 1 = no smoothing, a bigger level gives a steadier but slower value self._smoothing = max(1, int(level)) def read(self): # take one reading, return (temperature in Celsius, pressure in hPa) d1 = self._convert(_CMD_CONVERT_D1) d2 = self._convert(_CMD_CONVERT_D2) temperature, pressure = self._calculate(d1, d2) if self._smoothing > 1 and self.pressure is not None: pressure = self.pressure + (pressure - self.pressure) / self._smoothing self.temperature = temperature self.pressure = pressure return self.temperature, self.pressure def temperature_f(self): return self.temperature * 1.8 + 32 def pressure_mmhg(self): return self.pressure * 0.7500617 def pressure_inhg(self): return self.pressure * 0.02953 def altitude(self, sea_level=STANDARD_SEA_LEVEL): # meters above sea level; sea_level = the present sea level pressure in hPa return self._altitude(self.pressure, sea_level) def sea_level_pressure(self, altitude): # sea level pressure in hPa, from the last reading and a known altitude in meters return self.pressure / pow(1 - altitude / 44330, 5.255) def zero_height(self, samples=20): # make the present height the zero point (the average of some readings) smoothing, self._smoothing = self._smoothing, 1 total = 0 try: for _ in range(samples): total += self.read()[1] finally: self._smoothing = smoothing self.pressure = self._reference = total / samples def height(self): # meters above (+) or below (-) the zero point if self._reference is None: self.zero_height() return self._altitude(self.pressure, self._reference) @staticmethod def _altitude(pressure, reference): # international barometric formula return 44330 * (1 - pow(pressure / reference, 0.190295)) def _connect(self, address): self.address = address try: self._command(_CMD_RESET) except OSError: self._error = "MS5611 not found, check the wiring" return False sleep_ms(10) # the sensor reloads its calibration data prom = [] for i in range(8): self._command(_CMD_READ_PROM + 2 * i) data = self._i2c.readfrom(address, 2) prom.append((data[0] << 8) | data[1]) # a BMP280 or BMP180 can have the same address, the check code tells them apart valid = _crc4(prom) == (prom[7] & 0x0F) for value in prom[1:7]: if value == 0 or value == 0xFFFF: valid = False if not valid: self._error = "The device at 0x{:02X} is not a working MS5611".format(address) return False self._c = prom return True def _command(self, command): self._i2c.writeto(self.address, bytes([command])) def _convert(self, command): self._command(command + self._offset) sleep_ms(self._wait) self._command(_CMD_READ_ADC) data = self._i2c.readfrom(self.address, 3) value = (data[0] << 16) | (data[1] << 8) | data[2] if value == 0: raise OSError("MS5611 gives no result") return value def _calculate(self, d1, d2): # the integer math of the datasheet, with second order temperature compensation c = self._c dt = d2 - (c[5] << 8) temp = 2000 + ((dt * c[6]) >> 23) if self._ms5607: off = (c[2] << 17) + ((c[4] * dt) >> 6) sens = (c[1] << 16) + ((c[3] * dt) >> 7) else: off = (c[2] << 16) + ((c[4] * dt) >> 7) sens = (c[1] << 15) + ((c[3] * dt) >> 8) if temp < 2000: # below 20 degree Celsius low = (temp - 2000) ** 2 if self._ms5607: off2 = (61 * low) >> 4 sens2 = 2 * low else: off2 = (5 * low) >> 1 sens2 = (5 * low) >> 2 if temp < -1500: # below -15 degree Celsius very_low = (temp + 1500) ** 2 if self._ms5607: off2 += 15 * very_low sens2 += 8 * very_low else: off2 += 7 * very_low sens2 += (11 * very_low) >> 1 temp -= (dt * dt) >> 31 off -= off2 sens -= sens2 p = ((d1 * sens) >> 21) - off return temp / 100, p / 32768 / 100

The scripts of this page find the driver only if it is on the ESP32 under the name DIYables_MicroPython_MS5611.py. The steps below show how.

ESP32 MicroPython Code - MS5611 Pressure Sensor

Before the diary starts, we check that the sensor works. The first script prints the pressure and the temperature every two seconds:

  • I2C(0, scl=Pin(22), sda=Pin(21)) opens the first I2C bus of the ESP32 on our two pins.
  • MS5611(i2c) tries both addresses, 0x77 first. The sensor has a check code (CRC) in its memory, and the driver reads it to be sure that the device is an MS5611. If not, the script stops with a RuntimeError and a clear text.
  • sensor.read() takes one reading, which needs about 22 ms. It returns the temperature in °C and the pressure in hPa.
  • If a wire comes loose later, read() raises an OSError. The script catches it, prints a message and tries again.
""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-ms5611-pressure-sensor """ from machine import I2C, Pin from DIYables_MicroPython_MS5611 import MS5611 import time SCL_PIN = 22 # ESP32 GPIO22 connected to the SCL pin of the MS5611 module SDA_PIN = 21 # ESP32 GPIO21 connected to the SDA pin of the MS5611 module i2c = I2C(0, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN)) # Looks for the sensor at 0x77 and 0x76. # Without a working MS5611, the script stops here with a RuntimeError that tells why. sensor = MS5611(i2c) print("MS5611 is ready at I2C address 0x{:02X}".format(sensor.address)) while True: try: temperature, pressure = sensor.read() # one reading, about 22 ms print("Pressure: {:.2f} hPa Chip temperature: {:.1f} °C".format(pressure, temperature)) except OSError: print("No answer from the MS5611, check the wires") time.sleep(2)

Detailed Instructions

Here's instructions on how to set up and run your MicroPython code on the ESP32 using Thonny IDE:

  • You need Thonny IDE on your computer and the MicroPython firmware on your ESP32. If one of them is missing, follow the ESP32 MicroPython Getting Started guide first.
  • Connect the four wires as in the table. Check once more that VCC is on 3.3V.
  • Connect the ESP32 to the computer with the USB cable and open Thonny.
  • Go to Tools Options, open the Interpreter tab and select MicroPython (ESP32). Select the port of your board too, if it is not selected yet.
  • Put the driver on the ESP32 first:
    • Click the New button of Thonny, and paste the driver code into the empty tab.
    • Press Ctrl+S and choose MicroPython device.
    • Type DIYables_MicroPython_MS5611.py as the file name. Big and small letters must be the same as here.
  • Open one more new tab, and paste the script above into it.
  • Save it on the board:
    • Press Ctrl+S, or click the Save button.
    • Choose MicroPython device.
    • Type main.py as the file name and click OK.
  • Press F5, or click the green Run button.
  • Let the module lie on the desk for some lines. Then hold it just above the floor, and then high above your head.
  • Read the lines in the Shell at the bottom of Thonny.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot MS5611 is ready at I2C address 0x77 Pressure: 1004.93 hPa Chip temperature: 24.2 °C Pressure: 1004.92 hPa Chip temperature: 24.2 °C Pressure: 1004.94 hPa Chip temperature: 24.2 °C Pressure: 1005.01 hPa Chip temperature: 24.3 °C Pressure: 1005.02 hPa Chip temperature: 24.3 °C Pressure: 1004.79 hPa Chip temperature: 24.3 °C Pressure: 1004.78 hPa Chip temperature: 24.4 °C
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

If you name your script main.py and save it to the MicroPython device, it will run automatically every time the ESP32 is powered on.

The desk gives about 1004.93 hPa, the floor about 1005.02 hPa and the raised hand about 1004.78 hPa. The hand is about 2 meters above the floor. The gap is 1005.02 - 1004.78 = 0.24 hPa, and 2 x 0.12 hPa is also 0.24 hPa.

The temperature comes from the chip, and the driver uses it for the pressure math. Your room can be 1 to 3°C cooler than this value, because the electronics make some heat. A DHT22 is better for the room, and it also gives the humidity.

ESP32 MicroPython Code - Lowest and Highest Pressure of the Day

Now we write the diary. The second script does the same work again and again:

  • It waits one second and takes a new reading.
  • It compares the pressure with lowest and highest. A lower value replaces lowest, and a higher value replaces highest. Both begin with None, so the very first reading goes into both.
  • After 10 readings, which is about 10 seconds, it prints one line: the present pressure, the lowest, the highest, and the difference between the last two.

When somebody closes a door fast, one reading can jump, and this value would stay in the diary until the evening. So we use sensor.set_smoothing(10). Each new reading then moves the pressure only by one tenth of the way. A jump of 0.5 hPa in a single reading becomes 0.05 hPa. A real change still comes through: after 30 readings, about 96% of it has arrived.

If a reading fails, the script prints a message, keeps both numbers and tries again one second later.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-ms5611-pressure-sensor """ from machine import I2C, Pin from DIYables_MicroPython_MS5611 import MS5611 import time SCL_PIN = 22 # ESP32 GPIO22 connected to the SCL pin of the MS5611 module SDA_PIN = 21 # ESP32 GPIO21 connected to the SDA pin of the MS5611 module READINGS_PER_LINE = 10 # one reading per second, so one line about every 10 seconds i2c = I2C(0, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN)) sensor = MS5611(i2c) # stops here with a RuntimeError if there is no working MS5611 sensor.set_smoothing(10) # a slammed door should not enter the diary lowest = None # lowest pressure since the start, in hPa highest = None # highest pressure since the start, in hPa count = 0 # readings since the last printed line print("The weather diary starts now") while True: time.sleep(1) try: sensor.read() except OSError: print("No answer from the MS5611, check the wires") continue # no new value, try again in one second pressure = sensor.pressure # The first reading is the lowest and the highest at the same time if lowest is None or pressure < lowest: lowest = pressure if highest is None or pressure > highest: highest = pressure count += 1 if count == READINGS_PER_LINE: count = 0 print("Now {:.2f} | Lowest {:.2f} | Highest {:.2f} | Difference {:.2f} hPa".format( pressure, lowest, highest, highest - lowest))

Detailed Instructions

  • The driver file is already on the ESP32, so leave it there as it is.
  • Copy the script above into the editor of Thonny.
  • Save it to the MicroPython device as main.py. It replaces the first script.
  • Put the module on the desk and run the script (F5).
  • After two lines, hold the module high above your head for 40 seconds. Then put it back.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot The weather diary starts now Now 1004.92 | Lowest 1004.91 | Highest 1004.92 | Difference 0.01 hPa Now 1004.92 | Lowest 1004.91 | Highest 1004.93 | Difference 0.02 hPa Now 1004.84 | Lowest 1004.84 | Highest 1004.93 | Difference 0.09 hPa Now 1004.80 | Lowest 1004.80 | Highest 1004.93 | Difference 0.13 hPa Now 1004.79 | Lowest 1004.79 | Highest 1004.93 | Difference 0.14 hPa Now 1004.78 | Lowest 1004.78 | Highest 1004.93 | Difference 0.15 hPa Now 1004.86 | Lowest 1004.78 | Highest 1004.93 | Difference 0.15 hPa Now 1004.90 | Lowest 1004.78 | Highest 1004.93 | Difference 0.15 hPa Now 1004.92 | Lowest 1004.78 | Highest 1004.93 | Difference 0.15 hPa
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

The hand was about 1.2 meters above the desk, so the pressure went down by about 0.14 hPa. Back on the desk, Now returns to 1004.92, but Lowest keeps 1004.78. This is the memory of the diary.

Our test is not weather, so clear it: press the EN (reset) button of the ESP32. The script starts again from main.py with two new numbers. Then leave the module where it is.

One Day in the Diary

Here is an example of a day with rain in the afternoon. We started the script at 7 am and looked at the Shell five times:

Time Now Lowest Highest Difference Sky
7 am 1004.86 1004.86 1004.87 0.01 sun
10 am 1005.91 1004.71 1005.93 1.22 sun
2 pm 1002.87 1002.86 1005.93 3.07 gray clouds
5 pm 999.52 999.41 1005.93 6.52 wind and rain
9 pm 1001.68 999.41 1005.93 6.52 dry again

What the Difference Tells You

You can read the difference of a whole day like this. It is a rough guide and not a forecast:

Difference in One Day What It Means
less than 2 hPa a calm day, the weather stays as it is
2 to 5 hPa a normal change, for example from sun to clouds
5 to 10 hPa the weather really changed, often with wind or rain
more than 10 hPa a very strong change, a storm can be near

The difference says how much the pressure changed, but not in which direction. For this, compare Now with the other two numbers:

  • Now is close to Lowest: the pressure is falling, or it is still low. Clouds, wind or rain are likely (2 pm and 5 pm in the example).
  • Now is close to Highest: the pressure went up, or it is still high. Fair weather is likely (10 am in the example).
  • Now is between them: look again half an hour later. If Now moves away from Lowest, the weather is getting better. At 9 pm, Now is already 2.27 hPa above Lowest, and the rain is over.

The difference also does not know the time. If the pressure loses 3 hPa or more in 3 hours, a strong weather change is on its way. In the example, it happened between 2 pm and 5 pm: 1002.87 - 999.52 = 3.35 hPa.

Do you live near the equator? There, the air makes two small pressure waves every day, even in fine weather, so a difference of 2 to 3 hPa is nothing special.

Use It Every Day

  • New day, new page: press EN in the morning. Both numbers live in the RAM of the ESP32, so a reset or a power cut also clears them.
  • Fewer lines: with READINGS_PER_LINE = 60, you get one line per minute.
  • Ask by hand: click into the Shell and press Ctrl+C. The script stops, but MicroPython still knows the numbers. Type lowest, highest or round(highest - lowest, 2) and press Enter. To begin a new diary, press F5.
  • Power: a sleeping computer can switch off its USB port, so turn off the sleep mode for a long test.

Sea-Level Pressure and Altitude

A weather map does not show the pressure in your room. Its numbers are converted to sea level, for towns in the valley and in the mountains alike. With the height of your home, the driver does the same, and it can also give the height. Put one of these calls into a print() after sensor.read(). The results are for the last reading of our day, 1001.68 hPa, and a home 72 meters above the sea:

Call Result Meaning
sensor.sea_level_pressure(72) 1010.27 hPa the number for the weather map
sensor.altitude(1010.27) 72.0 m the height, with the present sea-level pressure
sensor.altitude() 96.8 m the height, with the standard 1013.25 hPa

Both heights come from the same reading. Only the sea-level pressure is different. It changes every day, and 1 hPa of error makes the height wrong by about 8.3 meters. So use the present value of your area (called QNH) from a weather website or an airport report. For other units, there are sensor.pressure_mmhg() and sensor.pressure_inhg().

Troubleshooting

  • ImportError, no module named 'DIYables_MicroPython_MS5611': The driver file is not on the ESP32, or its name has a typing mistake. Open the list of files with View Files in Thonny, and look for DIYables_MicroPython_MS5611.py under MicroPython device.
  • MS5611 not found, check the wiring: Nothing answers at 0x77 or 0x76. Type i2c.scan() in the Shell. An empty list [] means that the wiring is wrong: check VCC and GND first, then SCL on GPIO22 and SDA on GPIO21. With a working module, the list has the number 119 (0x77) or 118 (0x76).
  • The device at 0x77 is not a working MS5611: Another sensor is on the bus. A BMP280 or BME280 uses 0x76 or 0x77, and a BMP180 uses 0x77. Remove it, or move the MS5611 to the other address with CSB.
  • About 500 hPa, half of the real pressure: Your module carries an MS5607 chip. Write sensor = MS5611(i2c, ms5607=True) in both scripts.
  • A large difference on a calm day: Somebody moved the module, the sun or the wind reached it, or a wire was loose for a moment. Find a quiet place, add the foam, and press EN to start again.

Project Ideas

  • A diary with a screen: show Now, Lowest, Highest and the difference in four lines on an OLED 128x64. It also runs from 3.3V and can share GPIO21 and GPIO22 with the MS5611, because its I2C address is different (0x3C).
  • A rain column: add a rain sensor and note the pressure when the first drops fall.
  • A diary for the whole year: at midnight, write the two numbers with the date to an SD card and start again.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!