Struct OpticalSensor

Source
pub struct OpticalSensor { /* private fields */ }
Expand description

An optical sensor plugged into a Smart Port.

Implementations§

Source§

impl OpticalSensor

Source

pub const MIN_INTEGRATION_TIME: Duration

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

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

Source

pub const MAX_INTEGRATION_TIME: Duration

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

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

Source

pub const GESTURE_UPDATE_INTERVAL: Duration

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

Source

pub fn new(port: SmartPort) -> Self

Creates a new optical sensor from a SmartPort.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);
}
Source

pub fn led_brightness(&self) -> Result<f64, PortError>

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

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    if let Ok(brightness) = sensor.led_brightness() {
        println!("LED brightness: {:.1}%", brightness * 100.0);
    }
}
Source

pub fn set_led_brightness(&mut self, brightness: f64) -> Result<(), PortError>

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

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

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;
use core::time::Duration;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let mut sensor = OpticalSensor::new(peripherals.port_1);

    // Blink LED 3 times
    for _ in 0..3 {
        // Turn LED on
        if let Err(e) = sensor.set_led_brightness(1.0) {
            println!("Failed to turn LED on: {:?}", e);
        }

        sleep(Duration::from_millis(250)).await;

        // Turn LED off
        if let Err(e) = sensor.set_led_brightness(0.0) {
            println!("Failed to turn LED off: {:?}", e);
        }

        sleep(Duration::from_millis(250)).await;
    }
}
Source

pub fn integration_time(&self) -> Result<Duration, PortError>

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.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;
use core::time::Duration;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let mut sensor = OpticalSensor::new(peripherals.port_1);

    // Set integration time to 50 milliseconds.
    _ = sensor.set_integration_time(Duration::from_millis(50));

    // Log out the new integration time.
    if let Ok(time) = sensor.integration_time() {
        println!("Integration time: {:?}", time);
    }
}
Source

pub fn set_integration_time(&mut self, time: Duration) -> Result<(), PortError>

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.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;
use core::time::Duration;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let mut sensor = OpticalSensor::new(peripherals.port_1);

    // Set integration time to 50 milliseconds.
    _ = sensor.set_integration_time(Duration::from_millis(50));
}
Source

pub fn hue(&self) -> Result<f64, PortError>

Returns the detected color’s hue.

Hue has a range of 0 to 359.999.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    if let Ok(hue) = sensor.hue() {
        println!("Detected color hue: {:.1}°", hue);

        // Classify the color based on hue angle
        let color = match hue as u32 {
            0..=30 => "Red",
            31..=90 => "Yellow",
            91..=150 => "Green",
            151..=210 => "Cyan",
            211..=270 => "Blue",
            271..=330 => "Magenta",
            _ => "Red", // 331-359 wraps back to red
        };

        println!("Color: {}", color);
    }
}
Source

pub fn saturation(&self) -> Result<f64, PortError>

Returns the detected color’s saturation.

Saturation has a range 0 to 1.0.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    if let Ok(saturation) = sensor.saturation() {
        println!("Color saturation: {}%", saturation * 100.0);

        // Check if color is muted or vibrant
        if saturation < 0.5 {
            println!("Muted color detected");
        } else {
            println!("Vibrant color detected");
        }
    }
}
Source

pub fn brightness(&self) -> Result<f64, PortError>

Returns the detected color’s brightness.

Brightness values range from 0 to 1.0.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    if let Ok(brightness) = sensor.brightness() {
        println!("Color brightness: {}%", brightness * 100.0);

        // Check if color is dark or bright
        if brightness < 0.3 {
            println!("Dark color detected");
        } else if brightness > 0.7 {
            println!("Bright color detected");
        } else {
            println!("Medium brightness color detected");
        }
    }
}
Source

pub fn proximity(&self) -> Result<f64, PortError>

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.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    // Monitor proximity with thresholds
    if let Ok(prox) = sensor.proximity() {
        match prox {
            x if x > 0.8 => println!("Object very close!"),
            x if x > 0.5 => println!("Object nearby"),
            x if x > 0.2 => println!("Object detected"),
            _ => println!("No object in range"),
        }
    }
}
Source

pub fn color(&self) -> Result<OpticalRgb, PortError>

Returns the processed RGB color data from the sensor.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    // Color detection with RGB values
    if let Ok(rgb) = sensor.color() {
        println!("Color reading: R={}, G={}, B={}", rgb.red, rgb.green, rgb.blue);

        // Example: Check if object is primarily red
        // Note that you should probably use `OpticalSensor::hue` instead for this.
        if rgb.red > rgb.green && rgb.red > rgb.blue {
            println!("Object is primarily red!");
        }
    }
}
Source

pub fn raw_color(&self) -> Result<OpticalRaw, PortError>

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

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

Source

pub fn last_gesture(&self) -> Result<Option<Gesture>, PortError>

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

Gesture data updates every 500 milliseconds.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;
use core::time::Duration;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1);

    // Print the details of the last detected gesture.
    loop {
        if let Ok(Some(gesture)) = sensor.last_gesture() {
            println!("Direction: {:?}", gesture.direction);
        }

        sleep(Duration::from_millis(25)).await;
    }
}
Source

pub fn status(&self) -> Result<u32, PortError>

Returns the internal status code of the optical sensor.

§Errors

An error is returned if an optical sensor is not currently connected to the Smart Port.

§Examples
use vexide::prelude::*;

#[vexide::main]
async fn main(peripherals: Peripherals) {
    let sensor = OpticalSensor::new(peripherals.port_1, Direction::Forward);

    if let Ok(status) = sensor.status() {
        println!("Status: {:b}", status);
    }
}

Trait Implementations§

Source§

impl Debug for OpticalSensor

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<OpticalSensor> for SmartPort

Source§

fn from(device: OpticalSensor) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for OpticalSensor

Source§

fn eq(&self, other: &OpticalSensor) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

const fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl SmartDevice for OpticalSensor

Source§

const UPDATE_INTERVAL: Duration

The interval at which the V5 brain reads packets from Smart devices.
Source§

fn port_number(&self) -> u8

Returns the port number of the SmartPort this device is registered on. Read more
Source§

fn device_type(&self) -> SmartDeviceType

Returns the variant of SmartDeviceType that this device is associated with. Read more
Source§

fn is_connected(&self) -> bool

Determine if this device type is currently connected to the SmartPort that it’s registered to. Read more
Source§

fn timestamp(&self) -> Result<SmartDeviceTimestamp, PortError>

Returns the timestamp recorded by this device’s internal clock. Read more
Source§

fn validate_port(&self) -> Result<(), PortError>

Verify that the device type is currently plugged into this port, returning an appropriate PortError if not available. Read more
Source§

impl Eq for OpticalSensor

Source§

impl Send for OpticalSensor

Source§

impl StructuralPartialEq for OpticalSensor

Source§

impl Sync for OpticalSensor

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.