1Where Lab 5 Sits
So far you have controlled how fast and how bright. An LED had two states and a duty cycle; a DC motor had a speed that rose with duty cycle. In neither case did you ever know where anything was.
This week both motors are about position. A stepper moves in discrete, countable increments, so if you count steps you know the angle without measuring it. A servo contains its own feedback loop and holds whatever angle you command. They reach the same goal by opposite routes, and the contrast is the point of the lab.
A stepper is open loop: you command a sequence and trust that the motor followed it. A servo is closed loop: you command a position and the motor's internal electronics work to achieve it. Open loop is precise but silently fails when overloaded; closed loop corrects itself but only within its own range and resolution.
| Lab 5 task | What you do | Concept & section |
|---|---|---|
| 1 | Read the NEMA 17 and driver datasheets; identify driver pins and the four motor wires; draw a schematic | Coil sets, bipolar windings, driver role (§2, §5) |
| 2 | Create full-step and half-step logic tables, clockwise and counter-clockwise | How a rotating field is built from coil polarities (§3) |
| 3 | Build and run; two full rotations each way, both sequences; report runtime, revolutions, period, frequency, angle per step, total steps | Step angle and timing arithmetic (§4, §6) |
| 4 | Connect the MG996R servo; rotate to 30°; verify with a protractor | Pulse width to angle (§7) |
| 5 | Full range; duty-vs-angle table; fitting formula; accuracy; reject out-of-range input | Calibration and input validation (§8, §9) |
2How a Stepper Motor Works
2.1 The physical picture
A stepper has a permanent-magnet rotor and a stator carrying two independent coil sets, conventionally called A and B. Energising a coil creates a magnetic field; the rotor turns until its poles align with that field, and then holds there. Energise a different combination and the field direction moves, so the rotor follows it to a new alignment.
Rotation is therefore not continuous. It is a sequence of discrete jumps between stable alignments — and because the alignments are fixed by the motor's physical geometry, each jump is the same size every time. That repeatability is what makes the motor useful: counting steps is equivalent to measuring angle, with no sensor at all.
2.2 Four wires, two coils
A bipolar stepper such as the NEMA 17 has four leads: two per coil. Task 1 asks you to identify which coloured wire belongs to which coil, and this is worth doing carefully because guessing costs you the whole afternoon.
With the motor disconnected, measure resistance between pairs of leads. Two leads from the same coil show a low resistance — typically a few ohms. Two leads from different coils show an open circuit. That single test partitions the four wires into two pairs unambiguously.
A second, satisfying check: short two leads together and turn the shaft by hand. It becomes noticeably harder to turn, because you have completed a circuit and the motor is now generating current into a short. If that happens, those two leads are one coil. Confirm the pairing with the datasheet's colour code and record both in your report.
Which lead of a pair is which end only sets the direction of rotation. If the motor turns the wrong way, swap one pair.
3Full Step and Half Step
Task 2 asks you to create the logic tables, so this section gives you the rule for constructing them rather than the finished tables.
3.1 The organising principle
Each coil can be in one of three states: energised one way, energised the other way, or off. Write the control state as the four driver inputs (A1, B1, A2, B2) in the notation of your driver's datasheet. The field direction is the vector sum of the two coils' contributions, so:
- Energising one coil alone points the field along that coil's axis.
- Energising both coils together points the field along the diagonal, midway between the two axes, and with a larger magnitude — the vector sum of two equal perpendicular contributions is √2 times either one.
- Reversing a coil's polarity flips its contribution through 180°.
Full step uses only one kind of state throughout, so every position is the same distance from the last. There are four such states before the pattern repeats. Two variants exist — one energising a single coil at a time (lower holding torque, lower current), one energising both coils at every step (higher torque, more current, and the rotor sits on the diagonals). Pick one, say which you picked, and be consistent.
Half step alternates between the two kinds of state, so the field lands on the axes and the diagonals in turn. That doubles the number of positions per electrical cycle and halves the step angle, at the cost of a torque that alternates between two values.
Direction is simply the order in which you walk the table. Traverse it one way for clockwise, reverse the traversal for counter-clockwise. You do not need two separate tables — you need one table and an index that counts up or down, and saying so explicitly is a good observation for the report.
Sketch the field vector for each row as you build the table. If consecutive rows do not advance by a constant angle in a consistent direction, the sequence is wrong — and you will see that on paper long before the motor buzzes at you on the bench.
3.2 What each choice costs
| Mode | Step angle | Steps per revolution | Trade-off |
|---|---|---|---|
| Full step | θfull | S | Higher torque per step, simpler table, coarser resolution. Can be noisier, and is more prone to resonance at particular step rates. |
| Half step | θfull/2 | 2S | Twice the resolution and noticeably smoother, but torque alternates between the one-coil and two-coil values, and the step rate must double for the same speed. |
Both modes are required in Task 3, and running the same physical rotation in each is the cleanest way to demonstrate the difference. Listen to the motor as well as watching it — half-stepping is audibly smoother, and that observation belongs in the report.
4Step Angle, Revolutions and Timing
4.1 The arithmetic
Everything Task 3 asks you to report follows from two numbers: the step angle and the step rate.
where S is the number of steps in one full revolution in the mode you are using. If a delay td separates consecutive steps, then
Get the full-step angle from the NEMA 17 datasheet, then verify it by measurement: mark the shaft, command a known number of steps, and see whether it ends up where the arithmetic says it should. Command exactly one revolution's worth and check that the mark returns to its starting position.
Two things can make the measured figure differ from the naive calculation, and both are worth catching. A gearbox multiplies the steps per output revolution by the gear ratio. And your driver may be configured for microstepping, subdividing each full step further — check its mode pins, because a driver silently set to 1/8 microstepping will make every angle in your report wrong by a factor of eight while remaining perfectly self-consistent.
Task 3 explicitly asks you to compare the reported values with your observations. This is why.
4.2 Speed is limited by physics, not by code
You cannot step arbitrarily fast. Three effects set the ceiling:
- Torque falls with step rate. Each coil is an inductor; at high step rates the current has less time to build before the next transition, so the field is weaker and the torque drops.
- Missed steps. If the rotor cannot reach the next alignment before the field moves again, it slips. The motor buzzes, stalls, or turns erratically — and crucially, the software has no idea. Your step count says one thing, the shaft says another. This is the characteristic failure of open-loop control, and demonstrating it deliberately makes an excellent report figure.
- Resonance. At particular step rates the rotor's oscillation about each new position couples with the stepping rate and the motor loses torque badly. It is usually a narrow band, and stepping through it quickly avoids it.
If the motor misbehaves, increase td first. Most “the stepper does not work” problems are simply stepping too fast.
(a) A motor has a 1.8° full step. How many full steps make one revolution? How many half steps?
(b) Using that motor in half-step mode with td = 5 ms, find the step frequency, the time for one revolution, and the RPM.
(c) How many half steps are needed for two complete revolutions, and how long will that take at the same delay?
(d) You command 400 half steps and the shaft turns exactly one revolution, but the datasheet's full-step angle predicted two. Give two possible explanations and a test that distinguishes them.
5The Driver Chip
The same argument as Lab 4, one level up. A stepper coil draws far more current than a GPIO pin can supply, and it is inductive, so it needs the same treatment a DC motor did — except that each of the two coils must be driven in both polarities.
Reversing current through a coil requires four switches per coil, an arrangement called an H-bridge: two switches connect the coil ends to the supply, two to ground, and closing the appropriate diagonal pair sets the current direction. A bipolar stepper driver contains two H-bridges, one per coil, plus protection diodes and often current regulation — which is why you use a driver chip rather than building eight transistor switches.
Your schematic must show, and your report must list:
- Which driver pins are logic inputs from the Pi, and which are coil outputs to the motor.
- The motor supply pin and its voltage, and the logic supply pin if the chip has a separate one.
- Any enable pin, and whether it is active high or active low. A driver left disabled is a common and very quiet failure.
- Any mode pins selecting full-step or microstepping, and the setting you used (§4.1).
- The current limit, if the driver has one, and how it is set.
- The ground pins — and, as in Lab 4, that the Pi's ground and the motor supply's ground are tied together.
Breaking a coil circuit while current is flowing is exactly the inductive interruption of Lab 4's Equation (2), and it destroys driver chips reliably. Power down before changing any motor connection. Equally: the coils draw current whenever they are energised and holding position, even at a standstill, so the driver and motor get warm during normal operation. Warm is expected; too hot to touch means the current limit is set too high.
6Reporting the Stepper Numbers
Task 3 asks your program to report runtime, number of revolutions, period, frequency, rotation angle per step, and total number of steps — and then to compare those against what you actually observe. The comparison is the graded part, so make it easy on yourself:
| Quantity | Where it comes from | How to check it |
|---|---|---|
| Total steps | Counted by your program | Compare with Equation (1) for the revolutions you intended |
| Angle per step | Datasheet, divided by any microstep setting | Mark the shaft; command a known number of steps; measure with a protractor |
| Revolutions | Steps divided by S | Count turns of the shaft mark by eye |
| Runtime | time.perf_counter() around the loop | Time it with a stopwatch — a crude check that catches gross errors |
| Period and frequency | Equation (2) | Probe one coil-driver input on the scope and read the frequency directly |
S × td is a lower bound. Every loop iteration also spends time on four GPIO.output() calls, index arithmetic and the scheduler — exactly the overhead analysed in §5 of the Lecture 03 notes. Measured runtime will therefore come out longer than predicted, by an amount that grows in relative terms as td shrinks.
Quantifying that gap, and attributing it correctly, is a much better answer than reporting the two numbers and calling them equal.
7How a Hobby Servo Works
7.1 Three parts in one box
An MG996R contains a DC motor, a reduction gearbox, a position sensor (a potentiometer on the output shaft) and a small control circuit. The circuit continuously compares the commanded position with the potentiometer's reading and drives the motor to null the difference. That is a complete feedback loop, sealed inside the case — and it is why the servo holds its angle against a load while a stepper simply holds its last commanded step.
7.2 The command is a pulse width, not a duty cycle
A servo reads the width of the pulse, not the fraction of the period it occupies. The frame is conventionally repeated at 50 Hz (a 20 ms period), and within each frame a pulse of roughly 1–2 ms encodes the angle, with the usable range on many servos extending somewhat wider.
Because GPIO.PWM() is commanded in duty cycle, you must convert. At a fixed 50 Hz:
This only holds at 50 Hz. Change the PWM frequency and every duty-cycle number changes meaning, because the same duty cycle now corresponds to a different pulse width. If your servo behaves strangely, check the frequency before anything else.
At 50 Hz the period is 20 ms. A duty cycle of 5% is a pulse of 0.05 × 20 ms = 1.0 ms; 10% is 2.0 ms; 7.5% is 1.5 ms, the traditional centre. So the classical 1–2 ms servo range corresponds to only 5–10% duty cycle — a narrow window, which is why small duty-cycle errors produce visible angle errors.
The reference code used in this course sweeps a somewhat wider range to reach the MG996R's full travel. Verify on the oscilloscope what pulse widths your own duty cycles actually produce before you trust them.
8Calibrating the Servo
Task 4 asks for 30° verified with a protractor; Task 5 asks for the full range, a duty-versus-angle table, a fitting formula, and an assessment of its accuracy. The fit is yours to derive — but here is how to gather data worth fitting.
8.1 Approach the limits carefully
Commanding a pulse width outside the servo's mechanical range drives it against its internal end stop, where it stalls, draws heavy current, buzzes audibly and strips its gears if held there. Never simply command the extremes to “see what happens.”
Instead, approach each end in small increments and stop as soon as the horn stops moving or the servo begins to buzz. The buzzing is the warning — back off immediately. Record the last duty cycle that produced clean motion; that is your usable limit, and it is the number to quote.
Lab 5 also warns not to force the horn by hand. To change its orientation, remove it and reinstall it — forcing it drives the gear train backwards and can destroy it.
8.2 Taking the data
- Mount the servo so it cannot move, and fix a protractor with the horn's pivot over its centre. A servo that shifts between readings ruins the dataset in a way that is invisible afterwards.
- Step the duty cycle in small, even increments across the usable range, allowing time at each setting for the horn to settle before reading the angle.
- Record commanded duty cycle, measured pulse width from the scope, and measured angle. Including the measured pulse width is what lets you separate a software error from a servo characteristic.
- Sweep in both directions. Any difference between the increasing and decreasing sweeps is backlash — a real, quantifiable property of the gear train, and a good result to report.
8.3 Fitting and judging the fit
The relationship is designed to be linear, so a straight line in angle against duty cycle is the natural model. Report the slope in degrees per percent duty (or per millisecond, which is the more portable unit) and the intercept, both with units.
Then judge it honestly, which is what Task 5 means by evaluating accuracy:
- Plot the residuals, not just the line through the points. Systematic curvature means the servo is not quite linear; scatter means your protractor reading, or the servo's repeatability, is the limit.
- Compare the measured angular range with the datasheet, as Task 5 asks, and comment on any difference.
- State the smallest angle change you could reliably command and observe — the practical resolution. This is usually set by the duty-cycle granularity of your software, not by the servo.
- Note that a hobby servo's absolute accuracy is typically a degree or two at best. If your residuals are that size, you have reached the device's floor, and saying so is the correct conclusion.
(a) At 50 Hz, what pulse width does a 6.5% duty cycle produce? What duty cycle gives a 1.75 ms pulse?
(b) A servo moves 180° as the pulse goes from 0.6 ms to 2.4 ms. How many degrees per millisecond? Per percent duty cycle at 50 Hz?
(c) Your software sets duty cycle only in steps of 0.1%. Using (b), what angular resolution does that impose?
(d) A student runs their servo code at 100 Hz instead of 50 Hz and the servo jitters and will not hold position. Explain why, in terms of Equation (3).
9Validating the Input
The last part of Task 5 asks for a program that accepts an angle and rejects values outside the permitted range. This is a small piece of software engineering, and it is graded, so treat it as a design problem rather than an afterthought.
Three distinct categories, and all three deserve a sensible response:
- Out of range. A number outside your measured limits from §8.1. Reject it, say what the valid range is, and do not move the servo.
- Not a number. Empty input, or text. Converting it will raise an exception; catch it rather than letting the program crash and leave the servo energised.
- Valid. Convert the angle to a duty cycle with your own fitted formula from §8.3 — this is where the calibration work pays off — and command it.
The range you enforce should be the range you measured, not a textbook 0–180°. Enforcing limits your own servo cannot reach is how the gears get stripped, and quoting your measured limits shows the calibration actually informed the design.
One further habit worth adopting: stop sending pulses, or release the pin, when the program ends. A servo left with a live pulse train continues to hold torque, drawing current and getting warm on a bench nobody is watching.
10Common Mistakes and Bench Safety
10.1 Things that destroy hardware
- Unplugging a stepper with the driver powered. Inductive interruption; kills driver chips.
- Forcing the servo horn by hand. Drives the gear train backwards. Remove and reinstall instead.
- Holding a servo against its end stop. Stalled current, stripped gears. Back off at the first buzz.
- Powering motors from the Pi. Both motors need their own supply, exactly as in Lab 4.
- Missing common ground between the Pi, the driver and the motor supply.
- Driver current limit set too high. The motor and driver run hot. Set it from the motor's rated coil current.
10.2 Things that waste your afternoon
- Mis-paired coil wires — the motor buzzes, vibrates, or turns erratically instead of stepping. Do the DMM test in §2.2 first.
- Stepping too fast, so steps are silently missed (§4.2). Increase the delay before suspecting anything else.
- A driver enable pin left in the disabled state. Quiet, complete, and easy to overlook.
- A microstepping mode pin you did not notice, making every reported angle wrong by a fixed factor (§4.1).
- Running the servo at a PWM frequency other than 50 Hz, which silently changes what every duty cycle means.
- A servo or protractor that shifts between readings, quietly corrupting the whole calibration table.
10.3 Mechanical safety
Secure both motors to the bench. A stepper with anything attached to its shaft has real torque and will drag loose wiring around; a servo horn sweeps through its arc quickly enough to pinch fingers and catch probe leads. Keep hands clear while either is energised, and power down before adjusting anything mechanical.
11Self-Check
- Explain why counting steps tells you the angle, and state the one assumption that makes it true.
- Give the DMM procedure for identifying which stepper wires belong to the same coil, and the expected readings.
- What is the physical difference between a full step and a half step, in terms of the field direction?
- How do you obtain counter-clockwise rotation from a table written for clockwise?
- A motor has a 1.8° full step. How many half steps in two complete revolutions?
- At a 4 ms step delay in full-step mode on that motor, find the step frequency, the revolution period and the RPM.
- Why does an H-bridge have four switches per coil, and why does a bipolar stepper need two of them?
- What happens, mechanically and in software, when a stepper misses steps? Why is this the characteristic weakness of open-loop control?
- At 50 Hz, what duty cycle produces a 1.5 ms pulse? What happens to that pulse width if the frequency is changed to 100 Hz at the same duty cycle?
- Name the three input categories a robust servo angle routine must handle, and the correct response to each.
A stepper gives you position by construction — energise the coils in the right order and count — but it fails silently when pushed past its torque. A servo gives you position by feedback — send a pulse width and it corrects itself — but only inside a range you must measure, not assume. Both need their own power supply, a shared ground, and a calibration you performed rather than inherited.
12Practical Engineering Connections
- Steppers in machines. 3D printers, CNC mills, laser cutters and plotters position their axes by counting steps, which is why a printer that misses steps produces a layer-shifted part — the machine never knew.
- Steppers in instruments. Telescope drives, syringe pumps, filter wheels, monochromators and optical stages all rely on repeatable open-loop positioning.
- Microstepping. Driving the coils with graded currents rather than full on/off subdivides each step further, smoothing motion and reducing resonance — the direct extension of §3.1's vector argument.
- H-bridges. The same four-switch topology reverses DC motors, drives audio in class-D amplifiers, and forms the output stage of inverters.
- Hobby servos. Robot arms, camera gimbals, radio-controlled vehicles and animatronics use exactly the pulse-width protocol you calibrated here.
- Industrial servos. The same closed-loop principle scaled up, with encoders instead of potentiometers and a tuned controller, moves robot arms and machine-tool axes.
- Open versus closed loop. The central trade-off of control engineering: open loop is cheap and precise until something unexpected happens; closed loop costs a sensor and buys the ability to notice and correct.
- Calibration as method. Measuring your own duty-to-angle relation rather than trusting a datasheet is what instrument scientists do with every new device — and it is the habit this course is really trying to build.
PHYS 351 · Lecture 05 Notes · © Ran Yang, Ph.D. · yangran.org/teaching/phys351/