venice

Venice is an open-source Micropython runtime for VEX V5 robots.

from venice import *

async def main():
    my_motor = Motor(
        1,
        Direction.FORWARD,
        Gearset.GREEN
    )
    my_motor.set_voltage(10.0)

    while True:
        await vasyncio.Sleep(10, TimeUnit.MILLIS)

vasyncio.run(main())
class

AdiAccelerometer

class AdiAccelerometer
function

__init__

__init__(self, port: str | AdiExpanderPort, sensitivity: AdiAccelerometerSensitivity) -> None
function

get_acceleration

get_acceleration(self) -> float
function

raw_acceleration

raw_acceleration(self) -> int
attribute

max_acceleration

max_acceleration: float
attribute

sensitivity

sensitivity: AdiAccelerometerSensitivity
class

AdiAccelerometerSensitivity

class AdiAccelerometerSensitivity
attribute

HIGH

HIGH: AdiAccelerometerSensitivity
attribute

LOW

LOW: AdiAccelerometerSensitivity
class

AdiAddrLed

class AdiAddrLed
function

__init__

__init__(self, port: str | AdiExpanderPort, count: int) -> None
function

set_all

set_all(self, color: Color) -> None
function

set_buffer

set_buffer(self, buffer: Any) -> int
function

set_pixel

set_pixel(self, index: int, color: Color) -> None
class

AdiAnalogIn

class AdiAnalogIn
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

get_value

get_value(self) -> int
function

get_voltage

get_voltage(self) -> float
attribute

ADC_MAX_VALUE

ADC_MAX_VALUE: int
class

AdiDigitalIn

class AdiDigitalIn
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

get_value

get_value(self) -> bool
function

is_high

is_high(self) -> bool
function

is_low

is_low(self) -> bool
class

AdiDigitalOut

class AdiDigitalOut
function

__init__

__init__(self, port: str | AdiExpanderPort, initial_level: bool | None = None) -> None
function

get_value

get_value(self) -> bool
function

set_high

set_high(self) -> None
function

set_low

set_low(self) -> None
function

set_value

set_value(self, value: bool) -> None
function

toggle

toggle(self) -> None
class

AdiEncoder

class AdiEncoder
function

__init__

__init__(self, top_port: str | AdiExpanderPort, bottom_port: str | AdiExpanderPort, tpr: int = 360) -> None
function

get_position

get_position(self, unit: RotationUnit) -> float
function

reset_position

reset_position(self) -> None
function

set_position

set_position(self, position: float, unit: RotationUnit) -> None
class

AdiExpander

class AdiExpander
function

__init__

__init__(self, port: int) -> None
attribute

a

a: AdiExpanderPort
attribute

b

b: AdiExpanderPort
attribute

c

c: AdiExpanderPort
attribute

d

d: AdiExpanderPort
attribute

e

e: AdiExpanderPort
attribute

f

f: AdiExpanderPort
attribute

g

g: AdiExpanderPort
attribute

h

h: AdiExpanderPort
class

AdiExpanderPort

class AdiExpanderPort
class

AdiGyroscope

class AdiGyroscope
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

calibrate

calibrate(self, duration: float, unit: TimeUnit) -> AdiGyroscopeFuture
function

get_yaw

get_yaw(self, unit: RotationUnit) -> float
function

is_calibrating

is_calibrating(self) -> bool
class

AdiGyroscopeFuture

class AdiGyroscopeFuture
class

AdiLightSensor

class AdiLightSensor
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

get_brightness

get_brightness(self) -> float
function

get_raw_brightness

get_raw_brightness(self) -> int
class

AdiLineTracker

class AdiLineTracker
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

get_raw_reflectivity

get_raw_reflectivity(self) -> int
function

get_reflectivity

get_reflectivity(self) -> float
class

AdiMotor

class AdiMotor
function

__init__

__init__(self, port: str | AdiExpanderPort, slew: float) -> None
function

get_output

get_output(self) -> float
function

get_raw_output

get_raw_output(self) -> int
function

set_output

set_output(self, value: float) -> None
function

set_raw_output

set_raw_output(self, pwm: int) -> None
function

stop

stop(self) -> None
class

AdiPotentiometer

class AdiPotentiometer
function

__init__

__init__(self, port: str | AdiExpanderPort, potentiometer_type: PotentiometerType) -> None
function

get_angle

get_angle(self, unit: RotationUnit) -> float
function

get_max_angle

get_max_angle(self, unit: RotationUnit) -> float
attribute

type

type: PotentiometerType
class

AdiPwmOut

class AdiPwmOut
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

set_output

set_output(self, value: int) -> None
class

AdiRangeFinder

class AdiRangeFinder
function

__init__

__init__(self, input_port: str | AdiExpanderPort, output_port: str | AdiExpanderPort) -> None
function

get_distance

get_distance(self) -> int | None
class

AdiServo

class AdiServo
function

__init__

__init__(self, port: str | AdiExpanderPort) -> None
function

set_raw_target

set_raw_target(self, pwm: int) -> None
function

set_target

set_target(self, position: float, unit: RotationUnit) -> None
attribute

MAX_POSITION_DEG

MAX_POSITION_DEG: float
attribute

MIN_POSITION_DEG

MIN_POSITION_DEG: float
class

AiVisionAprilTagObject

class AiVisionAprilTagObject
attribute

bottom_left_x

bottom_left_x: int
attribute

bottom_left_y

bottom_left_y: int
attribute

bottom_right_x

bottom_right_x: int
attribute

bottom_right_y

bottom_right_y: int
attribute

id

id: int
attribute

top_left_x

top_left_x: int
attribute

top_left_y

top_left_y: int
attribute

top_right_x

top_right_x: int
attribute

top_right_y

top_right_y: int
class

AiVisionCodeObject

class AiVisionCodeObject
function

get_angle

get_angle(self, unit: RotationUnit) -> float
attribute

height

height: int
attribute

id

id: int
attribute

width

width: int
attribute

x

x: int
attribute

y

y: int
class

AiVisionColor

class AiVisionColor
function

__init__

__init__(self, rgb: Color, hue_range: float, saturation_range: float) -> None
attribute

b

b: int
attribute

g

g: int
attribute

hue_range

hue_range: float
attribute

r

r: int
attribute

saturation_range

saturation_range: float
class

AiVisionColorCode

class AiVisionColorCode
function

__init__

__init__(self, color1: int, color2: int | None = None, color3: int | None = None, color4: int | None = None, color5: int | None = None, color6: int | None = None, color7: int | None = None) -> None
class

AiVisionColorObject

class AiVisionColorObject
attribute

height

height: int
attribute

id

id: int
attribute

width

width: int
attribute

x

x: int
attribute

y

y: int
class

AiVisionDetectionMode

class AiVisionDetectionMode
attribute

APRILTAG

APRILTAG: AiVisionDetectionMode
attribute

COLOR

COLOR: AiVisionDetectionMode
attribute

COLOR_MERGE

COLOR_MERGE: AiVisionDetectionMode
attribute

MODEL

MODEL: AiVisionDetectionMode
class

AiVisionFlags

class AiVisionFlags
attribute

COLOR_MERGE

COLOR_MERGE: AiVisionFlags
attribute

DISABLE_APRILTAG

DISABLE_APRILTAG: AiVisionFlags
attribute

DISABLE_COLOR

DISABLE_COLOR: AiVisionFlags
attribute

DISABLE_MODEL

DISABLE_MODEL: AiVisionFlags
attribute

DISABLE_STATUS_OVERLAY

DISABLE_STATUS_OVERLAY: AiVisionFlags
attribute

DISABLE_USB_OVERLAY

DISABLE_USB_OVERLAY: AiVisionFlags
class

AiVisionModelObject

class AiVisionModelObject
attribute

classification

classification: str
attribute

confidence

confidence: int
attribute

height

height: int
attribute

id

id: int
attribute

width

width: int
attribute

x

x: int
attribute

y

y: int
class

AiVisionSensor

class AiVisionSensor
function

__init__

__init__(self, port: int) -> None
function

enable_test

enable_test(self, test: int) -> None
function

free

free(self) -> None
function

get_color

get_color(self, id: int) -> AiVisionColor | None
function

get_color_code

get_color_code(self, id: int) -> AiVisionColorCode | None
function

get_color_codes

get_color_codes(self) -> tuple[{"cls":"ExprTuple","elements":[{"cls":"ExprBinOp","left":{"cls":"ExprName","member":"get_color_codes","name":"AiVisionColorCode"},"operator":"|","right":"None"},"..."],"implicit":true}]
function

get_flags

get_flags(self) -> AiVisionFlags
function

get_object_count

get_object_count(self) -> int
function

get_objects

get_objects(self) -> tuple[{"cls":"ExprTuple","elements":[{"cls":"ExprBinOp","left":{"cls":"ExprBinOp","left":{"cls":"ExprBinOp","left":{"cls":"ExprName","member":"get_objects","name":"AiVisionColorObject"},"operator":"|","right":{"cls":"ExprName","member":"get_objects","name":"AiVisionCodeObject"}},"operator":"|","right":{"cls":"ExprName","member":"get_objects","name":"AiVisionAprilTagObject"}},"operator":"|","right":{"cls":"ExprName","member":"get_objects","name":"AiVisionModelObject"}},"..."],"implicit":true}]
function

get_temperature

get_temperature(self) -> float
function

set_apriltag_family

set_apriltag_family(self, family: AprilTagFamily) -> None
function

set_color

set_color(self, id: int, color: AiVisionColor) -> None
function

set_color_code

set_color_code(self, id: int, code: AiVisionColorCode) -> None
function

set_detection_mode

set_detection_mode(self, mode: AiVisionDetectionMode) -> None
function

set_flags

set_flags(self, flags: AiVisionFlags) -> None
function

start_awb

start_awb(self) -> None
class

AprilTagFamily

class AprilTagFamily
attribute

CIRCLE21H7

CIRCLE21H7: AprilTagFamily
attribute

TAG16H5

TAG16H5: AprilTagFamily
attribute

TAG25H9

TAG25H9: AprilTagFamily
attribute

TAG36H11

TAG36H11: AprilTagFamily
class

Auto

class Auto
function

__init__

__init__(self) -> None
class

BrakeMode

class BrakeMode
attribute

BRAKE

BRAKE: BrakeMode
attribute

COAST

COAST: BrakeMode
attribute

HOLD

HOLD: BrakeMode
class

ButtonState

class ButtonState
attribute

is_now_pressed

is_now_pressed: bool
attribute

is_now_released

is_now_released: bool
attribute

is_pressed

is_pressed: bool
attribute

is_released

is_released: bool
class

CalibrateFuture

class CalibrateFuture

Future that calibrates an IMU, created with InertialSensor.Calibrate.

class

Code

class Code
function

__init__

__init__(self, code: VisionCode) -> None
attribute

code

code: VisionCode
class

Color

class Color
function

__init__

__init__(self, r: int = 0, g: int = 0, b: int = 0) -> None
function

as_int

as_int(self) -> int
attribute

AQUA

AQUA: Color
attribute

b

b: int
attribute

BLACK

BLACK: Color
attribute

BLUE

BLUE: Color
attribute

FUCHSIA

FUCHSIA: Color
attribute

g

g: int
attribute

GRAY

GRAY: Color
attribute

GREEN

GREEN: Color
attribute

LIME

LIME: Color
attribute

MAROON

MAROON: Color
attribute

