Robotics & Arduino
Lesson 2 · Refinement

The servo · Putting it all together

Put it all together.

A target. A position.

We can control the width of a pulse to request a position.
We can use a potentiometer to check the actual position.

Code. Switches. Direction.

We can use code to turn electronic switches ON and OFF.

We can connect those switches in an H-bridge
to control the motor’s direction.

Now combine them.

We can make a motor turn to a specific target position — within our chosen tolerance.

Check the position. Compare it with the target.
Move, stop, and check again.

Consider this pseudocode.

tolerance = SMALL_ALLOWED_DIFFERENCE

directions:
STOP
FORWARD → S1 + S4
REVERSE → S2 + S3

repeat forever:

    // Receive the latest requested position.
    positionSignal = readPWM()
    targetPosition = translatePWMtoPot(positionSignal)

    // Check where we actually are.
    currentPosition = readPot()

    // Are we close enough?
    if abs(targetPosition - currentPosition) <= tolerance:
        direction = STOP
        turnMotorOff()

    else:
        // Which way must we move?
        if currentPosition < targetPosition:
            direction = FORWARD
        else:
            direction = REVERSE

        turnMotorOn(direction)

    wait briefly

Conceptual pseudocode, not an Arduino sketch. Here, readPWM() reads the latest command pulse width; translatePWMtoPot() puts it on the same scale as the pot reading.

When changing direction, turnMotorOn(direction) switches the old pair OFF before enabling the new pair.

Request. Measure. Compare. Correct.