9. Servo Control with Knob Potentiometer

Objective

In this challenge, you will learn how to utilize a servo and control it with a knob potentiometer. A knob potentiometer is a variable resistor that changes resistance when you turn the knob (a voltage divider).

Components

  • 1 Metro M0 Express

  • 1 breadboard

  • 1 micro servo

  • 1 knob potentiometer

  • Wires

Wiring

Follow the circuit diagram provided to wire the Metro M0 Express.

Coding/Programming

import time

import board

import pulseio

from adafruit_motor import servo

from analogio import AnalogIn

import simpleio


# create a PWMOut object on Pin D5.

pwm = pulseio.PWMOut(board.D5, duty_cycle=2 ** 15, frequency=50)

# Create a servo object, my_servo.

my_servo = servo.Servo(pwm)

analog_in = AnalogIn(__________)


while True:

pot = analog_in.value

angle = simpleio.map_range(pot, 0, 65535, 0, 180)

my_servo.angle = angle

time.sleep(0.1)

Note: a micro-servo typically has a degree range of 0 to 180 degrees.

Solution

import time

import board

import pulseio

from adafruit_motor import servo

from analogio import AnalogIn

import simpleio

# create a PWMOut object on Pin D5.

pwm = pulseio.PWMOut(board.D5, duty_cycle=2 ** 15, frequency=50)

# Create a servo object, my_servo.

my_servo = servo.Servo(pwm)

analog_in = AnalogIn(board.A1)

while True:

pot = analog_in.value

angle = simpleio.map_range(pot, 0, 65535, 0, 180)

my_servo.angle = angle

time.sleep(0.1)