NAVY

NAVY: Color
attribute

OLIVE

OLIVE: Color
attribute

PURPLE

PURPLE: Color
attribute

r

r: int
attribute

RED

RED: Color
attribute

SILVER

SILVER: Color
attribute

TEAL

TEAL: Color
attribute

WHITE

WHITE: Color
attribute

YELLOW

YELLOW: Color
class

Competition

class Competition
function

__init__

__init__(self) -> None
function

autonomous

autonomous(self, routine: Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"autonomous","name":"Any"}],"implicit":true}]) -> Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"autonomous","name":"Any"}],"implicit":true}]
function

connected

connected(self, routine: Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"connected","name":"Any"}],"implicit":true}]) -> Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"connected","name":"Any"}],"implicit":true}]
function

disabled

disabled(self, routine: Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"disabled","name":"Any"}],"implicit":true}]) -> Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"disabled","name":"Any"}],"implicit":true}]
function

disconnected

disconnected(self, routine: Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"disconnected","name":"Any"}],"implicit":true}]) -> Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"disconnected","name":"Any"}],"implicit":true}]
function

driver

driver(self, routine: Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"driver","name":"Any"}],"implicit":true}]) -> Callable[{"cls":"ExprTuple","elements":["...",{"cls":"ExprName","member":"driver","name":"Any"}],"implicit":true}]
function

run

run(self) -> CompetitionRuntime
class

CompetitionRuntime

class CompetitionRuntime
class

Controller

class Controller
function

__init__

__init__(self, id: ControllerId = ControllerId.PRIMARY) -> None
function

clear_line

clear_line(self, line: int) -> ControllerFuture
function

clear_screen

clear_screen(self) -> ControllerFuture
function

free

free(self) -> None
function

get_battery_capacity

get_battery_capacity(self) -> float
function

get_battery_level

get_battery_level(self) -> int
function

get_connection

get_connection(self) -> ControllerConnection
function

get_flags

get_flags(self) -> int
function

read_state

read_state(self) -> ControllerState
function

rumble

rumble(self, pattern: str) -> ControllerFuture
function

set_text

set_text(self, text: str, line: int, column: int) -> ControllerFuture
function

try_clear_line

try_clear_line(self, line: int) -> None
function

try_clear_screen

try_clear_screen(self) -> None
function

try_rumble

try_rumble(self, pattern: str) -> None
function

try_set_text

try_set_text(self, text: str, line: int, column: int) -> None
attribute

id

id: ControllerId
attribute

MAX_COLUMNS

MAX_COLUMNS: int
attribute

MAX_LINES

MAX_LINES: int
attribute

UPDATE_INTERVAL_MS

UPDATE_INTERVAL_MS: int
class

ControllerConnection

class ControllerConnection
attribute

OFFLINE

OFFLINE: ControllerConnection
attribute

TETHERED

TETHERED: ControllerConnection
attribute

VEX_NET

VEX_NET: ControllerConnection
class

ControllerFuture

class ControllerFuture
class

ControllerId

class ControllerId
attribute

PARTNER

PARTNER: ControllerId
attribute

PRIMARY

PRIMARY: ControllerId
class

ControllerState

class ControllerState
attribute

button_a

button_a: ButtonState
attribute

button_b

button_b: ButtonState
attribute

button_down

button_down: ButtonState
attribute

button_l1

button_l1: ButtonState
attribute

button_l2

button_l2: ButtonState
attribute

button_left

button_left: ButtonState
attribute

button_r1

button_r1: ButtonState
attribute

button_r2

button_r2: ButtonState
attribute

button_right

button_right: ButtonState
attribute

button_up

button_up: ButtonState
attribute

button_x

button_x: ButtonState
attribute

button_y

button_y: ButtonState
attribute

left_stick

left_stick: JoystickState
attribute

right_stick

right_stick: JoystickState
class

DetectionSource

class DetectionSource
function

__init__

__init__(self) -> None
attribute

Code

Code: type[Code]
attribute

Line

Line: type[Line]
attribute

Signature

Signature: type[Signature]
class

Direction

class Direction
attribute

FORWARD

FORWARD: Direction
attribute

REVERSE

REVERSE: Direction
class

DistanceObject

class DistanceObject
attribute

confidence

confidence: float
attribute

distance

distance: int
attribute

relative_size

relative_size: int | None
attribute

velocity

velocity: float
class

DistanceSensor

class DistanceSensor
function

__init__

__init__(self, port: int) -> None
function

free

free(self) -> None
function

get_object

get_object(self) -> DistanceObject | None
function

get_status

get_status(self) -> int
class

Electromagnet

class Electromagnet

An electromagnet plugged into a smart port.

The V5 electromagnet is a device unique to the V5 workcell kit. It is a simple device that produces a magnetic field at a provided power level. The power level does not have specific units.

Hardware Overview

Not much information can be found on the V5 workcell electromagnet; however, the electromagnet is intended to be used to pick up V5 Workcell colored disks. We can assume that the lower bound on the electromagnet's strength is the weight of a V5 Workcell colored disk. Assuming that the plastic part of the disk is made of ABS plastic and the metal part is solid iron, the electromagnet can lift at least ≈0.24oz based off of the CAD model files for the V5 Workcell kit provided by VEX.

function

__init__

__init__(self, port: int) -> None

Creates a new electromagnet.

Examples

from venice import *

electromagnet = Electromagnet(1)

# Use the electromagnet.
electromagnet.set_power(1, Electromagnet.MAX_POWER_DURATION_MS, MILLIS)
electromagnet.set_power(-0.2, 1000, MILLIS)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a Motor, free it, then construct a RotationSensor with the same Smart Port:

from venice import *

motor = Motor(1)
motor.free()
# `motor` is now unusable, but port 1 can be used in another device, such as a `RotationSensor`
rotation_sensor = RotationSensor(1)
function

get_current

get_current(self) -> float

Returns the magnet's electrical current in amps.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

electromagnet = Electromagnet(1)
electromagnet.set_power(1, Electromagnet.MAX_POWER_DURATION_MS, MILLIS)

current = electromagnet.get_current()
print(f"Current: {current}A")
function

get_power

get_power(self) -> float

Returns the user-set power level as a number from [-1.0, 1.0].

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

electromagnet = Electromagnet(1)
electromagnet.set_power(0.5, Electromagnet.MAX_POWER_DURATION_MS, MILLIS)

power = electromagnet.get_power()
print(f"Power: {power:.1%}")
function

get_status

get_status(self) -> int

Returns the status code of the magnet.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

electromagnet = Electromagnet(1)

status = electromagnet.get_status()
print(f"Status: 0x{status:08x}")
function

get_temperature

get_temperature(self) -> float

Returns the internal temperature of the magnet in degrees celsius.

Errors

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

electromagnet = Electromagnet(1)

temperature = electromagnet.get_temperature()
print(f"Temperature: {temperature}°C")
function

set_power

set_power(self, power: float, duration: float, unit: TimeUnit) -> None

Sets the power level of the magnet for a given duration.

Power is expressed as a number from [-1.0, 1.0]. Larger power values will result in a stronger force of attraction from the magnet.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

electromagnet = Electromagnet(1)
electromagnet.set_power(1, Electromagnet.MAX_POWER_DURATION_MS, MILLIS)
attribute

MAX_POWER_DURATION_MS

MAX_POWER_DURATION_MS: int

Maximum duration that the magnet can be powered for, in milliseconds.

class

EulerZYX

class EulerZYX
function

__init__

__init__(self, yaw: float = 0.0, pitch: float = 0.0, roll: float = 0.0) -> None
attribute

pitch

pitch: float
attribute

roll

roll: float
attribute

yaw

yaw: float
class

Gearset

class Gearset
attribute

BLUE

BLUE: Gearset
attribute

GREEN

GREEN: Gearset
attribute

RED

RED: Gearset
class

Gesture

class Gesture

Gesture data from an OpticalSensor.

function

get_time

get_time(self, unit: TimeUnit) -> float
attribute

count

count: int
attribute

direction

direction: GestureDirection
attribute

down

down: int
attribute

gesture_type

gesture_type: int
attribute

left

left: int
attribute

right

right: int
attribute

up

up: int
class

GestureDirection

class GestureDirection

Represents a gesture and its direction.

attribute

DOWN

DOWN: GestureDirection

Down gesture.

attribute

LEFT

LEFT: GestureDirection

Left gesture.

attribute

RIGHT

RIGHT: GestureDirection

Right gesture.

attribute

UP

UP: GestureDirection

Up gesture.

class

GpsSensor

class GpsSensor

A GPS sensor plugged into a Smart Port.

This module provides an interface to interact with the VEX V5 Game Position System (GPS) Sensor, which uses computer vision and an inertial measurement unit (IMU) to provide absolute position tracking within a VEX Robotics Competition field.

Hardware Description

The GPS sensor combines a monochrome camera and an IMU for robust position tracking through visual odometry. It works by detecting QR-like patterns on the field perimeter, using both the pattern sequence's and apparent size for position determination. The integrated IMU provides motion tracking for position estimation when visual tracking is unavailable or unreliable.

The sensor has specific operating ranges: it requires a minimum distance of 20 inches from the field perimeter for reliable readings, has a deadzone between 0-13.5 inches, and maintains accuracy up to 12 feet from the perimeter.

Sensor fusion between the camera and IMU helps maintain position tracking through dead zones and areas of inconsistent visual detection.

Further information about the sensor's method of operation can be found in IFI's patent.

function

__init__

__init__(self, port: int, offset: Point2, initial_position: Point2, initial_heading: float, initial_heading_unit: RotationUnit) -> None

Creates a new GPS sensor.

Sensor Configuration

The sensor requires three measurements to be made at the start of a match, passed as arguments to this function:

Sensor Offset

offset is the physical offset of the sensor's mounting location from a reference point on the robot.

Offset defines the exact point on the robot that is considered a "source of truth" for the robot's position. For example, if you considered the center of your robot to be the reference point for coordinates, then this value would be the signed 4-quadrant x and y offset from that point on your robot in meters. Similarly, if you considered the sensor itself to be the robot's origin of tracking, then this value would simply be Point2(0, 0)

Initial Robot Position

initial_position is an estimate of the robot's initial cartesian coordinates on the field in meters. This value helpful for cases when the robot's starting point is near a field wall.

When the GPS Sensor is too close to a field wall to properly read the GPS strips, the sensor will be unable to localize the robot's position due the wall's proximity limiting the view of the camera. This can cause the sensor inaccurate results at the start of a match, where robots often start directly near a wall.

By providing an estimate of the robot's initial position on the field, this problem is partially mitigated by giving the sensor an initial frame of reference to use.

Initial Robot Heading

initial_heading is a value between 0 and 360 degrees that informs the GPS of its heading at the start of the match. Similar to initial_position, this is useful for improving accuracy when the sensor is in close proximity to a field wall, as the sensor's rotation values are continuously checked against the GPS field strips to prevent drift over time. If the sensor starts too close to a field wall, providing an initial_heading can help prevent this drift at the start of the match.

Examples

from venice import *

# Create a GPS sensor mounted 22.5 cm left and 22.5 cm forward of the robot's tracking origin.
# Starting at position (0, 0) with a 90 degree heading.
gps = GpsSensor(
# Port 1
1,

# Sensor is mounted 0.225 meters to the left and 0.225 meters forward from the robot's tracking origin.
Point2(-0.225, 0.225),

# Robot's starting point is at the center of the field.
Point2(0, 0),

# Robot is facing to the right initially.
90,
DEGREES
)
function

