指间ESP姿态传感器操作
502748957@qq.com(讨论 | 贡献)2019年7月25日 (四) 07:52的版本
指间ESP姿态传感器操作
import machine, display
from machine import Pin, I2C
import mpu6050
i2c = I2C(scl=Pin(21), sda=Pin(22))
accelerometer = mpu6050.MPU6050(i2c)
bkcolor = 0x333333
tft = display.TFT()
tft.init(tft.ST7789)
tft.clear()
tft.rect(0, 0, 240, 240, bkcolor, bkcolor)
def mapTo(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
_X = 0
_Y = 0
while True:
tft.text(80, 15, "mpu6050", 0x0FF00F, transparent=True)
AcData = accelerometer.get_values()
pointX = int(AcData["AcX"] / 1638)
pointY = int(AcData["AcY"] / 1638)
if _X != pointX:
tft.circle(120 + 3 * _X, 60 + 3 * _Y, 9, bkcolor, bkcolor)
_X = pointX
if _Y != pointY:
tft.circle(120 + 3 * _X, 60 + 3 * _Y, 9, bkcolor, bkcolor)
_Y = pointY
print(_X, " ", _Y)
tft.circle(120 + 3 * pointX, 60 + 3 * pointY, 8, 0xFFFFFF, 0xF00000)
程序详解:
import machine, display
from machine import Pin, I2C
import mpu6050
之后声明I2C设备,并命名为accelerometer。声明XY坐标使用的参数 i2c = I2C(scl=Pin(21), sda=Pin(22))
accelerometer = mpu6050.MPU6050(i2c)
_X = 0
_Y = 0
初始化TFT并使用背景色"bkcolor"填充屏幕 bkcolor = 0x333333
tft = display.TFT()
tft.init(tft.ST7789)
tft.clear()
tft.rect(0, 0, 240, 240, bkcolor, bkcolor)
自制map函数,用于将ADC值映射到绘制图形的尺寸上 def mapTo(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
获取6050数据并做数据处理。数据有变化则根据数据重新绘制姿态球位置。 AcData = accelerometer.get_values()
pointX = int(AcData["AcX"] / 1638)
pointY = int(AcData["AcY"] / 1638)
if _X != pointX:
tft.circle(120 + 3 * _X, 60 + 3 * _Y, 9, bkcolor, bkcolor)
_X = pointX
if _Y != pointY:
tft.circle(120 + 3 * _X, 60 + 3 * _Y, 9, bkcolor, bkcolor)
_Y = pointY
覆盖变化前的姿态球 tft.circle(120 + 3 * pointX, 60 + 3 * pointY, 8, 0xFFFFFF, 0xF00000)
|