Accelerometer#

Initializing the Accelerometer Class#

An Accelerometer is created by using the following constructor:

Accelerometer(port, sensitivity)

This constructor uses two parameters:

Parameter

Description

port

The 3-Wire Port that the Accelerometer is connected to, whether it’s a port on the Brain, or a 3-Wire Expander.

sensitivity

Optional. Enables high sensitivity mode (+/- 2g) on the Accelerometer. True to enable high sensitivity. The default sensitivity is (+/- 6g).

A Brain or 3-Wire Expander must be created first before they can be used to create an object with the Accelerometer Class constructor.

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

This accel object will be used in all subsequent examples throughout this API documentation when referring to Accelerometer class methods.

For optimal functionality, it is recommended to use separate Accelerometers for each axis, initializing them individually:

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

Class Methods#

acceleration()#

The acceleration() method reads the value of the Accelerometer scaled to units of gravity.

Returns: A value in the range +/- 6G, or +/-2G if high sensitivity mode is set.

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

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

changed()#

The changed(callback, arg) method registers a function to be called when the value of the accelerometer changes.

Parameters

Description

callback

A function that will be called when the axis value changes.

arg

Optional. A tuple that is used to pass arguments to the callback function.

Returns: An instance of the Event class.

# 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)