free

free(self) -> None

Returns the internal status code of the inertial sensor.

Errors

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InertialSensor(1)
status = imu.get_status()

print(f"Status: 0x{status:08x}")
function

get_acceleration

get_acceleration(self) -> Vec3

Returns raw accelerometer values of the sensor's internal IMU.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

async def main():
# Read out acceleration values every 10 ms
while True:
acceleration = gps.get_acceleration()
print(f"x: {acceleration.x}G, y: {acceleration.y}G, z: {acceleration.z}G")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_error

get_error(self) -> float

Returns the RMS (Root Mean Squared) error for the sensor's position reading in meters.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Check position accuracy
error = gps.get_error()
if error > 0.3:
print(f"Warning: GPS position accuracy is low ({error} m)")
function

get_euler

get_euler(self, unit: RotationUnit) -> EulerZYX

Returns the Euler angles (pitch, yaw, roll) representing the GPS's orientation.

Euler angles are normalized to half a turn, meaning they range from (-180°, 180°].

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

angles = gps.get_euler(DEGREES)
print("yaw: {angles.yaw}°, pitch: {angles.pitch}°, roll: {angles.roll}°")
function

get_gyro_rate

get_gyro_rate(self) -> Vec3

Returns the raw gyroscope values of the sensor's internal IMU.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

async def main():
# Read out angular velocity values every 10 ms
while True:
rates = gps.get_gyro_rate()
print(f"x: {rates.x}°/s, y: {rates.y}°/s, z: {rates.z}°/s")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_heading

get_heading(self, unit: RotationUnit) -> float

Returns the sensor's yaw angle bounded by [0.0, 360.0) degrees.

Clockwise rotations are represented with positive degree values, while counterclockwise rotations are represented with negative ones. If a heading offset has not been set using GpsSensor.set_heading, then 90 degrees will located to the right of the field.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Get current heading
heading = gps.get_heading(DEGREES)
print(f"Heading is {heading} degrees")
function

get_offset

get_offset(self) -> Point2

Returns the user-configured offset from a reference point on the robot.

This offset value is passed to GpsSensor() and can be changed using GpsSensor.set_offset.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

gps = GpsSensor(
1,

# Initial offset value is configured here!
#
# Let's assume that the sensor is mounted 22.5 cm to the left and 22.5 cm forward from
# our desired tracking origin
Point2(-0.225, 0.225),

Point2(0, 0),
90,
DEGREES
)

# Get the configured offset of the sensor
offset = gps.get_offset()
print(f"GPS sensor is mounted at x={offset.x}, y={offset.y}") # "Sensor is mounted at x=-0.225, y=0.225"

# Change the offset to something new
gps.set_offset(Point2(0, 0))

# Get the configured offset of the sensor again
new_offset = gps.get_offset()
print(f"GPS sensor is mounted at x={new_offset.x}, y={new_offset.y}") # "Sensor is mounted at x=0.0, y=0.0"
function

get_position

get_position(self) -> Point2

Returns an estimate of the robot's location on the field as cartesian coordinates measured in meters.

The reference point for a robot's position is determined by the sensor's configured offset value.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Get current position
position = gps.get_position()
print(f"Robot is at x={position.x}, y={position.y}")
function

get_quaternion

get_quaternion(self) -> Quaternion

Returns a quaternion representing the sensor's orientation.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

quaternion = gps.get_quaternion()
print(f"x: {quaternion.x}, y: {quaternion.y}, z: {quaternion.z}, scalar: {quaternion.w}")
function

get_rotation

get_rotation(self, unit: RotationUnit) -> float

Returns the total number of degrees the GPS has spun about the z-axis.

This value is theoretically unbounded. Clockwise rotations are represented with positive degree values, while counterclockwise rotations are represented with negative ones. If a heading offset has not been set using GpsSensor.set_rotation, then 90 degrees will located to the right of the field.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

rotation = gps.get_rotation(DEGREES)
print(f"Robot has rotated {rotation} degrees since calibration.")
function

get_status

get_status(self) -> int

Returns the internal status code of the sensor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

status = gps.get_status()
print(f"Status: 0x{status:08x}")
function

reset_heading

reset_heading(self) -> None

Offsets the reading of GpsSensor.get_heading to zero.

This method has no effect on the values returned by GpsSensor.get_position.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

async def main():
# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

# Store heading before reset.
heading = gps.get_heading(DEGREES)

# Reset heading back to zero.
gps.reset_heading()

vasyncio.run(main)
function

reset_rotation

reset_rotation(self) -> None

Offsets the reading of GpsSensor.get_rotation to zero.

This method has no effect on the values returned by GpsSensor.get_position.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

async def main():
# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

# Store rotation before reset.
rotation = gps.get_rotation(DEGREES)

# Reset rotation back to zero.
gps.reset_rotation()

vasyncio.run(main)
function

set_data_interval

set_data_interval(self, interval: float, unit: TimeUnit) -> None

Sets the internal computation speed of the sensor's internal IMU.

This method does NOT change the rate at which user code can read data off the GPS, as the brain will only talk to the device every 10mS regardless of how fast data is being sent or computed. This also has no effect on the speed of methods such as GpsSensor.get_position, as it only changes the internal computation speed of the sensor's internal IMU.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Set to minimum interval
gps.set_data_interval(5, MILLIS)
function

set_heading

set_heading(self, heading: float, unit: RotationUnit) -> None

Offsets the reading of GpsSensor.get_heading to a specified angle value.

Target will default to 360.0 if above 360.0 and default to 0.0 if below 0.0.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Set heading to 90 degrees clockwise.
gps.set_heading(90, DEGREES)

heading = gps.get_heading(DEGREES)
print(f"Heading: {heading} degrees")
function

set_offset

set_offset(self, offset: Point2) -> None

Adjusts the sensor's physical offset from the robot's tracking origin.

This value is also configured initially through GpsSensor::().

Offset defines the exact point on the robot that is considered a "source of truth" for the robot's position. For example, if you considered the center of your robot to be the reference point for coordinates, then this value would be the signed 4-quadrant x and y offset from that point on your robot in meters. Similarly, if you considered the sensor itself to be the robot's origin of tracking, then this value would simply be Point2(0, 0)

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

gps = GpsSensor(
1,

# Initial offset value is configured here!
#
# Let's assume that the sensor is mounted 22.5 cm to the left and 22.5 cm forward from
# our desired tracking origin
Point2(-0.225, 0.225),

Point2(0, 0),
90,
DEGREES
)

# Get the configured offset of the sensor
offset = gps.get_offset()
print(f"GPS sensor is mounted at x={offset.x}, y={offset.y}") # "Sensor is mounted at x=-0.225, y=0.225"

# Change the offset to something new
gps.set_offset(Point2(0, 0))

# Get the configured offset of the sensor again
new_offset = gps.get_offset()
print(f"GPS sensor is mounted at x={new_offset.x}, y={new_offset.y}") # "Sensor is mounted at x=0.0, y=0.0"
function

set_rotation

set_rotation(self, rotation: float, unit: RotationUnit) -> None

Offsets the reading of GpsSensor.get_rotation to a specified angle value.

This method has no effect on the values returned by GpsSensor.get_position.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

# Assume we're starting in the middle of the field facing upwards, with the sensor's
# mounting point being our reference for position.
gps = GpsSensor(
1,
Point2(0, 0),
Point2(0, 0),
0,
DEGREES
)

# Set rotation to 90 degrees clockwise.
gps.set_rotation(90, DEGREES)

rotation = gps.get_rotation(DEGREES)
print(f"Rotation: {rotation} degrees")
class

InertialOrientation

class InertialOrientation

Represents one of six possible physical IMU orientations relative to the earth's center of gravity.

attribute

X_DOWN

X_DOWN: InertialOrientation

X-axis facing down.

attribute

X_UP

X_UP: InertialOrientation

X-axis facing up.

attribute

Y_DOWN

Y_DOWN: InertialOrientation

Y-axis facing down.

attribute

Y_UP

Y_UP: InertialOrientation

Y-axis facing up.

attribute

Z_DOWN

Z_DOWN: InertialOrientation

Z-Axis facing up (VEX logo facing DOWN).

attribute

Z_UP

Z_UP: InertialOrientation

Z-Axis facing down (VEX logo facing UP).

class

InertialSensor

class InertialSensor

An inertial sensor (IMU) plugged into a Smart Port.

This class provides an interface to interact with the V5 Inertial Sensor, which combines a 3-axis accelerometer and 3-axis gyroscope for precise motion tracking and navigation capabilities.

Hardware Overview

The IMU's integrated accelerometer measures linear acceleration along three axes:

  • X-axis: Forward/backward motion
  • Y-axis: Side-to-side motion
  • Z-axis: Vertical motion

These accelerometer readings include the effect of gravity, which can be useful for determining the sensor's orientation relative to the ground.

The IMU also has a gyroscope that measures rotational velocity and position on three axes:

  • Roll: Rotation around X-axis
  • Pitch: Rotation around Y-axis
  • Yaw: Rotation around Z-axis

Like all other Smart devices, VEXos will process sensor updates every 10mS.

Coordinate System

The IMU uses a NED (North-East-Down) right-handed coordinate system:

  • X-axis: Positive towards the front of the robot (North)
  • Y-axis: Positive towards the right of the robot (East)
  • Z-axis: Positive downwards (towards the ground)

This NED convention means that when the robot is on a flat surface:

  • The Z acceleration will read approximately +9.81 m/s² (gravity)
  • Positive roll represents clockwise rotation around the X-axis (when looking North)
  • Positive pitch represents nose-down rotation around the Y-axis
  • Positive yaw represents clockwise rotation around the Z-axis (when viewed from above)

Calibration & Mounting Considerations

The IMU requires a calibration period to establish its reference frame in one of six possible orientations (described by InertialOrientation). The sensor must be mounted flat in one of these orientations. Readings will be unpredictable if the IMU is mounted at an angle or was moving/disturbed during calibration.

In addition, physical pressure on the sensor's housing or static electricity can cause issues with the onboard gyroscope, so pressure-mounting the IMU or placing the IMU low to the ground is undesirable.

Disconnect Behavior

If the IMU loses power due to a disconnect — even momentarily, all calibration data will be lost and VEXos will re-initiate calibration automatically. The robot cannot be moving when this occurs due to the aforementioned unpredictable behavior. As such, it is vital that the IMU maintain a stable connection to the Brain and voltage supply during operation.

function

__init__

__init__(self, port: int) -> None

Create a new inertial sensor.

Important

This sensor must be calibrated using InertialSensor.calibrate before any meaningful data can be read from it.

Examples

from venice import *

imu = InertialSensor(1)
function

calibrate

calibrate(self) -> CalibrateFuture

Calibrates the IMU.

Returns a CalibrateFuture that resolves once the calibration operation has finished or timed out.

This method MUST be called for any meaningful gyroscope readings to be obtained. Calibration requires the sensor to be sitting completely still. If the sensor is moving during the calibration process, readings will drift from reality over time.

Raises

Calibration has a 1-second start timeout (when waiting for calibration to actually start on the sensor) and a 3-second end timeout (when waiting for calibration to complete after it has started) as a failsafe in the event that something goes wrong and the sensor gets stuck in a calibrating state.

  • DeviceError: If either timeout is exceeded in its respective phase of calibration, or if there is not an Inertial Sensor connect to the port.

