In this part, we'll use the configured PWM from the previous part to sweep a servo motor through 180°.
Create a new project file pwm.rs under examples, copy the contents of the last part into it and empty the loop section.
Table of contents
- Requirements
Implementation
- Connections Diagram
- sweep
- Final Code
Requirements
- 1 x Raspberry Pico board
- 1 x USB Cable type 2.0
- 9 x M-M jumper wires
- 2 x Mini Breadboards
- 1 x SG90 Servo Motor
Implementation
Connections Diagram
The electrical connections of the modules will be as shown below.
We can refactor the above above application code into a function sweep as below.
pub fn sweep(pwm: &pwm2, mut degrees: u16) {
const BASE: u16 = 1500;// here pwm at position 0 degrees
degrees = BASE + (degrees * 24);// ~28: movt by 1 degree
unsafe {
pwm.cc().modify(|_, w| w.a().bits(degrees) );// move by one degree * no of degrees
}
}
Import the pwm channel.
use rp2040_pac::pwm::ch::CH;
Our application code will now be:
// Servo sweep through 180
for deg in 0..=180 {
sweep(pwm2, deg);
delay.delay_ms(10);
if deg == 180 {
delay.delay_ms(500);
for deg in (0..=180).rev() {
sweep(pwm2, deg);
delay.delay_ms(10);
}
}
delay.delay_ms(500);
Flashing this into the Pico should have the same sweep results as before.
Final Code
The final code up to this point can be found here.
In the next part we apply the PWM in our overall project
SOCIAL SHARE CARD GENERATOR