Okay so im back, so I've tested the sensor on an Arduino, and it works with the sample code that's provided in the wiki. However I've tried and attempted to use the code to interface with the Raspberry. Im not quite show whats wrong with the code.
Code:
import smbus2import timeimport matplotlib.pyplot as pltimport numpy as npSENSOR_ADDRESS = 0x00 # I2C address of the sensorCONVERSION_FACTOR = 500.0 / 32767.0 # Conversion factor for pressureTEMPERATURE_CONVERSION_FACTOR = 1.0 # Assuming direct reading in Celsiusdef read_sensor(bus): try: bus.write_byte(SENSOR_ADDRESS, 0x01) time.sleep(0.05) # Short delay to allow for data processing data = bus.read_i2c_block_data(SENSOR_ADDRESS, 0, 6) pressure_raw = data[0] << 16 | data[1] << 8 | data[2] if pressure_raw & 0x800000: # handling two's complement pressure_raw -= 0x1000000 pressure = pressure_raw * CONVERSION_FACTOR temperature_raw = data[3] << 16 | data[4] << 8 | data[5] if temperature_raw & 0x800000: # handling two's complement temperature_raw -= 0x1000000 temperature = temperature_raw * TEMPERATURE_CONVERSION_FACTOR return pressure, temperature except IOError: # Handle error (e.g., sensor not connected) return None,None# Function to convert pressure to velocity (based on Bernoulli's principle)def pressure_to_velocity(pressure): # Assuming air density at sea level (~1.225 kg/m^3) air_density = 1.225 # Velocity calculation from differential pressure velocity = np.sqrt(2 * abs(pressure) / air_density) return velocitybus = smbus2.SMBus(1)# Collect datapressure_data = []velocity_data = []temperature_data = []time_data = []start_time = time.time()try: while True: current_time = time.time() - start_time pressure, temperature = read_sensor(bus) if pressure is not None and temperature is not None: velocity = pressure_to_velocity(pressure) pressure_data.append(pressure) velocity_data.append(velocity) temperature_data.append(temperature) time_data.append(current_time) # Print the latest readings print(f"Time: {current_time:.2f} s, Pressure: {pressure:.2f} Pa, Velocity: {velocity:.2f} m/s, Temperature: {temperature:.2f} °C") time.sleep(1) # Adjust the delay as neededexcept KeyboardInterrupt: # Create a subplot with 2 side-by-side graphs fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) # Velocity-Time Graph ax1.plot(time_data, velocity_data, label='Velocity', color='blue') ax1.set_title('Velocity-Time Graph') ax1.set_xlabel('Time (s)') ax1.set_ylabel('Velocity (m/s)') ax1.legend() ax1.grid(True) # Pressure-Time Graph ax2.plot(time_data, pressure_data, label='Pressure', color='green') ax2.set_title('Pressure-Time Graph') ax2.set_xlabel('Time (s)') ax2.set_ylabel('Pressure (Pa)') ax2.legend() ax2.grid(True) plt.tight_layout() plt.show()
Statistics: Posted by Rlow1937 — Sun Feb 04, 2024 7:07 am