Examples

Calibration process with error handling and a retry:

from venice import *

imu = InertialSensor(1)

async def main():
try:
imu.calibrate()
print("IMU calibrated successfully.")
except DeviceError as err:
print(f"IMU failed to calibrate, retrying. Reason: {err}")

# Since calibration failed, let's try one more time. If that fails,
# we just ignore the error and go on with our lives.
await imu.calibrate()

vasyncio.run(main)

Calibrating in a competition environment:

from venice import *

imu = InertialSensor(1)

comp = Competition()

@comp.autonomous
async def auton():
while True:
try:
heading = imu.get_heading(DEGREES)
print(f"IMU Heading: {heading}°")
except DeviceError:
pass

await vasyncio.Sleep(10, MILLIS)

async def main():
try:
await imu.calibrate()
except DeviceError:
# Log out a warning to terminal if calibration failed. You can also retry by
# calling it again, although this usually only happens if the sensor was unplugged.
println!("WARNING: IMU failed to calibrate! Readings might be inaccurate!");

await comp.run()

vasyncio.run(main)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a RotationSensor, free it, then construct a Motor with the same Smart Port:

from venice import *

sensor = RotationSensor(1)
sensor.free()
# `sensor` is now unusable, but port 1 can be used in another device, such as a `Motor`
motor = Motor(1)
function

get_acceleration

get_acceleration(self) -> Vec3

Returns the sensor's raw acceleration readings in g (multiples of ~9.8 m/s/s).

Errors

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Read out angular velocity values every 10mS
while True:
acceleration = sensor.get_acceleration()
print(f"x: {acceleration.x}G, y: {acceleration.y}G, z: {acceleration.z}G")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_euler

get_euler(self, unit: RotationUnit) -> EulerZYX

Returns the Euler angles (pitch, yaw, roll) in radians representing the Inertial Sensor’s orientation.

Euler angles are normalized to half a turn, meaning they range from (-180°, 180°].

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

euler = sensor.get_euler(DEGREES)
print("pitch: {euler.pitch}°, yaw: {euler.yaw}°, roll: {euler.roll}°")

vasyncio.run(main)
function

get_gyro_rate

get_gyro_rate(self) -> Vec3

Returns the Inertial Sensor’s raw gyroscope readings in dps (degrees per second).

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Read out angular velocity values every 10mS
while True:
rates = sensor.get_gyro_rate()
print(f"x: {rates.x}°/s, y: {rates.y}°/s, z: {rates.z}°/s")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_heading

get_heading(self, unit: RotationUnit) -> float

Returns the Inertial Sensor’s yaw angle bounded from [0.0, 360.0) degrees.

Clockwise rotations are represented with positive degree values, while counterclockwise rotations are represented with negative ones.

Exceptions

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

try:
heading = imu.get_heading(DEGREES)
print(f"Heading is {heading} degrees.")
except DeviceError:
pass

vasyncio.run(main)
function

get_physical_orientation

get_physical_orientation(self) -> InertialOrientation

Returns the physical orientation of the sensor measured at calibration.

This orientation can be one of six possible orientations aligned to two cardinal directions.

Raises

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
await imu.calibrate()
orientation = imu.get_physical_orientation()
print(f"Sensor was calibrated while facing {orientation}")

vasyncio.run(main)
function

get_quaternion

get_quaternion(self) -> Quaternion

Returns a quaternion representing the Inertial Sensor’s current orientation.

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

quaternion = sensor.get_quaternion()
print("x: {quaternion.x}, y: {quaternion.y}, z: {quaternion.z}, w: {quaternion.w}")

vasyncio.run(main)
function

get_rotation

get_rotation(self, unit: RotationUnit) -> float

Returns the total number of degrees the Inertial Sensor has spun about the z-axis.

This value is theoretically unbounded. Clockwise rotations are represented with positive degree values, while counterclockwise rotations are represented with negative ones.

Errors

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

try:
rotation = imu.get_rotation(DEGREES)
print(f"Robot has rotated {rotation} degrees since calibration.")
except DeviceError:
pass

vasyncio.run(main)
function

get_status

get_status(self) -> int

Returns the internal status code of the inertial sensor.

Errors

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InertialSensor(1)
status = imu.get_status()

print(f"Status: 0x{status:08x}")
function

is_auto_calibrated

is_auto_calibrated(self) -> bool

Returns True if the sensor was calibrated using auto-calibration.

In some cases (such as a loss of power), VEXos will automatically decide to recalibrate the inertial sensor.

Errors

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InterialSensor(1)

if sensor.is_auto_calibrated():
print("Sensor was automatically calibrated by VEXos.")
function

is_calibrating

is_calibrating(self) -> bool

Returns True if the sensor is currently calibrating.

Errors

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

imu = InertialSensor(1)

# We haven't calibrated yet, so this is expected.
if !imu.is_calibrating():
print("Sensor is not currently calibrating.")
function

reset_heading

reset_heading(self) -> None

Resets the current reading of the sensor's heading to zero.

This only affects the value returned by InertialSensor.get_heading and does not effect InertialSensor.get_rotation or InertialSensor.get_euler/ InertialSensor.get_quaternion.

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

# Store heading before reset.
heading = sensor.get_heading()

# Reset heading back to zero.
sensor.reset_heading()

vasyncio.run(main)
function

reset_rotation

reset_rotation(self) -> None

Resets the current reading of the sensor's rotation to zero.

This only affects the value returned by InertialSensor.get_rotation and does not effect InertialSensor.get_heading or InertialSensor.get_euler/InertialSensor.get_quaternion.

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

async def main():
# Calibrate sensor, raise if calibration fails.
await imu.calibrate()

# Sleep for two seconds to allow the robot to be moved.
await vasyncio.Sleep(2, SECOND)

# Store rotation before reset.
rotation = sensor.get_rotation(DEGREES)

# Reset heading back to zero.
sensor.reset_rotation()

vasyncio.run(main)
function

set_data_interval

set_data_interval(self, interval: float, unit: TimeUnit) -> None

Sets the internal computation speed of the IMU.

This method does NOT change the rate at which user code can read data off the IMU, as the brain will only talk to the device every 10mS regardless of how fast data is being sent or computed.

This duration should be above InertialSensor.MIN_DATA_INTERVAL (5 milliseconds).

Precision

The internal data rate of the IMU has a precision of 5 milliseconds.

Raises

  • DeviceError: If no device is connected to the port, or if the wrong type of device is connected.
  • ValueError: If interval is negative.

Examples

from venice import *

imu = InertialSensor(1)

# Set to minimum interval.
imu.set_data_interval(InertialSensor.MIN_DATA_INTERVAL)
function

set_heading

set_heading(self, heading: float, unit: RotationUnit) -> None

Sets the current reading of the sensor's heading to a given value.

This only affects the value returned by InertialSensor.get_heading and does not effect InertialSensor.get_rotation or InertialSensor.get_euler/ InertialSensor.get_quaternion.

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)

# Set heading to 90 degrees clockwise.
imu.set_heading(90, DEGREES)
function

set_rotation

set_rotation(self, rotation: float, unit: RotationUnit) -> None

Sets the current reading of the sensor's rotation to a given value.

This only affects the value returned by InertialSensor.get_rotation and does not effect InertialSensor.get_heading or InertialSensor.get_euler/InertialSensor.get_quaternion.

Raises

  • DeviceError: If there is not an Inertial Sensor connected to the port, or if the sensor is currently calibrating and cannot be used.

Examples

from venice import *

imu = InertialSensor(1)
imu.set_rotation(90, DEGREES)
attribute

CALIBRATION_END_TIMEOUT_MS

CALIBRATION_END_TIMEOUT_MS: int

The maximum time that the Inertial Sensor should take to end its calibration process after calibration has begun. Measured in milliseconds.

attribute

CALIBRATION_START_TIMEOUT_MS

CALIBRATION_START_TIMEOUT_MS: int

The maximum time that the Inertial Sensor should take to begin its calibration process following a call to InertialSensor.calibrate. Measured in milliseconds.

attribute

MIN_DATA_INTERVAL

MIN_DATA_INTERVAL: int

The minimum data rate that you can set an IMU to run at, in milliseconds.

class

JoystickState

class JoystickState
attribute

x

x: float
attribute

x_raw

x_raw: int
attribute

y

y: float
attribute

y_raw

y_raw: int
class

LedMode

class LedMode
class

Manual

class Manual
function

__init__

__init__(self, r: int, g: int, b: int, brightness: float) -> None
attribute

b

b: int
attribute

brightness

brightness: float
attribute

g

g: int
attribute

r

r: int
function

__init__

__init__(self) -> None
attribute

Auto

Auto: type[Auto]
class

Line

class Line
function

__init__

__init__(self) -> None
class

LinkType

class LinkType

The type of radio link being established.

VEXLink is a point-to-point connection, with one "manager" robot and one "worker" robot.

attribute

MANAGER

MANAGER: LinkType

Manager Radio

This end of the link has a 1040-bytes/sec data rate when communicating with a worker radio.

attribute

WORKER

WORKER: LinkType

Worker Radio

This end of the link has a 520-bytes/sec data rate when communicating with a manager radio.

class

Motor

class Motor

A motor plugged into a Smart Port.

This class provides abstractions for interacting with VEX Smart Motors, supporting both the 11W and 5.5W variants.

Overview

The V5 Smart Motors come in two variants: an 11W model, with interchangeable gear cartridges and a 5.5W model, with a fixed gearing. The 11W motor supports three cartridge options, which will gear the motor down from its base RPM of 3600: a red cartridge providing 100 RPM output, a green cartridge for 200 RPM, and a blue cartridge for 600 RPM. The 5.5W motor comes with a non-interchangeable 200 RPM gear cartridge.

Smart Motors feature several integrated sensors, including an encoder for measuring the velocity and position of the motor, a temperature sensor for detecting overheats, and sensors for measuring output voltage, current, and efficiency.

Communication between a Smart motor and the V5 Brain occur at two different intervals. While the motor communicates with the Brain every 5 milliseconds (and commands can be written to the motor every 5mS), the Brain only reads data from the motor every 10mS. This effectively places the date write interval at 5mS and the data read interval at 10mS.

More in-depth specs for the 11W motor can be found here.

Current Limitations

There are some cases where VEXos or the motor itself may decide to limit output current:

  • Stall Prevention: The stall current on 11W motors is limited to 2.5A. This limitation eliminates the need for automatic resetting fuses (PTC devices) in the motor, which can disrupt operation. By restricting the stall current to 2.5A, the motor effectively avoids undesirable performance dips and ensures that users do not inadvertently cause stall situations.

  • Motor Count: Robots that use 8 or fewer 11W motors will have the aforementioned current limit of 2.5A set for each motor. Robots using more than 8 motors, will have a lower default current limit per-motor than 2.5A. This limit is determined in VEXos by a calculation accounting for the number of motors plugged in, and the user's manually set current limits using Motor.set_current_limit. For more information regarding the current limiting behavior of VEXos, see this forum post.

  • Temperature Management: Motors have an onboard sensor for measuring internal temperature. If the motor determines that it is overheating, it will throttle its output current and warn the user.

Motor Control

Each motor contains a sophisticated control system built around a Cortex M0+ microcontroller. The microcontroller continuously monitors position, speed, direction, voltage, current, and temperature through integrated sensors.

