3.7 - Swinging Servo

In this kit, in addition to LED and passive buzzer, there is also a device controlled by PWM signal, Servo.

Servo is a position (angle) servo device, which is suitable for those control systems that require constant angle changes and can be maintained. It has been widely used in high-end remote control toys, such as airplanes, submarine models, and remote control robots.

Now, try to make the servo sway!

Schematic

sch_servo

Wiring

wiring_servo

  • Orange wire is signal and connected to GP15.

  • Red wire is VCC and connected to VBUS(5V).

  • Brown wire is GND and connected to GND.

Code

Note

  • You can open the file 3.7_swinging_servo.ino under the path of kepler-kit-main/arduino/3.7_swinging_servo.

  • Or copy this code into Arduino IDE.

  • For detailed tutorials, please refer to Open & Run Code Directly.

  • Or run this code directly in the Arduino Web Editor.

Don’t forget to select the Raspberry Pi Pico W board and the correct port before clicking the Upload button.

When the program is running, we can see the Servo Arm swinging back and forth from 0° to 180°.

How it works?

By calling the library Servo.h, you can drive the servo easily.

#include <Servo.h>

Library Functions:

Servo

Create Servo object to control a servo.

uint8_t attach(int pin);

Turn a pin into a servo driver. Calls pinMode. Returns 0 on failure.

void detach();

Release a pin from servo driving.

void write(int value);

Set the angle of the servo in degrees, 0 to 180.

int read();

Return that value set with the last write().

bool attached();

Return 1 if the servo is currently attached.