電路圖
程式列表
Python - mpu6050.py
# Simple library for ePy-Lite on ESP8266 with micropython
# Reference: https://github.com/adamjezek98/MPU6050-ESP8266-MicroPython
import machine
class accel():
def __init__(self, i2c, addr=0x68):
self.iic = i2c
self.addr = addr
self.iic.send(bytearray([107, 0]),self.addr)
def get_raw_values(self):
a = bytearray(14)
self.iic.send(bytearray([0x3B]),self.addr)
self.iic.recv(a,self.addr)
return a
def get_ints(self):
b = self.get_raw_values()
c = []
for i in b:
c.append(i)
return c
def bytes_toint(self, firstbyte, secondbyte):
if not firstbyte & 0x80:
return firstbyte << 8 | secondbyte
return - (((firstbyte ^ 255) << 8) | (secondbyte ^ 255) + 1)
def get_values(self):
raw_ints = self.get_raw_values()
vals = {}
vals["AcX"] = self.bytes_toint(raw_ints[0], raw_ints[1])
vals["AcY"] = self.bytes_toint(raw_ints[2], raw_ints[3])
vals["AcZ"] = self.bytes_toint(raw_ints[4], raw_ints[5])
vals["Tmp"] = self.bytes_toint(raw_ints[6], raw_ints[7]) / 340.00 + 36.53
vals["GyX"] = self.bytes_toint(raw_ints[8], raw_ints[9])
vals["GyY"] = self.bytes_toint(raw_ints[10], raw_ints[11])
vals["GyZ"] = self.bytes_toint(raw_ints[12], raw_ints[13])
return vals # returned in range of Int16
# -32768 to 32767
def val_test(self): # ONLY FOR TESTING! Also, fast reading sometimes crashes IIC
from time import sleep
while 1:
print(self.get_values())
sleep(0.05)
Python - ePy-Lite_MPU6050.py
"""
MPU6050
ePy-Lite MPU6050
-----------------
3V3 Pin1 VCC
GND Pin2 GND
P18_SDA0 Pin3 SDA
P17_SCL0 Pin4 SCL
Pin5 XDA
Pin6 XCL
Pin7 AD0
Pin8 INT
"""
from machine import I2C,LED
from machine import Switch #Get button KEY library
from utime import sleep
import mpu6050
# Start Function
if __name__ == '__main__':
KeyA = Switch('keya') #Create button A
led = LED('ledy')
led.off()
sensor_i2c = I2C(0,I2C.MASTER,baudrate=100000) #Create I2C0 Master Mode, Baudrate=100kHz
accelerometer = mpu6050.accel(sensor_i2c)
while True:
led.on()
sensor_values = accelerometer.get_values()
print(sensor_values)
led.off()
if KeyA.value() == True: #Press A Key
break
sleep(1)
sensor_i2c.deinit()
執行結果