The onboard motor firmware implements a set of pre-tuned PID (Proportional-Integral-Derivative) controllers operating on a 10-millisecond cycle for position and velocity control. Motors also have braking functionality for holding a specific position under load.

function

__init__

__init__(self, port: int, direction: Direction = Direction.FORWARD, gearset: Gearset = Gearset.GREEN) -> None

Creates a new 11W (V5) Smart Motor.

See Motor.new_exp to create a 5.5W (EXP) Smart Motor.

Examples

from venice import *

motor = Motor(1)
assert motor.is_v5
assert motor.max_voltage == Motor.V5_MAX_VOLTAGE
function

brake

brake(self, mode: BrakeMode) -> None

Stops this motor with the given BrakeMode.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

motor = Motor(1)
motor.brake(BrakeMode.HOLD)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a Motor, free it, then construct a RotationSensor with the same Smart Port:

from venice import *

motor = Motor(1)
motor.free()
# `motor` is now unusable, but port 1 can be used in another device, such as a `RotationSensor`
rotation_sensor = RotationSensor(1)
function

get_current

get_current(self) -> float

Returns the electrical current draw of the motor in amps.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the current draw of a motor:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(motor.max_voltage)
while True:
current = motor.get_current()
print(f"Current: {current:.2}A")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_current_limit

get_current_limit(self) -> float

Returns the current limit for the motor in amps.

This limit can be configured with the Motor.set_current_limit method.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the current limit of a motor:

from venice import *

motor = Motor(1)
current_limit = motor.get_current_limit()
print(f"Current Limit: {current_limit:.2}A")
function

get_direction

get_direction(self) -> Direction

Returns the Direction of this motor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

def print_motor_direction(motor: Motor):
if motor.get_direction() == Direction.FORWARD:
print("Motor is set to forwards")
else:
print("Motor is set to reverse")
function

get_efficiency

get_efficiency(self) -> float

Returns the efficiency of the motor from a range of [0.0, 1.0].

An efficiency of 1.0 means that the motor is moving electrically while drawing no electrical power, and an efficiency of 0.0 means that the motor is drawing power but not moving.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the efficiency of a motor:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(motor.max_voltage)
while True:
efficiency = motor.get_efficiency()
print(f"Current: {efficiency:.2}")

await vasyncio.Sleep(10, MILLIS)
function

get_faults

get_faults(self) -> int

Returns the fault flags of the motor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Check if a motor is over temperature:

from venice import *

OVER_TEMPERATURE_FLAG = 0x01

motor = Motor(1)

async def main():
while True:
faults = motor.get_faults()
print(f"Status: 0x{status:08x}")

# Test if `faults` contains `OVER_TEMPERATURE_FLAG`
if faults & OVER_TEMPERATURE_FLAG == OVER_TEMPERATURE_FLAG:
print("Warning: Motor is over temperature!")
await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_gearset

get_gearset(self) -> Gearset

Returns the gearset of the motor

For 5.5W motors, this will always be returned as Gearset::Green.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the gearset of a motor:

from venice import *

def print_gearset(motor: Motor):
try:
gearset = motor.gearset()
except:
print("Failed to get gearset. Is this an EXP motor?")
return

if gearset == Gearset.RED:
print("Motor is using the red gearset")
elif gearset == Gearset.GREEN:
print("Motor is using the green gearset")
elif gearset == Gearset.BLUE:
print("Motor is using the blue gearset")
function

get_position

get_position(self, unit: RotationUnit) -> float

Returns the angular position of the motor as measured by the IME (integrated motor encoder).

Gearing affects position!

Position measurements are dependent on the Motor's Gearset, and may be reported incorrectly if the motor is configured with the incorrect gearset variant. Make sure that the motor is configured with the same gearset as its physical cartridge color.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the current position of a motor:

from venice import *

motor = Motor(1)

async def main():
while True:
position = motor.get_position(DEGREES)
print(f"Position: {position}")
await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_power

get_power(self) -> float
function

get_raw_position

get_raw_position(self) -> int

Returns the most recently recorded raw encoder tick data from the motor's IME.

The motor's integrated encoder has a TPR of 4096. Gearset is not taken into consideration when dealing with the raw value, meaning this measurement will be taken relative to the motor's internal position before being geared down from 3600RPM.

Methods such as Motor::reset_position and Motor::set_position do not change the value of this raw measurement.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

use vexide::prelude::*;

motor = Motor(1)

async def main():
while True:
raw_pos = motor.get_raw_position()
print(f"Raw Position: {raw_pos}")

await vasyncio.sleep(10, MILLIS)

vasyncio.run(main)
function

get_status

get_status(self) -> int

Returns the status flags of a motor.

Errors

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Check if a motor is "busy" (busy only occurs if communicating with the motor fails)

from venice import *

BUSY_FLAG = 0x01

def is_motor_busy(motor: Motor) -> bool:
# Test if the motor status bits contain `BUSY_FLAG`
motor.get_status() & BUSY_FLAG == BUSY_FLAG
function

get_temperature

get_temperature(self) -> float

Returns the internal temperature recorded by the motor in increments of 5 °C.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Turn off the motor if it gets too hot:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(12)
while True:
if motor.get_temperature() > 30:
motor.brake(BrakeMode.COAST)
else:
motor.set_voltage(12)
await vasyncio.Sleep(10, MILLIS)
function

get_torque

get_torque(self) -> float

Returns the torque output of the motor in Nm.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the torque output of a motor:

from venice import *

motor = Motor(1)

async def main():
while True:
torque = motor.get_torque()
print(f"Torque: {torque:.2}Nm")
await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_velocity

get_velocity(self) -> float
function

get_voltage

get_voltage(self) -> float

Returns the voltage the motor is drawing in volts.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the voltage drawn by a motor:

from venice import *

motor = Motor(1)

async def main():
while True:
voltage = motor.get_voltage()
print(f"Voltage: {voltage:.2}V")
await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

get_voltage_limit

get_voltage_limit(self) -> float

Returns the voltage limit for the motor if one has been explicitly set.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print the voltage limit of a motor:

from venice import *

motor = Motor(1)
voltage_limit = motor.get_voltage_limit()
print(f"Voltage Limit: {voltage_limit:.2}V")
function

is_driver_fault

is_driver_fault(self) -> bool

Returns True if a H-bridge (motor driver) fault has occurred.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print a warning if the motor's H-bridge has a fault:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(12)
while True:
if motor.is_driver_fault():
print("Warning: Motor has a H-bridge fault")
current = motor.get_current()
print(f"Current: {current:.2}A")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

is_driver_over_current

is_driver_over_current(self) -> bool

Returns True if the motor's H-bridge has an over-current fault.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print a warning if it draws too much current:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(12)
while True:
if motor.is_driver_over_current():
print("Warning: Motor is drawing too much current")
current = motor.get_current()
print(f"Current: {current:.2}A")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

is_over_current

is_over_current(self) -> bool

Returns True if the motor's over-current flag is set.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Print a warning if the motor draws too much current:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(12)
while True:
if motor.is_over_current():
print("Warning: Motor is drawing too much current")
current = motor.get_current()
print(f"Current: {current:.2}A")

await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function

is_over_temperature

is_over_temperature(self) -> bool

Returns True if the motor's over temperature flag is set.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Turn off the motor if it gets too hot:

from venice import *

motor = Motor(1)

async def main():
motor.set_voltage(12)
while True:
if motor.is_over_temperature():
motor.brake(BrakeMode.COAST)
else:
motor.set_voltage(12)
await vasyncio.Sleep(10, MILLIS)

vasyncio.run(main)
function staticmethod

new_exp

new_exp(port: int, direction: Direction = Direction.FORWARD) -> Motor

Creates a new 5.5W (EXP) Smart Motor.

See Motor() or Motor.new_v5 to create a 11W (V5) Smart Motor.

Examples

from venice import *

motor = Motor(1)
assert motor.is_exp
assert motor.max_voltage == Motor.EXP_MAX_VOLTAGE
function staticmethod

new_v5

new_v5(port: int, direction: Direction = Direction.FORWARD, gearset: Gearset = Gearset.GREEN) -> Motor
function

reset_position

reset_position(self) -> None

Sets the current encoder position to zero without moving the motor.

Analogous to taring or resetting the encoder to the current position.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Move the motor in increments of 10 degrees:

from venice import *

motor = Motor(1)

async def main():
while True:
motor.set_position_target(10, DEGREES, 200)
await vasyncio.Sleep(1, SECOND)
motor.reset_position()
function

set_current_limit

set_current_limit(self, limit: float) -> None

Sets the current limit for the motor in amps.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Limit the current draw of a motor to 2.5A:

from venice import *

motor = Motor(1)
motor.set_current_limit(2.5)
function

set_direction

set_direction(self, direction: Direction) -> None

Sets the motor to operate in a given Direction.

This determines which way the motor considers to be “forwards”. You can use the marking on the back of the motor as a reference:

  • When Direction.FORWARD is specified, positive velocity/voltage values will cause the motor to rotate with the arrow on the back. Position will increase as the motor rotates with the arrow.
  • When Direction::REVERSE is specified, positive velocity/voltage values will cause the motor to rotate against the arrow on the back. Position will increase as the motor rotates against the arrow.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

motor = Motor(1, Direction.FORWARD)
motor.set_direction(Direction.REVERSE)
function

set_gearset

set_gearset(self, gearset: Gearset) -> None

Sets the gearset of an 11W motor.

Raises

DeviceError: If the motor is a 5.5W EXP Smart Motor, which has no swappable gearset, or if no motor is connected to the port.

Examples

from venice import *

# This must be a V5 motor
motor = Motor(1, Direction.FORWARD, Gearset.GREEN)

# Set the motor to use the red gearset
motor.set_gearset(Gearset.RED)
function

set_position

set_position(self, position: float, unit: RotationUnit) -> None

Sets the current encoder position to the given position without moving the motor.

Analogous to taring or resetting the encoder so that the new position is equal to the given position.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Set the current position of the motor to 90 degrees:

from venice import *

motor = Motor(1)
motor.set_position(90, DEGREES)

Reset the position of the motor to 0 degrees (analogous to Motor.reset_position):

from venice import *

motor = Motor(1)
motor.set_position(0, DEGREES)
function

set_position_target

set_position_target(self, position: float, unit: RotationUnit, velocity: int) -> None

Sets an absolute position target for the motor to attempt to reach.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

motor = Motor(1)

# Turn the motor to a position of 90 degrees at 200rpm.
motor.set_position_target(90, DEGREES, 200)
function

set_profiled_velocity

set_profiled_velocity(self, velocity: int) -> None

Changes the output velocity for a profiled movement (motor_move_absolute or motor_move_relative).

This will have no effect if the motor is not following a profiled movement.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

motor = Motor(1)

# Set the motor's target to a Position so that changing the velocity isn't a noop.
motor.set_position_target(90, DEGREES, 200)
motor.set_profiled_velocity(100)
function

set_velocity

set_velocity(self, rpm: int) -> None

Spins the motor at a target velocity.

This velocity corresponds to different actual speeds in RPM depending on the gearset used for the motor. Velocity is held with an internal PID controller to ensure consistent speed, as opposed to setting the motor's voltage.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Spin a motor at 100 RPM:

from venice import *

motor = Motor(1)
motor.set_velocity(100)
function

set_voltage

set_voltage(self, volts: float) -> None

Sets the motor's output voltage.

