【Micropython】ESP8266驱动mpu6050读取数据
-
📌相关篇《【MicroPython ESP32】ssd1306驱动0.96“I2C屏幕+mpu6050图形控制》
-
✨本案例基于Thonny平台开发。✨
-
🔖esp8266固件版本:
MicroPython v1.19.1 on 2022-06-18
-
📍本篇需要使用的加载的mpu6050模块库(无法在Thonny里面下载到):
https://github.com/narutogo/micropython-mpu6050-
-
🎈与之相关的库(兼容ESP32):
https://github.com/Lezgend/MPU6050-MicroPython
🛠将库下载下来后,将模块导入进去
📝示例程序一
- ✨主程序通过库所提供的测试代码上添加了温度数据打印。
from machine import I2C, Pin
import q4
import time,math
import mpu
import mpu6050
i2c = I2C(scl=Pin(5), sda=Pin(4))
acc = mpu6050.accel(i2c)
acc.error_gy()
#ay=acc.get_values()
#mpu.one_filter(ay["AcX"],ay["AcY"],ay["AcZ"],ay["GyX"],ay["GyY"],ay["GyZ"])
i=0
gyx=0
gyy=0
r=[]
q=[]
while 1:
ay=acc.get_values()
i=i+1
if i==124:
#print(r)
print(q)
i=0
#print(ay["AcX"],ay["AcY"],ay["AcZ"],ay["GyX"],ay["GyY"],ay["GyZ"])
#r=mpu.one_filter(ay["AcX"],ay["AcY"],ay["AcZ"],ay["GyX"],ay["GyY"],ay["GyZ"])
q=q4.IMUupdate(ay["GyX"]/65.5*0.0174533,ay["GyY"]/65.5*0.0174533,ay["GyZ"]/65.5*0.0174533,ay["AcX"]/8192,ay["AcY"]/8192,ay["AcZ"]/8192)
Temp = ay["Tmp"]
print("Temp:",Temp,"°C",q)
time.sleep(1)
- 📋输出打印信息:
📖示例程序二
- 🔖此库可以将数据保存到
.txt
中
# Example code for (GY-521) MPU6050 Accelerometer/Gyro Module
# Write in MicroPython by Warayut Poomiwatracanont JAN 2023
from MPU6050 import MPU6050
from os import listdir, chdir
from machine import Pin
from time import sleep_ms
mpu = MPU6050()
# List all files directory.
print("Root directory: {} \n".format(listdir()))
# Change filename and fileformat here.
filename = "{}%s.{}".format("data_logs", "txt")
# Increment the filename number if the file already exists.
i = 0
while (filename % i) in listdir():
i += 1
# Save file in path /
with open(filename % i, "w") as f:
cols = ["Temp", "AcX", "AcY", "AcZ"]
f.write(",".join(cols) + "\n")
while True:
# Accelerometer Data
accel = mpu.read_accel_data() # read the accelerometer [ms^-2]
aX = accel["x"]
aY = accel["y"]
aZ = accel["z"]
print("x: " + str(aX) + " y: " + str(aY) + " z: " + str(aZ))
# Gyroscope Data
# gyro = mpu.read_gyro_data() # read the gyro [deg/s]
# gX = gyro["x"]
# gY = gyro["y"]
# gZ = gyro["z"]
# print("x:" + str(gX) + " y:" + str(gY) + " z:" + str(gZ))
# Rough Temperature
temp = mpu.read_temperature() # read the device temperature [degC]
# print("Temperature: " + str(temp) + "°C")
# G-Force
# gforce = mpu.read_accel_abs(g=True) # read the absolute acceleration magnitude
# print("G-Force: " + str(gforce))
# Write to file
data = {"Temp" : temp,
"AcX" : aX,
"AcY" : aY,
"AcZ" : aZ
}
push = [ str(data[k]) for k in cols ]
row = ",".join(push)
f.write(row + "\n")
# Time Interval Delay in millisecond (ms)
sleep_ms(100)
- 📜打印调试信息: