Configuring a DIY DC Servo Motor for CNC Positioning

Tom Garrett13 min read
Motion ControlOther ManufacturerTroubleshooting
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Motor starting and commutation current can disturb a shared PIC supply; this build counted shaft motion by hand but became erratic when the motor was powered. Optical isolation later let Mach3 move it, while the commanded travel still continued after the keyboard jog stopped. The deciding measurements are rail behavior during motor start and reversal, encoder edge rate, and the difference between commanded and measured position.

A capacitor alone cannot correct shared-supply coupling

A capacitor between the motor supply and ground was reported to help in one direction, but the controller became erratic again when the motor reversed. That result is not proof that the capacitor value is wrong. A motor shares both supply impedance and return wiring with the PIC when both use the same supply; starting current and switching transients can move the PIC supply voltage or its local ground reference. Direction reversal changes the switching paths, so a bypass that appears to help one polarity may leave another disturbance path intact.

Treat bypass capacitors as part of a power-distribution design, not as a substitute for separating noisy and sensitive current paths. Measure the PIC supply at the microcontroller pins while the motor starts and reverses, and measure motor current at the same time. A reset, corrupted input, or false encoder transition that coincides with rail movement points to a power-integrity or grounding problem. Stable logic rails with excessive motor current or heating point to a different fault: motor load, driver capacity, or a stalled mechanism.

Do not select a suppression diode or connect one directly across a reversing motor without checking the switching-driver topology. The correct transient-suppression arrangement depends on how the motor is driven. Use the driver schematic and its recommended suppression circuit, then test both directions.

A single optical channel cannot recover signed position

One interrupter can report that a slot or mark passed the sensor, but the same sequence of light and dark states occurs when the shaft turns either way. It can count pulses or estimate speed when direction is known independently; it cannot determine signed shaft position on its own. Reversing the motor electrically does not repair this feedback ambiguity if the shaft can coast, stall, or be moved externally.

For position feedback, use two sensors observing the same encoder wheel with an offset that produces phase-shifted outputs. One channel must lead the other in one direction and lag it in the opposite direction. That lead/lag relationship is the direction information. The build began with one salvaged printer interrupter, then moved toward using two interrupters; keep the distinction clear between the Mach3 command input and the two feedback channels.

If only one encoder channel is available, direction must come from a separate trustworthy source, such as a confirmed direction command combined with a system that cannot coast or move independently. That arrangement is less robust than quadrature feedback when the motor reverses near a sensor edge. For closed-loop CNC positioning, use two-channel feedback or another encoder that supplies signed position.

Rising-edge-only counting loses small reversals

Counting only rising edges on channel A and using channel B as a direction bit can work under restricted motion assumptions, but it can miscount when the shaft reverses before channel B changes. For example, if channel A toggles repeatedly while B remains low, a rising-edge-only counter records additional forward movement even though the shaft has returned across the same edge. Using both channels and both edges lets each small forward transition be canceled by the corresponding reverse transition.

For clean quadrature, adjacent states differ by one bit. One valid sequence is 00 → 01 → 11 → 10 → 00; the reverse sequence represents the opposite direction. The choice of which sequence increments is arbitrary and depends on wiring. A transition that changes both bits at once is invalid: it usually means the input was missed, noisy, or sampled too slowly.

A rising-edge A/count plus B/direction decoder can be adequate if the application guarantees that direction changes only after enough shaft travel for B to identify direction. That is a restrictive operating condition, not a general substitute for a quadrature state machine. For a CNC axis that can dither or reverse at small increments, decode both channels from previous and current states.

A controller swap cannot resolve command-versus-motion timing

The reported Mach3 behavior was that the motor kept turning after the operator released a keyboard key, then stopped after reaching the number of commanded steps. That can be normal for a position-following servo: input pulses accumulate into a target position, and the drive continues moving until measured position catches up. A DC motor does not stop at each command pulse as a stepper motor typically appears to do; inertia and the position controller determine how it moves between target counts.

The phrase “too fast” can refer to pulse width, pulse frequency, or the motor’s ability to follow the requested move profile. Those are separate quantities. Measure STEP pulse width and spacing, count pulses accepted by the PIC, and compare the resulting target position with encoder feedback. If the target count stops changing at key release while the motor continues, the drive is catching up to a stored position error. If target counts keep arriving, inspect the motion software’s jog behavior and signal configuration. If feedback counts fail to keep pace or jump, investigate encoder bandwidth and electrical noise.