This voltage value spans from -12 (fully spinning reverse) to +12 (fully spinning forwards) volts, and controls the raw output of the motor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Give the motor full power:

from venice import *

v5_motor = Motor(1)
exp_motor = Motor(2)

v5_motor.set_voltage(v5_motor.max_voltage)
exp_motor.set_voltage(exp_motor.max_voltage)

Drive the motor based on a controller joystick:

from venice import *

motor = Motor(1)
controller = Controller()

async def main():
while True:
controller_state = controller.get_state()
voltage = controller_state.left_stick.x * motor.max_voltage

motor.set_voltage(voltage)

await vasyncio.Sleep(Motor.WRITE_INTERVAL_MS, MILLIS)

vasyncio.run(main)
function

set_voltage_limit

set_voltage_limit(self, limit: float) -> None

Sets the voltage limit for the motor in volts.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Limit the voltage of a motor to 4V:

from venice import *

motor = Motor(1)
motor.set_voltage_limit(4)
# Will appear as if the voltage was set to only 4V
motor.set_voltage(12)
attribute

EXP_MAX_VOLTAGE

EXP_MAX_VOLTAGE: float

The maximum voltage value that can be sent to an EXP Motor.

attribute

is_exp

is_exp: bool
attribute

is_v5

is_v5: bool
attribute

max_voltage

max_voltage: float
attribute

motor_type

motor_type: MotorType
attribute

V5_MAX_VOLTAGE

V5_MAX_VOLTAGE: float

The maximum voltage value that can be sent to a V5 Motor.

attribute

WRITE_INTERVAL_MS

WRITE_INTERVAL_MS: int

The interval at which the Brain will send new packets to a Motor, in milliseconds.

class

MotorType

class MotorType
attribute

EXP

EXP: MotorType
attribute

V5

V5: MotorType
class

OpticalRaw

class OpticalRaw

Represents the raw RGBC data an OpticalSensor.

attribute

b

b: int
attribute

clear

clear: int
attribute

g

g: int
attribute

r

r: int
class

OpticalRgb

class OpticalRgb

RGB data from an OpticalSensor.

attribute

b

b: float
attribute

brightness

brightness: float
attribute

g

g: float
attribute

r

r: float
class

OpticalSensor

class OpticalSensor

An optical sensor plugged into a Smart Port.

This class provides an interface to interact with the V5 Optical Sensor, which combines ambient light sensing, color detection, proximity measurement, and gesture recognition capabilities.

Hardware Overview

The optical sensor provides multi-modal optical sensing with an integrated white LED for low-light operation.

Color Detection

Color data reported as RGB, HSV, and grayscale data, with optimal performance at distances under 100mm. The proximity sensing uses reflected light intensity, making readings dependent on both ambient lighting and target reflectivity.

Gesture Detection

The optical sensor can detect four distinct motions (up, down, left, right) of objects passing over the sensor.

function

__init__

__init__(self, port: int) -> None

Creates a new optical sensor.

Examples

from venice import *

sensor = OpticalSensor(1)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a Motor, free it, then construct a RotationSensor with the same Smart Port:

from venice import *

motor = Motor(1)
motor.free()
# `motor` is now unusable, but port 1 can be used in another device, such as a `RotationSensor`
rotation_sensor = RotationSensor(1)
function

get_brightness

get_brightness(self) -> float

Returns the detected color's brightness.

Brightness values range from 0 to 1.0.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

brightness = sensor.get_brightness()
print(f"Color brightness: {brightness:.0%}")

# Check if color is dark or bright
if brightness < 0.3:
print("Dark color detected")
elif brightness > 0.7:
print("Bright color detected")
else:
print("Medium brightness color detected")
function

get_color

get_color(self) -> OpticalRgb

Returns the processed RGB color data from the sensor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

rgb = sensor.get_color()
print(f"Color reading: R={rgb.r}, G={rgb.g}, B={rgb.b}")

# Example: Check if object is primarily red
# Note that you should probably use `OpticalSensor.get_hue` instead for this
if rgb.r > rgb.g && rgb.r > rgb.b:
print("Object is primarily red!")
function

get_hue

get_hue(self) -> float

Returns the detected color's hue.

Hue has a range of 0 to 359.999.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

hue = sensor.get_hue()
print(f"Detected color hue: {hue:.1}°")
function

get_integration_time

get_integration_time(self, unit: TimeUnit) -> float

Returns integration time of the optical sensor in milliseconds, with minimum time being 3ms and the maximum time being 712ms.

The default integration time for the sensor is 103mS, unless otherwise set with OpticalSensor.set_integration_time.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

# Set integration time to 50 milliseconds.
sensor.set_integration_time(50, MILLIS)

# Log out the new integration time.
integration_time = sensor.get_integration_time(MILLIS)
print(f"Integration time: {integration_time}ms")
function

get_last_gesture

get_last_gesture(self) -> Gesture | None

Returns the most recent gesture data from the sensor, or None if no gesture was detected.

Gesture data updates every 500 milliseconds.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

async def main():
while True:
gesture = sensor.get_last_gesture()
if direction:
print(f"Direction: {gesture.direction}")

await vasyncio.Sleep(25, MILLIS)

vasyncio.run(main)
function

get_led_brightness

get_led_brightness(self) -> float

Returns the intensity/brightness of the sensor's LED indicator as a number from [0.0-1.0].

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

brightness = sensor.get_led_brightness()
print(f"LED brightness: {brightness:.1%}")
function

get_proximity

get_proximity(self) -> float

Returns an analog proximity value from 0 to 1.0.

A reading of 1.0 indicates that the object is close to the sensor, while 0.0 indicates that no object is detected in range of the sensor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

# Monitor proximity with thresholds
prox = sensor.get_proximity()
if prox > 0.8:
print("Object very close!")
elif prox > 0.5:
print("Object nearby")
elif prox > 0.2:
print("Object detected")
else:
print("No object in range")
function

get_raw_color

get_raw_color(self) -> OpticalRaw

Returns the raw, unprocessed RGBC color data from the sensor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

function

get_saturation

get_saturation(self) -> float

Returns the detected color's saturation.

Saturation has a range 0 to 1.0.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

saturation = sensor.get_saturation()
print(f"Color saturation: {saturation:.0%}")

# Check if color is muted or vibrant
if saturation < 0.5:
print("Muted color detected")
else:
print("Vibrant color detected")
function

get_status

get_status(self) -> int

Returns the internal status code of the optical sensor.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

status = sensor.get_status()
print(f"Status: 0x{status:08x}")
function

set_integration_time

set_integration_time(self, time: float, unit: TimeUnit) -> None

Set the integration time of the optical sensor.

Lower integration time results in faster update rates with lower accuracy due to less available light being read by the sensor.

The time value must be a duration between 3 and 712 milliseconds. If the integration time is out of this range, it will be clamped to fit inside it. See https://www.vexforum.com/t/v5-optical-sensor-refresh-rate/109632/9 for more information.

The default integration time for the sensor is 103mS, unless otherwise set.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

# Set integration time to 50 milliseconds.
sensor.set_integration_time(50, MILLIS)
function

set_led_brightness

set_led_brightness(self, brightness: float) -> None

Set the intensity of (intensity/brightness) of the sensor's LED indicator.

Intensity is expressed as a number from [0.0, 1.0].

Python

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = OpticalSensor(1)

async def main():
for _ in range(3):
# Turn LED on
try:
sensor.set_led_brightness(1)
except DeviceError as e:
print(f"Failed to turn LED on: {e}")

await vasyncio.Sleep(250, MILLIS)

# Turn LED off
try:
sensor.set_led_brightness(0)
except DeviceError as e:
print(f"Failed to turn LED off: {e}")

await vasyncio.Sleep(250, MILLIS)
attribute

GESTURE_UPDATE_INTERVAL_MS

GESTURE_UPDATE_INTERVAL_MS: int

The interval that gesture detection through OpticalSensor.get_last_gesture provides new data at.

attribute

MAX_INTEGRATION_TIME_MS

MAX_INTEGRATION_TIME_MS: int

The largest integration time you can set on an optical sensor, in milliseconds.

Source: https://www.vexforum.com/t/v5-optical-sensor-refresh-rate/109632/9

attribute

MIN_INTEGRATION_TIME_MS

MIN_INTEGRATION_TIME_MS: int

The smallest integration time you can set on an optical sensor, in milliseconds.

Source: https://www.vexforum.com/t/v5-optical-sensor-refresh-rate/109632/9

class

Point2

class Point2
function

__init__

__init__(self, x: float = 0.0, y: float = 0.0) -> None
attribute

x

x: float
attribute

y

y: float
class

PotentiometerType

class PotentiometerType
function

get_max_angle

get_max_angle(self, unit: RotationUnit) -> float
attribute

LEGACY

LEGACY: PotentiometerType
attribute

LEGACY_MAX_ANGLE_DEG

LEGACY_MAX_ANGLE_DEG: float
attribute

V2

V2: PotentiometerType
attribute

V2_MAX_ANGLE_DEG

V2_MAX_ANGLE_DEG: float
class

Quaternion

class Quaternion
function

__init__

__init__(self, w: float = 1.0, x: float = 0.0, y: float = 0.0, z: float = 0.0) -> None
attribute

w

w: float
attribute

x

x: float
attribute

y

y: float
attribute

z

z: float
class

RotationSensor

class RotationSensor
function

__init__

__init__(self, port: int, direction: Direction = Direction.FORWARD) -> None

Creates a new rotation sensor on the given port.

Whether or not the sensor should be reversed on creation can be specified.

Examples

from venice import *

sensor = RotationSensor(1)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a RotationSensor, free it, then construct a Motor with the same Smart Port:

from venice import *

sensor = RotationSensor(1)
sensor.free()
# `sensor` is now unusable, but port 1 can be used in another device, such as a `Motor`
motor = Motor(1)
function

get_angle

get_angle(self, unit: RotationUnit) -> float
function

get_direction

get_direction(self) -> Direction
function

get_position

get_position(self, unit: RotationUnit) -> float

Returns the total accumulated rotation of the sensor over time.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = RotationSensor(1)
position = sensor.get_position(DEGREES)

print(f"Position in degrees: {position}")
function

get_status

get_status(self) -> int

Returns the sensor's internal status code.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = RotationSensor(1)
status = sensor.get_status()
print(f"Status: 0x{status:08x}")
function

get_velocity

get_velocity(self) -> float

Returns the sensor's current velocity in degrees per second.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

from venice import *

sensor = RotationSensor(1)

velocity = sensor.get_velocity()
print(f"Velocity in RPM: {velocity / 6}") # 1rpm = 6dps
function

reset_position

reset_position(self) -> None

Reset's the sensor's position reading to zero.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = RotationSensor(1)

print(f"Before reset: {sensor.get_position()}")
sensor.reset_position()
print(f"After reset: {sensor.get_position()}")
function

set_data_interval

set_data_interval(self, interval: float, unit: TimeUnit) -> None

Sets the internal computation speed of the rotation sensor.

This method does NOT change the rate at which user code can read data off the sensor, as the brain will only talk to the device every 10mS regardless of how fast data is being sent or computed.

This duration should be above Self.MIN_DATA_INTERVAL (5 milliseconds).

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = RotationSensor(1)

# Set to minimum interval.
sensor.set_data_interval(RotationSensor.MIN_DATA_INTERVAL)
function

set_direction

set_direction(self, direction: Direction) -> None

