accessories/
accessories.rs

1#![no_std]
2#![no_main]
3
4extern crate alloc;
5
6use alloc::sync::Arc;
7use core::time::Duration;
8
9use pros::{
10    core::sync::Mutex,
11    devices::{
12        smart::vision::{LedMode, VisionZeroPoint},
13        Controller,
14    },
15    prelude::*,
16};
17
18struct ExampleRobot {
19    motor: Arc<Mutex<Motor>>,
20    vision: VisionSensor,
21}
22impl ExampleRobot {
23    pub fn new(peripherals: Peripherals) -> Self {
24        Self {
25            motor: Arc::new(Mutex::new(
26                Motor::new(peripherals.port_2, Gearset::Green, Direction::Forward).unwrap(),
27            )),
28            vision: VisionSensor::new(peripherals.port_9, VisionZeroPoint::Center).unwrap(),
29        }
30    }
31}
32
33impl AsyncRobot for ExampleRobot {
34    async fn opcontrol(&mut self) -> Result {
35        let handle = pros::async_runtime::spawn(async {
36            for _ in 0..5 {
37                println!("Hello from async!");
38                sleep(Duration::from_millis(1000)).await;
39            }
40        });
41
42        handle.await;
43
44        // Create a controller, specifically controller 1.
45        let controller = Controller::Master;
46
47        self.vision.set_led(LedMode::On(Rgb::new(0, 0, 255)));
48
49        // Spawn a new task that will print whether or not the motor is stopped constantly.
50        pros_core::task::spawn({
51            let motor = Arc::clone(&self.motor); // Obtain a shared reference to our motor to safely share between tasks.
52
53            move || loop {
54                println!("Motor stopped? {}", motor.lock().velocity() < 2);
55
56                // Sleep the task as to not steal processing time from the OS.
57                // This should always be done in any loop, including loops in the main task.
58                // Because this is a real FreeRTOS task this is not the sleep function used elsewhere in this example.
59                // This sleep function will block the entire task, including the async executor! (There isn't one running here, but there is in the main task.)
60                delay(Duration::from_millis(Motor::DATA_READ_RATE));
61            }
62        });
63
64        loop {
65            // Set the motors output with how far up or down the right joystick is pushed.
66            // Set output takes a float from -1 to 1 that is scaled to -12 to 12 volts.
67            self.motor
68                .lock()
69                .set_voltage(Motor::MAX_VOLTAGE * controller.state()?.joysticks.right.y)?;
70
71            // println!("pid out {}", pid.update(10.0, motor.position().into_degrees() as f32));
72            println!(
73                "Vision objs {}",
74                self.vision.nth_largest_object(0)?.middle_x
75            );
76
77            // Once again, sleep.
78            sleep(Duration::from_millis(20)).await;
79        }
80    }
81}
82async_robot!(
83    ExampleRobot,
84    ExampleRobot::new(Peripherals::take().unwrap())
85);