Changing from Mach3 to another motion program will not fix incorrect direction signaling, missed encoder edges, or an unstable power rail. First identify whether the mismatch is in the command stream, feedback decoder, motor dynamics, or software motion profile.

Separate command position, feedback position, and motor drive

Build the controller around three distinct quantities: a signed target position, a signed measured position, and the resulting position error. Under a conventional STEP/DIR interface, each accepted STEP pulse changes the target by one command increment, while DIR selects the sign. The encoder changes measured position according to actual shaft movement. The controller then acts on the difference between target and measured position.

The project routed the Mach3 step input to RB0 (INT) on a PIC16F628A. Confirm whether the interface also supplies a DIR signal and how the software reads it. If the PIC receives only STEP pulses, the pulse train provides magnitude but not direction; the target cannot be updated correctly for signed moves without a separate direction signal or another explicitly defined encoding.

A useful control model is:

target_position = target_position + signed_command_steps
position_error = target_position - measured_position
motor_command = controller(position_error)

Do not treat each incoming command pulse as a physical motor step. A DC motor has continuous motion, and one pulse changes the requested position by one encoder-equivalent command increment; the motor may need many control updates to reach it. Verify the driver’s direction and output behavior separately from the command counter before adding PID gains. The PID coefficients depend on motor, load, gearing, encoder scale, driver, and update timing, so determine them from the actual mechanism rather than copying values from another build.

A two-channel state machine preserves encoder direction

Read both encoder inputs often enough to observe every valid state change, then compare each sample to the preceding sample. The following pseudocode describes the decoding logic; it is not PIC-specific code:

previous = read_AB()
loop:
    current = read_AB()
    if current == previous:
        continue
    if current is the next state in the chosen sequence:
        position = position + 1
    else if current is the previous state in the chosen sequence:
        position = position - 1
    else:
        invalid_transition = invalid_transition + 1
    previous = current

Use a timer-driven sample routine or an input-change interrupt only if the microcontroller can capture both channels on the required edges. The polling or interrupt rate must exceed the fastest encoder transitions with margin; verify this at maximum motor speed rather than at hand-turned speed. A missed state produces an invalid two-bit transition or an incorrect count, depending on how the decoder is written.

Count invalid transitions during testing. If they rise when the motor switches, investigate electrical noise and input conditioning. If they rise with motor speed while the rail is stable, reduce the edge rate or improve sampling and signal integrity. Once the counter has lost transitions, its position is no longer trustworthy; re-establish a known reference before relying on the axis coordinate.

Encoder spacing, count rate, and axis resolution set the limits

Space the two optical sensors so their outputs are offset by approximately one-quarter of an encoder cycle. The important quantity is electrical phase, not a universal physical distance: the wheel geometry determines how far apart the sensors must sit. Coarse hand-made wheels make sensor placement and edge shape especially consequential. A finer printer encoder disk can increase counts per revolution, but it also increases the edge rate the decoder must process.

If the wheel produces N encoder cycles per motor revolution and the decoder counts all four transitions, then counts per motor revolution are 4N. For a screw with lead L per output revolution and a transmission ratio R defined as motor revolutions per output revolution, ideal travel per decoded count is L / (4NR). This is a resolution calculation, not an accuracy guarantee; backlash, compliance, missed edges, and encoder mounting all affect actual positioning.

For a rotary output with effective radius r and the same ratio definition, ideal linear travel per count is 2πr / (4NR). Reconstructing a claimed linear resolution requires the encoder cycles, decode mode, transmission ratio, and effective output diameter. A tooth count alone does not determine linear resolution. Chain or gear backlash affects direction reversals even when motor-shaft counts are perfect; a motor-mounted encoder does not measure lost movement downstream of that encoder.

Quantity Decision it controls Where to measure or read it
Motor current and PIC rail voltage Separate current-induced rail disturbance from a logic or decoder fault; compare motor and driver current with their rated limits. Measure current during startup, reversal, and stall-like loading; scope the PIC supply at its pins. Read motor and driver ratings from their datasheets.
Encoder cycles per revolution and maximum RPM Calculate the required edge-processing rate: RPM × 4N / 60 for x4 decoding. Count wheel cycles per motor revolution; measure or read the motor’s operating speed under load.
STEP pulse width and pulse rate Determine whether the input signal is electrically acceptable and whether the commanded position rate exceeds motor or decoder capability. Use a scope or logic analyzer at the PIC input and inspect the motion controller’s pulse configuration.
Target count, feedback count, and driver temperature Distinguish a growing position backlog from missed feedback or a current/thermal overload. Log the PIC counters and inspect driver and motor temperature against the applicable datasheet ratings.