Sets the sensor to operate in a given Direction.

This determines which way the sensor considers to be “forwards”. You can use the marking on the top of the motor as a reference:

  • When Direction.FORWARD is specified, positive velocity/voltage values will cause the motor to rotate with the arrow on the top. Position will increase as the motor rotates with the arrow.
  • When Direction.REVERSE is specified, positive velocity/voltage values will cause the motor to rotate against the arrow on the top. Position will increase as the motor rotates against the arrow.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

Set the sensor's direction to Direction.Reverse.

from venice import *

sensor = Rotation(1)

# Reverse the sensor
sensor.set_direction(Direction.REVERSE)

Reverse the sensor's direction (set to opposite of the previous direction):

from venice import *

sensor = RotationSensor(1)

# Reverse the sensor
sensor.set_direction(~sensor.get_direction())
function

set_position

set_position(self, position: float, unit: RotationUnit) -> None

Sets the sensor's position reading.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = RotationSensor(1)

# Set position to 15 degrees
sensor.set_position(15, DEGREES)
attribute

MIN_DATA_INTERVAL_MS

MIN_DATA_INTERVAL_MS: int

The minimum data rate that you can set a rotation sensor to, in milliseconds.

attribute

TICKS_PER_REVOLUTION

TICKS_PER_REVOLUTION: int

The amount of unique sensor readings per one revolution of the sensor.

class

RotationUnit

class RotationUnit
attribute

DEGREES

DEGREES: RotationUnit
attribute

RADIANS

RADIANS: RotationUnit
attribute

TURNS

TURNS: RotationUnit
class

SerialPort

class SerialPort
function

clear_buffers

clear_buffers(self) -> None
function

flush

flush(self) -> None
function

free

free(self) -> None
function

ioctl

ioctl(self, request: int, arg: int = 0) -> int
function staticmethod

open

open(port_number: int, baud_rate: int) -> SerialPortOpenFuture
function

read

read(self, size: int = {"cls":"ExprUnaryOp","operator":"-","value":"1"}) -> bytes
function

read1

read1(self, size: int = {"cls":"ExprUnaryOp","operator":"-","value":"1"}) -> bytes
function

set_baud_rate

set_baud_rate(self, baud_rate: int) -> None
function

write

write(self, buffer: bytes | bytearray | memoryview) -> int
function

write1

write1(self, buffer: bytes | bytearray | memoryview) -> int
attribute

INTERNAL_BUFFER_SIZE

INTERNAL_BUFFER_SIZE: int
attribute

MAX_BAUD_RATE

MAX_BAUD_RATE: int
class

SerialPortOpenFuture

class SerialPortOpenFuture
class

Signature

class Signature
function

__init__

__init__(self, id: int) -> None
attribute

id

id: int
class

StartupAuto

class StartupAuto
function

__init__

__init__(self) -> None
class

TimeUnit

class TimeUnit
attribute

MILLIS

MILLIS: TimeUnit
attribute

SECOND

SECOND: TimeUnit
class

Vec3

class Vec3
function

__init__

__init__(self, x: float = 0.0, y: float = 0.0, z: float = 0.0) -> None
attribute

x

x: float
attribute

y

y: float
attribute

z

z: float
class

VisionCode

class VisionCode
function

__init__

__init__(self, sig1: int, sig2: int, sig3: int | None = None, sig4: int | None = None, sig5: int | None = None) -> None
function staticmethod

from_id

from_id(id: int) -> VisionCode
attribute

sig1

sig1: int
attribute

sig2

sig2: int
attribute

sig3

sig3: int | None
attribute

sig4

sig4: int | None
attribute

sig5

sig5: int | None
class

VisionMode

class VisionMode
attribute

COLOR_DETECTION

COLOR_DETECTION: VisionMode
attribute

LINE_DETECTION

LINE_DETECTION: VisionMode
attribute

MIXED_DETECTION

MIXED_DETECTION: VisionMode
attribute

TEST

TEST: VisionMode
attribute

WIFI

WIFI: VisionMode
class

VisionObject

class VisionObject
function

get_angle

get_angle(self, unit: RotationUnit) -> float
attribute

center_x

center_x: int
attribute

center_y

center_y: int
attribute

height

height: int
attribute

offset_x

offset_x: int
attribute

offset_y

offset_y: int
attribute

source

source: DetectionSource
attribute

width

width: int
class

VisionSensor

class VisionSensor

A Vision Sensor plugged into a Smart Port.

This class provides an interface for interacting with the VEX Vision Sensor.

Hardware Overview

The VEX Vision Sensor is a device powered by an ARM Cortex M4 and Cortex M0 coprocessor with a color camera for the purpose of performing object recognition. The sensor can be trained to locate objects by color. The camera module itself is very similar internally to the Pixy2 camera, and performs its own onboard image processing. Manually processing raw image data from the sensor is not currently possible.

Every 20 milliseconds, the camera provides a list of the objects found matching up to seven unique VisionSignatures. The object’s height, width, and location is provided. Multi-colored objects may also be programmed through the use of VisionCodes.

The Vision Sensor has USB for a direct connection to a computer, where it can be configured using VEX's proprietary vision utility tool to generate color signatures. The Vision Sensor also has Wi-Fi Direct and can act as web server, allowing a live video feed of the camera from any computer equipped with a browser and Wi-Fi.

function

__init__

__init__(self, port: int) -> None

Creates a new vision sensor.

Examples

from venice import *

sensor = VisionSensor(1)
function

add_code

add_code(self, code: VisionCode) -> None

Registers a color code to the sensor's onboard memory. This code will be used to identify objects when using VisionSensor.get_objects.

Color codes are effectively "signature groups" that the sensor will use to identify objects containing the color of their signatures next to each other.

Volatile Memory

The onboard memory of the Vision Sensor is volatile and will therefore be wiped when the sensor loses its power source. As a result, this function should be called every time the sensor is used on program start.

Raises

  • DeviceError: If there was not a sensor connected to the port, or if a read operation failed, or there was no signature previously set in the slot(s) specified in the VisionCode. ValueError: If the given signature ID is not in the interval [1, 7].

Examples

from venice import *

sensor = VisionSensor(1)

# Two color signatures.
sig_1 = VisionSensor(10049, 11513, 10781, -425, 1, -212, 4.1)
sig_2 = VisionSensor(8973, 11143, 10058, -2119, -1053, -1586, 5.4)

# Store the signatures on the sensor.
sensor.set_signature(1, sig_1)
sensor.set_signature(2, sig_2)

# Create a code associating signatures 1 and 2 together.
code = VisionCode(1, 2)

# Register our code on the sensor. When we call `VisionSensor.get_objects`, the associated
# signatures will be returned as a single object if their colors are detected next to each
# other.
sensor.add_code(code)

# Scan for objects.
for object in sensor.get_objects():
# Filter only objects matching the code we just set.
if obj.source == DetectionSource.Code(code):
print(obj)
function

free

free(self) -> None

Release this device and free its Smart Port lock. This binding will become unusable after this call, but you can reuse the underlying Smart Port number in a new device.

Any attempts to use this device after freeing will result in a ValueError being raised.

Raises

ValueError: If the device has already been freed.

Examples

Construct a Motor, free it, then construct a RotationSensor with the same Smart Port:

from venice import *

motor = Motor(1)
motor.free()
# `motor` is now unusable, but port 1 can be used in another device, such as a `RotationSensor`
rotation_sensor = RotationSensor(1)
function

get_brightness

get_brightness(self) -> float

Returns the current brightness setting of the vision sensor as a percentage.

The returned result should be from 0.0 (0%) to 1.0 (100%).

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

async def main():
# Set brightness to 50%
sensor.set_brightness(0.5)

# Give the sensor time to update.
await vasyncio.Sleep(VisionSensor.UPDATE_INTERVAL_MS, MILLIS)

# Read brightness. Should be 50%, since we just set it.
assert sensor.get_brightness() == 0.5

vasyncio.run(main)
function

get_led_mode

get_led_mode(self) -> LedMode

Returns the user-set behavior of the LED indicator on the sensor.

Raises

  • DeviceError: If there was not a sensor connected to the port, or if a read operation failed, or there was no signature previously set in the slot(s) specified in the VisionCode.

Examples

from venice import *

sensor = VisionSensor(1)

async def main():
# Set the LED to red at 100% brightness.
sensor.set_led_mode(LedMode.Manual(255, 0, 0, 1))

# Give the sensor time to update.
await vasyncio.Sleep(VisionSensor.UPDATE_INTERVAL_MS, MILLIS)

# Check the sensor's reported LED mode. Should be the same as what we just set.
led_mode = sensor.get_led_mode()
assert led_mode == LedMode.Manual(255, 0, 0, 1)

vasyncio.run(main)
function

get_mode

get_mode(self) -> VisionMode

Returns the current detection mode that the sensor is using.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

async def main():
# Place the sensor into "Wi-Fi mode," allowing you to connect to it via a hotspot and
# receive a video stream of its camera from another device.
sensor.set_mode(VisionMode.WIFI)

await vasyncio.Sleep(VisionSensor.UPDATE_INTERVAL_MS, MILLIS)

# Since we just set the mode, we can the mode off the sensor to verify that it's now in
# Wi-Fi mode.
assert sensor.get_mode() == VisionMode.WIFI

vasyncio.run(main)
function

get_object_count

get_object_count(self) -> int

Returns the number of objects detected by the sensor.

Raises

  • DeviceError: If there was not a sensor connected to the port, or if the sensor is in Wi-Fi mode, or if the sensor failed to read an object.

Examples

from venice import *

sensor = VisionSensor(1)

async def main():
# Set a color signature on the sensor's first slot.
sensor.set_signature(1, VisionSignature(10049, 11513, 10781, -425, 1, -212, 4.1))
while True:
object_count = sensor.get_object_count()
print(f"Sensor is currently detecting {object_count} objects.")

await vasyncio.Sleep(VisionSensor.UPDATE_INTERVAL_MS, MILLIS)

vasyncio.run(main)
function

get_objects

get_objects(self) -> tuple[{"cls":"ExprTuple","elements":[{"cls":"ExprName","member":"get_objects","name":"VisionObject"},"..."],"implicit":true}]

Returns a tuple of objects detected by the sensor.

Raises

  • DeviceError: If there was not a sensor connected to the port, or if the sensor is in Wi-Fi mode, or if the sensor failed to read an object.

Examples

With one signature:

from venice import *

sensor = VisionSensor(1)

# Set a color signature on the sensor's first slot.
sensor.set_signature(1, VisionSignature(10049, 11513, 10781, -425, 1, -212, 4.1))

# Scan for detected objects.
for _ in sensor.get_objects():
print("Object detected")

With multiple signatures:

from venice import *

sensor = VisionSensor(1)

# Two color signatures.
sig_1 = VisionSignature(10049, 11513, 10781, -425, 1, -212, 4.1)
sig_2 = VisionSignature(8973, 11143, 10058, -2119, -1053, -1586, 5.4)

# Store the signatures on the sensor.

sensor.set_signature(1, sig_1)
sensor.set_signature(2, sig_2)

# Scan for objects.
for object in sensor.get_objects():
# Identify which signature the detected object matches.
if object.source == DetectionSource.Signature(1):
print(f"Detected object matching sig_1: {object}")
elif object.source == DetectionSource.Signature(2):
print(f"Detected object matching sig_2: {object}")
function

