from imu import MPU6050
from time import sleep
from machine import Pin, I2C
# Initialize I2C and MPU6050
i2c = I2C(1, sda=Pin(2), scl=Pin(3), freq=400000) # Pico
imu = MPU6050(i2c)
try:
# Open or create a file for writing data
file = open("data.txt", "a") # "w" to overwrite, "a" to append
except OSError:
# If file opening fails, create a new file
file = open("data.txt", "w") # "w" to overwrite, "a" to append
count = 0
while True:
# Read accelerometer, gyroscope, and temperature data
ax = round(imu.accel.x, 2)
ay = round(imu.accel.y, 2)
az = round(imu.accel.z, 2)
gx = round(imu.gyro.x)
gy = round(imu.gyro.y)
gz = round(imu.gyro.z)
tem = round(imu.temperature, 2)
# Print data to console
print("ax", ax, "\tay", ay, "\taz", az, "\tgx", gx, "\tgy", gy, "\tgz", gz, "\tTemperature", tem)
# Write data into file
file.write(str(count) + "," + str(ax) + "," + str(ay) + "," + str(az) + "," + str(gx) + "," + str(gy) + "," + str(gz) + "," + str(tem) + "\n")
file.flush()
count += 1
# Wait for 1 second
sleep(1)