Skip to content

Commit 35167d5

Browse files
authored
Implement Servo set_position (#28)
1 parent b7d4865 commit 35167d5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/output_devices.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,29 @@ impl Servo {
734734
}
735735
}
736736

737+
/// Set servo to any position between min and max.
738+
/// value must be between -1 (the minimun position) and +1 (the maximum position).
739+
pub fn set_position(&mut self, value: f64) {
740+
if value >= -1.0 && value <= 1.0 {
741+
// Map value form [-1, 1] to [min_pulse_width, max_pulse_width] linearly
742+
let range: f64 = (self.max_pulse_width - self.min_pulse_width) as f64;
743+
let pulse_width: u64 = self.min_pulse_width + (((value + 1.0)/2.0) * range).round() as u64;
744+
if self
745+
.pin
746+
.set_pwm(
747+
Duration::from_millis(self.frame_width),
748+
Duration::from_micros(pulse_width),
749+
)
750+
.is_err()
751+
{
752+
println!("Failed to set servo to a new position");
753+
}
754+
}
755+
else {
756+
println!("set_position value must be between -1 and 1");
757+
}
758+
}
759+
737760
/// Set the servo's minimum pulse width
738761
pub fn set_min_pulse_width(&mut self, value: u64) {
739762
if value >= self.max_pulse_width {

0 commit comments

Comments
 (0)