get_signature

get_signature(self, id: int) -> VisionSignature | None

Returns a signature from the sensor's onboard volatile memory.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected. ValueError: If the given signature ID is not in the interval [1, 7].

Examples

from venice import *

sensor = VisionSensor(1)

# Set an example signature in the sensor's first slot.
sensor.set_signature(1, VisionSignature(10049, 11513, -425, 1, -212, 4.1))

# Read signature 1 off the sensor.
# This should be the same as the one we just set.
signature = sensor.get_signature(1)
print(signature)
function

get_signatures

get_signatures(self) -> tuple[{"cls":"ExprTuple","elements":[{"cls":"ExprBinOp","left":{"cls":"ExprName","member":"get_signatures","name":"VisionSignature"},"operator":"|","right":"None"},"..."],"implicit":true}]

Returns all signatures currently stored on the sensor's onboard volatile memory.

Raises

  • DeviceError: If there was not a sensor connected to the port, or if a read operation failed, or there was no signature previously set in the slot(s) specified in the VisionCode.

Examples

from venice import *

sensor = VisionSensor(1)

# A bunch of random color signatures.
sig_1 = VisionSignature(10049, 11513, 10781, -425, 1, -212, 4.1)
sig_2 = VisionSignature(8973, 11143, 10058, -2119, -1053, -1586, 5.4)
sig_3 = VisionSignature(-3665, -2917, -3292, 4135, 10193, 7164, 2.0)
sig_4 = VisionSignature(-5845, -4809, -5328, -5495, -4151, -4822, 3.1)

# Set signatures 1-4.
sensor.set_signature(1, sig_1)
sensor.set_signature(2, sig_2)
sensor.set_signature(3, sig_3)
sensor.set_signature(4, sig_4)

# Read back the signatures from the sensor's memory.
# These should be the signatures that we just set.
signatures = sensor.get_signatures()
for signature in signatures:
if signature:
print(f"Found sig saved on sensor: {signature}")
function

get_white_balance

get_white_balance(self) -> WhiteBalance

Returns the current white balance of the vision sensor as an RGB color.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

async def main():
# Set white balance to manual.
sensor.set_white_balance(WhiteBalance.Manual(255, 255, 255))

# Give the sensor time to update.
await vasyncio.Sleep(VisionSensor.UPDATE_INTERVAL_MS, MILLIS)

# Read white balance. Should be the same as what we just set.
white_balance = sensor.get_white_balance()
assert white_balance == WhiteBalance.Manual(255, 255, 255)

vasyncio.run(main)
function

set_brightness

set_brightness(self, brightness: float) -> None

Sets the brightness percentage of the vision sensor. Should be between 0.0 and 1.0.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

# Set brightness to 50%
sensor.set_brightness(0.5)
function

set_led_mode

set_led_mode(self, mode: LedMode) -> None

Configure the behavior of the LED indicator on the sensor.

The default behavior is represented by LedMode.Auto, which will display the color of the most prominent detected object's signature color. Alternatively, the LED can be configured to display a single RGB color.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

# Set the LED to red at 100% brightness.
sensor.set_led_mode(LedMode.Manual(255, 0, 0, 1))
function

set_mode

set_mode(self, mode: VisionMode) -> None

Sets the vision sensor's detection mode. See VisionMode for more information on what each mode does.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

# Place the sensor into "Wi-Fi mode," allowing you to connect to it via a hotspot and
# receive a video stream of its camera from another device.
sensor.set_mode(VisionMode.WIFI)
function

set_signature

set_signature(self, id: int, signature: VisionSignature) -> None

Adds a detection signature to the sensor's onboard memory.

This signature will be used to identify objects when using VisionSensor.get_objects.

The sensor can store up to 7 unique signatures, with each signature slot denoted by the id parameter. If a signature with an ID matching an existing signature on the sensor is added, then the existing signature will be overwritten with the new one.

Volatile Memory

The memory on the Vision Sensor is volatile and will therefore be wiped when the sensor loses power. As a result, this function should be called every time the sensor is used on program start.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected. ValueError: If the given signature ID is not in the interval [1, 7].

Examples

from venice import *

sensor = VisionSensor(1)

# These signatures can be generated using VEX's vision utility
example_signature = VisionSignature(10049, 11513, 10781, -425, 1, -212, 4.1)

# Set signature 1 on the sensor.
sensor.set_signature(1, example_signature)
function

set_white_balance

set_white_balance(self, balance: WhiteBalance) -> None

Sets the white balance of the vision sensor.

White balance can be either automatically set or manually set through an RGB color.

Raises

DeviceError: If no device is connected to the port, or if the wrong type of device is connected.

Examples

from venice import *

sensor = VisionSensor(1)

# Set white balance to manual.
sensor.set_white_balance(WhiteBalance.Manual(255, 255, 255))
attribute

DIAGONAL_FOV

DIAGONAL_FOV: float

The diagonal FOV of the vision sensor in degrees.

attribute

HORIZONTAL_FOV

HORIZONTAL_FOV: float

The horizontal FOV of the vision sensor in degrees.

attribute

HORIZONTAL_RESOLUTION

HORIZONTAL_RESOLUTION: int

The horizontal resolution of the vision sensor.

This value is based on the VISION_FOV_WIDTH macro constant in PROS.

attribute

UPDATE_INTERVAL_MS

UPDATE_INTERVAL_MS: int

The update rate of the vision sensor, in milliseconds.

attribute

VERTICAL_FOV

VERTICAL_FOV: float

The vertical FOV of the vision sensor in degrees.

attribute

VERTICAL_RESOLUTION

VERTICAL_RESOLUTION: int

The vertical resolution of the vision sensor.

This value is based on the VISION_FOV_HEIGHT macro constant in PROS.

class

VisionSignature

class VisionSignature
function

__init__

__init__(self, u_min: int, u_max: int, u_mean: int, v_min: int, v_max: int, v_mean: int, range: float) -> None
attribute

flags

flags: int
attribute

range

range: float
attribute

u_max

u_max: int
attribute

u_mean

u_mean: int
attribute

u_min

u_min: int
attribute

v_max

v_max: int
attribute

v_mean

v_mean: int
attribute

v_min

v_min: int
class

WhiteBalance

class WhiteBalance
class

Manual

class Manual
function

__init__

__init__(self, r: int, g: int, b: int) -> None
attribute

b

b: int
attribute

g

g: int
attribute

r

r: int
function

__init__

__init__(self) -> None
attribute

Auto

Auto: type[Auto]
attribute

StartupAuto

StartupAuto: type[StartupAuto]
module

battery

source ↗
module battery

Robot battery information.

This module provides APIs for retrieving information about the robot's battery and state of charge.

function

get_capacity

get_capacity() -> float

Returns the charge capacity of the robot's battery in the range of [0.0, 1.0].

A value of 0.0 indicates a completely empty battery, while a value of 1.0 indicates a fully-charged battery.

Examples

from venice import *

capacity = battery.get_capacity()
print(f"Battery at {capacity:.0%} capacity")

if capacity < 0.2:
print("Warning: Low battery!")
function

get_current

get_current() -> float

Returns the electric current of the robot's battery in amps.

Maximum current draw on the V5 battery is 20 Amps.

Examples

from venice import *

current = battery.get_current()

print(f"Drawing {current} amps")
function

get_temperature

get_temperature() -> int

Returns the internal temperature of the robot's battery in degrees Celsius.

Examples

from venice import *

temp = battery.get_temperature()
print(f"Battery temperature: {temp}°C")

# Check if battery is too hot
if temp > 45:
print("Warning: Battery temperature critical!")
function

get_voltage

get_voltage() -> float

Returns the robot's battery voltage in volts.

Nominal battery voltage on the V5 brain is 12.8V.

Examples

from venice import *

voltage = battery.get_voltage()
print("Battery voltage: {voltage} V")
module

display

source ↗
module display

Display and touchscreen input.

Contains user calls to the V5 Brain display for touching and displaying graphics.

class

FontFamily

class FontFamily
attribute

MONOSPACE

MONOSPACE: FontFamily
attribute

PROPORTIONAL

PROPORTIONAL: FontFamily
class

FontSize

class FontSize
function

__init__

__init__(self, numerator: int, denominator: int) -> None
attribute

denominator

denominator: int
attribute

EXTRA_LARGE

EXTRA_LARGE: FontSize
attribute

EXTRA_SMALL

EXTRA_SMALL: FontSize
attribute

FULL

FULL: FontSize
attribute

LARGE

LARGE: FontSize
attribute

MEDIUM

MEDIUM: FontSize
attribute

numerator

numerator: int
attribute

SMALL

SMALL: FontSize
class

RenderMode

class RenderMode
attribute

DOUBLE_BUFFERED

DOUBLE_BUFFERED: RenderMode
attribute

IMMEDIATE

IMMEDIATE: RenderMode
class

TouchEvent

class TouchEvent
attribute

is_held

is_held: bool
attribute

is_now_pressed

is_now_pressed: bool
attribute

is_pressed

is_pressed: bool
attribute

is_released

is_released: bool
attribute

press_count

press_count: int
attribute

release_count

release_count: int
attribute

x

x: int
attribute

y

y: int
function

draw_buffer

draw_buffer(x: int, y: int, width: int, height: int, buffer: Any) -> None
function

draw_circle

draw_circle(x: int, y: int, radius: int, color: Color) -> None
function

draw_line

draw_line(start_x: int, start_y: int, end_x: int, end_y: int, color: Color) -> None
function

draw_pixel

draw_pixel(x: int, y: int, color: Color) -> None
function

draw_rect

draw_rect(x: int, y: int, width: int, height: int, color: Color) -> None
function

draw_text

draw_text(text: str, x: int, y: int, font_size: FontSize = FontSize.MEDIUM, font_family: FontFamily = FontFamily.PROPORTIONAL, color: Color = Color.WHITE, bg_color: Color | None = None) -> None
function

erase

erase(color: Color) -> None
function

fill_circle

fill_circle(x: int, y: int, radius: int, color: Color) -> None
function

fill_rect

fill_rect(x: int, y: int, width: int, height: int, color: Color) -> None
function

get_touch_status

get_touch_status() -> TouchEvent
function

is_held

is_held() -> bool
function

is_now_pressed

is_now_pressed() -> bool
function

is_pressed

is_pressed() -> bool
function

is_released

is_released() -> bool
function

print

print(values: object = (), sep: str =  , end: str = \n) -> None
function

render

render() -> None
function

scroll

scroll(start: int, offset: int) -> None
function

scroll_region

scroll_region(x: int, y: int, width: int, height: int, offset: int) -> None
function

set_render_mode

set_render_mode(render_mode: RenderMode) -> None
alias

Color

Color = venice.Color
module

vasyncio

source ↗
module vasyncio

Venice implements its own async runtime on top of Micropython. vasyncio provides primitives for working with async Python in Venice.

class

EventLoop

class EventLoop
function

__init__

__init__(self) -> None
function

run

run(self) -> None
function

spawn

spawn(self, coro: Any) -> Task
class

Sleep

class Sleep
function

__init__

__init__(self, interval: float, unit: TimeUnit) -> None
class

Task

class Task
function

get_running_loop

get_running_loop() -> EventLoop
function

run

run(coro: Any) -> None
function

spawn

spawn(coro: Any) -> Task
alias

TimeUnit

TimeUnit = venice.TimeUnit
Home Learn API Discord GitHub