kregus
kregus

Reputation: 1108

How to read from an I2C pressure sensor on Raspberry Pi using Python

For my current project I've attached a MEAS M32JM pressure & temperature sensor to my Pi, but I've been unable to read the sensor values using its I2C protocol.

Here is the sensor's datasheet: https://eu.mouser.com/datasheet/2/418/8/ENG_DS_M3200_A19-1958281.pdf

NOTE: check out the C example code at the end of the datasheet

The datasheet mentions:

The I2C address consists of a 7-digit binary value. The factory setting for the I2C slave address is 0x28. The address is always followed by a write bit (0) or read bit (1). The default hexadecimal I2C header for read access to the sensor is therefore 0x51.

This is what I tried:

import smbus
import time

bus = smbus.SMBus(1)
address = 0x28
read_header = 0x51

bus.write_byte_data(address, read_header, 0x01)  # Start reading: 0 = WRITE, 1 = READ

time.sleep(0.7)

for i in range(8):
    print(bus.read_byte_data(address, i))

However, all the prints return 0.

The datasheet also mentions that after sending the read bit, we have to wait for an acknowledge bit, but how would I receive and process that bit?

Never worked with I2C or bitwise operations before, so any help with how I can read data from this sensor would be greatly appreciated!

Upvotes: 2

Views: 1703

Answers (1)

kregus
kregus

Reputation: 1108

Managed to solve it using pigpio instead of smbus.

I installed it on the Pi using:

apt install pigpio
apt-get install python-pigpio python3-pigpio

Then I used the following Python script to read the sensor data:

import pigpio

SENSOR_ADDRESS = 0x28  # 7 bit address 0101000-, check datasheet or run `sudo i2cdetect -y 1`
BUS = 1

pi = pigpio.pi()

handle = pi.i2c_open(BUS, SENSOR_ADDRESS)

# Attempt to write to the sensor, catch exceptions
try:
  pi.i2c_write_quick(handle, 1)  # Send READ_MR command to start measurement and DSP calculation cycle
except:
  print("Error writing to the sensor, perhaps none is connected to bus %s" % bus, file=sys.stderr)
  pi.stop()
  return None

time.sleep(2 / 1000)  # Give the sensor some time

count, data = pi.i2c_read_device(handle, 4)  # Send READ_DF4 command, to fetch 2 pressure bytes & 2 temperature bytes

pi.i2c_close(handle)
pi.stop()

print("count = ", count)
print("data = ", data)

Click here to see the full script.

Upvotes: 1

Related Questions