指间ESP姿态传感器操作

来自Microduino Wikipedia
跳转至: 导航搜索

指间ESP姿态传感器操作


指间ESP开发板板载了MPU6050传感器,本示例在屏幕上绘制了体感球,基于MPU6050传感器获得的数据向四个方向运动。

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)
    • 该程序使用板载TFT屏幕画出一个红色实心姿态球,根据手持开发板的前倾后倾左倾右倾来改变姿态球位置。
Tftmotion.png

程序详解:
import为引用所需文件,包括display(屏幕驱动),Pin(IO口驱动)、I2C驱动、并引用mpu6050库

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)




返回指间ESP开发板编程手册界面