I have been learning python on and off for a while and have started tinkering with a Raspberry Pi and peripherals. I'm trying to communicated with a SPI pressure sensor and am getting readings but unable to get positive pressure readings from the senor, it reached 0 Pa and won't go any higher. Per the user manual I am to send the sensor 3 bytes to engage it and then 16 clock pulses for the returning reading. The returning bytes are then converted to either positive or negative values based on two's compliment and that value is divided by 1200 to convert the pressure to Pa. For some reason I can't figure out the pressure reading will only return negative readings. When the pressure should be positive it will read at maximum zero though the sensor seems to read correctly in the negative direction. I feel like this code should work but it's not checking out. I'm wondering if there is something obvious I'm missing with regards to the SPI communication in the code. Is there something obvious I'm ignorant about?
Code:
import spidevimport time# SPI setupspi = spidev.SpiDev() # Initialize SPIspi.open(0, 0) # Open SPI bus 0, device 0spi.max_speed_hz = 500000 # Set SPI speed to 500 kHzspi.mode = 0b00 # Set SPI mode to 0 (CPOL=0, CPHA=0)# Helper function to handle signed 16-bit two's complement datadef convert_to_signed(value, bits): """Convert unsigned integer to signed integer (two's complement).""" if value & (1 << (bits - 1)): # If the sign bit is set (MSB is 1) value -= 1 << bits # Subtract 2^16 to get the negative value return valuedef read_pressure(): """Reads the pressure from the sensor.""" # Step 1: Poll current pressure measurement (0x2D) spi.xfer2([0x2D]) time.sleep(0.01) # Step 2: Send result to data register (0x14) spi.xfer2([0x14]) time.sleep(0.01) # Step 3: Read data register (0x98) spi.xfer2([0x98]) time.sleep(0.01) # Read 16-bit pressure data (MSB first) response = spi.xfer2([0x00, 0x00]) # Send dummy data to clock out response raw_value = (response[0] << 8) | response[1] # Convert to signed 16-bit value using two's complement conversion pressure_counts = convert_to_signed(raw_value, 16) # Scale factor for ±25 Pa bidirectional sensor is 1200 counts/Pa scale_factor = 1200 # Calculate pressure in Pascals (Pa) pressure_pa = pressure_counts / scale_factor return pressure_patry: while True: pressure = read_pressure() print(f"Pressure: {pressure:.2f} Pa") time.sleep(1) # Delay before reading again, 1 secondexcept KeyboardInterrupt: print("\nExiting...") spi.close() # Clean up the SPI connection when done
Statistics: Posted by EatDemCashews — Fri Oct 11, 2024 7:41 pm — Replies 3 — Views 44