加速度计#

初始化加速度计类#

使用以下构造函数创建加速度计:

加速度计(端口,灵敏度)

此构造函数使用两个参数:

范围

描述

端口

加速度计连接到的 3 线端口,无论它是 大脑 上的端口,还是 3 线扩展器 上的端口。

敏感性

**可选。**启用加速度计的高灵敏度模式 (+/- 2g)。设置为“True”表示启用高灵敏度。默认灵敏度为 (+/- 6g)。

必须先创建 Brain3-Wire Expander,然后才能使用加速度计类构造函数创建对象。

# Create the Brain.
brain = Brain()
# Construct an Accelerometer "accel" with the
# Accelerometer class.
accel = Accelerometer(brain.three_wire_port.a)

当引用加速度计类方法时,此“accel”对象将在整个 API 文档的所有后续示例中使用。

为了获得最佳功能,建议为每个轴使用单独的加速度计,并单独初始化它们:

accel_x = Accelerometer(brain.three_wire_port.a)
accel_y = Accelerometer(brain.three_wire_port.b)
accel_z = Accelerometer(brain.three_wire_port.c)

类方法#

acceleration()#

acceleration() 方法读取加速度计按重力单位缩放的值。

返回: 范围内的值 +/- 6G,如果设置了高灵敏度模式,则为 +/-2G。

# Drive the robot forward.
drivetrain.drive(FORWARD)

# Get the Accelerometer's acceleration.
value = accel.acceleration()

changed()#

changed(callback, arg) 方法注册一个函数,当加速度计的值发生变化时调用该函数。

参数

描述

打回来

当轴值改变时调用的函数。

arg

**可选。**用于向回调函数传递参数的元组。

**返回:**事件类的一个实例。

# Drive the robot forward.
drivetrain.drive(FORWARD)

# Define the function accelerometer_changed.
def accelerometer_changed():
    # The Brain will print that the Accelerometer's value 
    # changed on the Brain's screen.
    brain.screen.print("accelerometer changed")
    
# Run accelerometer_changed when the value of the 
# Accelerometer changes.
accel.changed(accelerometer_changed)