Written with ChatGPT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import smbus import time # Define the I2C address of the accelerometer ACCEL_ADDR = 0x4c # Initialize the I2C bus bus = smbus.SMBus(1) # Start measurement bus.write_byte_data(ACCEL_ADDR, 0x07, 0x01) while True: # Read the acceleration values for each axis try: accel_x = bus.read_byte_data(ACCEL_ADDR, 0x00) accel_y = bus.read_byte_data(ACCEL_ADDR, 0x01) accel_z = bus.read_byte_data(ACCEL_ADDR, 0x02) except OSError as e: print(“Error reading accelerometer data: {}”.format(e)) accel_x, accel_y, accel_z = 0, 0, 0 # Convert the raw values to G-forces accel_x_g = (accel_x & 0x3F) * 0.047 # 47 mg/LSB if (accel_x & 0x40): accel_x_g -= 2.048 # 2 g offset accel_y_g = (accel_y & 0x3F) * 0.047 if (accel_y & 0x40): accel_y_g -= 2.048 accel_z_g = (accel_z & 0x3F) * 0.047 if (accel_z & 0x40): accel_z_g -= 2.048 # Print the acceleration values print(“Acceleration (g): X={:.2f}, Y={:.2f}, Z={:.2f}”.format(accel_x_g, accel_y_g, accel_z_g)) # Wait for 1 second time.sleep(1) |
Leave a Reply