from imu import MPU6050
from time import sleep
from machine import Pin, I2C
# Initialize I2C and PUG@Se
i2c = I2C(1, sda=Pin(2), scl=Pin(3), freq=400000)
imu = MPU6050(i2c)
try:
# Open or create a file for writing data
file = open("data.txt", "a") # "a" to append, "w" to overwrite
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, 2)
gy = round(imu.gyro.y, 2)
gz = round(imu.gyro.z, 2)
temp = round(imu.temperature, 2)
# Print data to console
print("ax:", ax, "\tay:", ay, "\taz:", az, "\tgx:", gx, "\tgy:", gy, "\tgz:", gz, "\tTemperature:", temp)
# Write data to file
file.write(str(count) + "," + str(ax) + "," + str(ay) + "," + str(az) + "," + str(gx) + "," + str(gy) + "," + str(gz) + "," + str(temp) + "\n")
file.flush()
count += 1
# Wait for 1 second
sleep(1)