|
| 1 | +#![no_std] |
| 2 | + |
| 3 | +use libtock_platform::{ErrorCode, Syscalls}; |
| 4 | + |
| 5 | +pub struct Servo<S: Syscalls>(S); |
| 6 | + |
| 7 | +impl<S: Syscalls> Servo<S> { |
| 8 | + /// Check whether the driver exists. |
| 9 | + pub fn exists() -> Result<(), ErrorCode> { |
| 10 | + let val = S::command(DRIVER_NUM, EXISTS, 0, 0).is_success(); |
| 11 | + if val { |
| 12 | + Ok(()) |
| 13 | + } else { |
| 14 | + Err(ErrorCode::Fail) |
| 15 | + } |
| 16 | + } |
| 17 | + /// Returns the number of the servomotors available. |
| 18 | + pub fn count() -> Result<u32, ErrorCode> { |
| 19 | + S::command(DRIVER_NUM, SERVO_COUNT, 0, 0).to_result() |
| 20 | + } |
| 21 | + |
| 22 | + /// Changes the angle of the servo. |
| 23 | + /// |
| 24 | + /// # Arguments |
| 25 | + /// - `angle` - the variable that receives the angle |
| 26 | + /// (in degrees from 0 to 180) from the servo driver. |
| 27 | + /// - `index` - the variable that receives the index of the servomotor. |
| 28 | + /// |
| 29 | + /// # Return values: |
| 30 | + /// - `Ok(())`: The attempt at changing the angle was successful. |
| 31 | + /// |
| 32 | + /// # Errors: |
| 33 | + /// - `FAIL`: Cannot change the angle. |
| 34 | + /// - `INVAL`: The value exceeds u16, indicating it's incorrect |
| 35 | + /// since servomotors can only have a maximum of 360 degrees. |
| 36 | + /// - `NODEVICE`: The index exceeds the number of servomotors provided. |
| 37 | + pub fn set_angle(index: u32, angle: u32) -> Result<(), ErrorCode> { |
| 38 | + S::command(DRIVER_NUM, SET_ANGLE, index, angle).to_result() |
| 39 | + } |
| 40 | + |
| 41 | + /// Returns the angle of the servo. |
| 42 | + /// |
| 43 | + /// # Arguments |
| 44 | + /// - `index` - the variable that receives the index of the servomotor. |
| 45 | + /// |
| 46 | + /// # Return values: |
| 47 | + /// - `angle`: The value, in angles from 0 to 360, of the servo. |
| 48 | + /// |
| 49 | + /// # Errors: |
| 50 | + /// - `NOSUPPORT`: The servo cannot return its angle. |
| 51 | + /// - `NODEVICE`: The index exceeds the number of servomotors provided. |
| 52 | + pub fn get_angle(index: u32) -> Result<u32, ErrorCode> { |
| 53 | + S::command(DRIVER_NUM, GET_ANGLE, index, 0).to_result() |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests; |
| 59 | + |
| 60 | +// ----------------------------------------------------------------------------- |
| 61 | +// Driver number and command IDs |
| 62 | +// ----------------------------------------------------------------------------- |
| 63 | + |
| 64 | +const DRIVER_NUM: u32 = 0x90009; |
| 65 | + |
| 66 | +// Command IDs |
| 67 | +const EXISTS: u32 = 0; |
| 68 | +const SERVO_COUNT: u32 = 1; |
| 69 | +const SET_ANGLE: u32 = 2; |
| 70 | +const GET_ANGLE: u32 = 3; |
0 commit comments