Power isolation and reversal testing expose noise faults

The successful reported change was optical isolation between the motor-control side and the PIC supply domain. Isolation can prevent switching-current return paths from corrupting logic references, but it does not correct inadequate encoder sampling or a wrong command target. It also requires correct wiring and power on each side of the isolator; verify the actual circuit rather than assuming that an optocoupler alone makes the whole system immune to noise.

  1. Record the PIC supply voltage at the microcontroller pins with the motor disconnected, then repeat during motor startup, steady running, and reversal. Capture the same events with a current measurement.
  2. Separate motor and logic supply paths or use the tested optical-isolation arrangement. Keep motor return current out of the PIC ground path; connect signal references only as required by the actual isolated interface.
  3. Inspect the motor driver and suppression wiring against the driver schematic. A circuit that behaves in one direction but fails in the other needs a bidirectional switching-path check.
  4. Repeat the test in both directions while monitoring rail voltage, encoder states, reset behavior, and invalid transitions. Confirm the PIC supply remains within its component rating and the driver remains within its current and thermal limits.

If the PIC becomes erratic only when the motor switches and its rail or encoder pins show disturbances, fix wiring, isolation, or suppression before PID tuning. If the rail and digital signals remain stable but the motor draws excessive current or heats rapidly, inspect mechanical binding and verify motor and driver ratings instead.

Position-loop verification distinguishes lag from lost counts

Test the command path, encoder, and motor loop in that order. Begin with the motor unpowered and move the shaft by hand through several encoder cycles in both directions. The signed count must increase in one direction, decrease in the other, return to its initial value after a small back-and-forth movement, and report no invalid transitions. Then power the controller with the motor output disabled and confirm that STEP and DIR change the target count in the intended direction.

  1. Run the motor at a low, measurable speed and compare commanded target counts with encoder counts. Confirm both counters change consistently during forward and reverse motion.
  2. Increase speed in controlled increments while observing encoder transitions and supply behavior. Stop increasing the rate when invalid transitions, count divergence, resets, or current/temperature limits appear.
  3. Issue a finite move and stop generating command pulses. If target count is fixed while feedback continues toward it, the motor is completing a queued position move. If target count continues changing, inspect the STEP/DIR stream and jog configuration.
  4. Repeat reversals under the intended mechanical load. Check whether shaft feedback returns accurately and whether the axis itself loses motion through backlash or compliance.

Keep separate records for target count, feedback count, invalid transitions, motor current, rail voltage, and temperature. A growing target-to-feedback error with valid encoder transitions indicates that the motor or drive is not following the requested move; stable current and temperature do not excuse an unstable position error. A discontinuous feedback count points toward encoder timing, signal integrity, or decoding. Rising current and heat with a stable feedback stream point toward load or driver capacity instead of a logic fault.

FAQ: DIY DC servo encoder and step timing

What happens if the motor keeps running after I release the Mach3 jog key?

If the PIC has already accumulated a target position, the motor can keep moving until feedback reaches that target. Compare the target counter, feedback counter, and STEP input after key release to distinguish position catch-up from continued pulses.

What happens if I use only one optical interrupter?

You can count transitions, but the channel alone cannot identify rotation direction. Add a phase-shifted second channel or provide direction through a separately verified signal.

What happens if I count only rising edges on channel A?

Small reversals across an A edge can add counts without corresponding shaft travel when B has not changed. Decode previous and current states from both channels to count forward and reverse transitions.

What happens if the PIC works by hand but fails when the motor is powered?

Measure motor current and the PIC supply at its pins during startup and reversal, then inspect encoder inputs for switching-correlated transitions. The reported capacitor change helped in one direction, while optical isolation later allowed Mach3 operation.

What happens if encoder counts fail at higher motor speed?

Calculate the x4 edge rate from motor RPM and encoder cycles per revolution, then compare it with the decoder’s measured sampling capability. Stop testing if motion becomes unpredictable, current or temperature exceeds component ratings, or counts diverge; resolve the fault before resuming and escalate unresolved interface or driver questions to the relevant supplier’s official support.

Back to blog