Mircopython: 在BPIbit上检测板子的姿态


Document

17025158-7f2b76c6a8fcf042.gif

板子姿态检测

  • 这个模块可以让你获得板子当前的九轴姿态,分别是加速度、重力、磁感应的(X\Y\Z)方向状态值

  • 最基本的功能是获取它们当前的 X、Y、Z 三轴的值来判断板子此时的运动状态,比如说,加速度 Z 值由小增大,表示 Z 轴方向上有在移动(有了加速度),所以可以判断出板子在移动,移动的方向在 Z 轴之上

基础运用

  • 经过了简单的介绍,可以设计一个简单的判断,例如 获取板子的平衡情况,以 accelerometer 加速度模块为例,获取它的 X 轴的值,即可得到一个基本的数值,如果数值大于 20 说明它向右偏了,如果小于 - 20 则说明它向左偏了,如果在 这两者之间,则说明它是平衡的,所以有如下的代码,显示 L 表示向左偏,而显示 R 表示板子向右偏了
from microbit import *

while True:
    reading = accelerometer.get_x()
    if reading > 20:
        display.show("R")
    elif reading < -20:
        display.show("L")
    else:
        display.show("-")

实测效果

17025158-f9520089f17597b2.gif

趣味游戏

  • 基于先前的基础运用,可以做出一个趣味游戏,控制一颗球的移动
import utime
from random import randint
from machine import I2C, Pin
from mpu9250 import MPU9250

i2c = I2C(scl=Pin(22), sda=Pin(21), freq=200000)
sensor = MPU9250(i2c)
print("MPU9250 id: " + hex(sensor.whoami))
from display import Pixel, PixelPower

PixelPower(True)
View = Pixel()
X, Y, Color, Flag = 2, 2, 2, 0
while True:
    # print('acceleration:', sensor.acceleration)
    # print('gyro:', sensor.gyro)
    # print('magnetic:', sensor.magnetic)
    A = sensor.acceleration  # -1 and -2 Software correction
    View.LoadXY(X, Y, (0, 0, 0), False)
    if (A[1] > -1 and A[1] > X and X < View.Max - 1):
        X = X + 1
    elif (A[1] < -1 and A[1] < X and X > View.Min):
        X = X - 1
    if (A[0] > -2 and A[0] > Y and Y > View.Min):
        Y = Y - 1
    elif (A[0] < -2 and A[0] < Y and Y < View.Max - 1):
        Y = Y + 1

    Color = Color + Flag
    if (Color == 10):
        Flag = -2
    elif (Color == 2):
        Flag = +2

    View.LoadXY(X, Y, (0, Color, Color), False)
    View.Show()
    utime.sleep_ms(100)
17025158-a346083ed0292e6f.gif

写在最后的话

有了这个传感器,可以做到许多需要基本姿态检测的功能,它是一个很有拓展性的功能模块


17025158-b37f40b064145dd4.png
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值