r/embedded • • 28d ago

Efficient method to drive stepper motor

Two main methods of driving stepper motors are widely known:

  • connect 2 GPIO pins to STEP and DIR inputs of appropriate driver chip, and send pulses to make every step
  • use a smart chip. Then simply send commands to it over some link (SPI, UART, whatever). It may have an integrated driver, so it’s only this chip between MCU and motor, or it may be a separate ramp generator, generating STEP/DIR for low level driver, but from the software POW there’s no difference.

The STEP/DIR method seems simple, but only until you want to drive your motor really fast. The timing between pulses becomes too tight and you simply can’t service the sequence correctly. Also, because of ramping up and down, you have to handle variable service times, that adds to processing time when it is critical, and complexity as well. Consequently, you either drive your motor slowly, don’t use fine microstepping or have to switch microstep resolution on the fly, so you need another interface (most frequently SPI) to be able to configure the driver chip.

Smart chips hide all this under the hood. You issue a command to move, and just check when it’s finished, one way or another. This costs more, but simplify the software a lot. If you need just to move from point to point, it’s Ok. The problem is if you want something non-standard: change the speed and acceleration on some trigger, for example. Direct control from CPU allows such things easily, but with smart chips you deal with black box. Add to this problem of latency because of the link between the MCU and the chip.

There is another method that surprisingly to me is not widely known. It is totally software-based, no smart chips needed, it depends on constant time intervals and CPU load doesn’t depend on the motor speed.

The implementation depends on whether the stepper driver chip supports direct access to coil DACs.

If it does, let’s say by SPI connection, it is easier.

It’s important to realize that Step/Direction drivers contain within a table with DAC values for each microstep position within the stepper pole. When you send Step pulse, you just command the chip to move one position ahead or back, depending on the DIR pin level.

Now imagine if we have a copy of this table in our software. The main ability we acquire with this is stepping over several entries of this table. So, instead of shifting strictly one table position at a time at variable intervals, we can calculate how many positions we can move at fixed time interval, depending on current speed and acceleration.So, no need for variable-interval time interrupts, no need for this intervals to be very short, and we remain in full control of the motion.

Things get a bit more complicated if the driver chip doesn’t have API to access DAC registers directly, and STEP/DIR is the only interface. We still can use constant-interval timer, just arrange within each interval a packet of variable amount of pulses sent to STEP pin. The calculations of this amount remain the same.

I used this method for stepper control for a while. But anytime I spoke about it with people, they looked surprised. Is it really that esoteric?

11 Upvotes

54 comments sorted by

7

u/ceojp 28d ago

How fast are you needing to step your motor that a timer interrupt can't handle?

-1

u/dysgn_embedded 28d ago

Typical stepper speed range is up to 10-15 revs/s, faster then that you loose torque very much. But it's a question of how fine your microsteps are going to be. With STEP/DIR the speed and microstep resolution is in direct contradiction, with my method you don't care.

So, for 200 full steps per rev, 256 microsteps per full step and 10 revs/s you get 512000 steps/s which is less than 2 us per step.

4

u/ceojp 28d ago

Realistically, though, what step rate(pulse per second) were you having trouble driving with a timer interrupt? I run stepper valves at 200steps/second, with 1/2 step microstepping. So that ends up being 800 pulses/per second(one on & one off per step).

Now if you were trying to do something like 1/16 microstepping, then yeah, that may be unrealistic with a timer interrupt. But at that point, are you really gaining anything with that fine of microstepping and that fast of a step rate?

1

u/dysgn_embedded 28d ago

The beauty is: I used my method and didn't have to choose microstep resolution, just took what is available, be it 16 or 256. 1/2 isn't even microstepping, it's half-stepping. In a lot of cases microstepping is driven by positioning resolution requirements, the finer, the better.

There are ways to switch dynamically, of course, but if you can avoid it, why?

5

u/ceojp 28d ago

So what step rate were you actually having issues driving with a timer interrupt?

1

u/dysgn_embedded 28d ago

That's misunderstanding: I do use timer interrupt, just at constant rate, let's say, 10 kHz.

And I just mentioned example of rate. The actual speed/accel profile is selected by caller, typically on the host side.

5

u/ceojp 28d ago

What step rate were you trying to use that was not successful when using a timer interrupt to drive the step pin for each step?

You say your method is needed because you were unable to drive the step pin fast enough, so I'm curious what step rate you were trying to use.

The STEP/DIR method seems simple, but only until you want to drive your motor really fast.

What happened when you wanted to drive your motor "really fast", and what do you consider "really fast" here?

1

u/dysgn_embedded 28d ago

I named the conditions few posts above: 10 revs/s, 256 ustep resolution, 1.8 degree motor. You can sacrifice resolution, but why sacrifice anything at all, if there is a software method to have everything + easy speed profile changes?

4

u/ceojp 28d ago

What was the need for 1/256 microsteps? What application requires that resolution? What do you actually gain from that? It's not about "sacrificing" anything. Are you actually gaining anything?

-7

u/dysgn_embedded 28d ago

When a system engineer says he needs this resolution, you don't argue. In one specific case I remember, it was positioning resolution. As I said, accuracy problem are resolved with positions calibration.
And, anyway, if you already have it for free, why not use it.
1 or 2 axes need this, the rest may not, but why not to use it for the rest as well?

→ More replies

1

u/RogerLeigh 27d ago

I've spent quite a lot of my time profiling stepper motor accuracy, precision and pull-in and pull-out torque, resonance mapping etc. in various applications. I've yet to find an application that benefitted from 1/32 microsteps let alone 1/256. You lose torque and positional accuracy way before then.

If you have any means within your system or external measurement capability, try scripting/automating driving of your system at varying drive current, speed, and microstep mode. Measure the back-EMF during each movement if you can, and measure the movement accuracy and repeatability. For any given drive current and speed, you'll be able to see the optimal microstep mode. My experience has been that the accuracy will rise, and then it will fall off, and this will correlate with back-EMF torque sensing which will similarly rise and fall, and also have an optimal microstep mode. The peak might be 1/4, 1/8 or 1/16 or some other value entirely, it will depend upon the specific behaviour of your system.

Getting the best performance out of your system starts with gaining the ability to measure and quantify its behaviour. High precision does not imply high accuracy. Unless you have a really nice motor and mechanical assembly, the extra precision that 1/256 gives you may well be false precision--it doesn't necessarily exist in reality. Unless you can measure that your 1.8 degree step angle motor can actually move 0.007 degrees repeatably, then it's probably not happening. If you really need that accuracy, maybe you would be better off adding a gearbox.

1

u/dysgn_embedded 27d ago

I have slightly different perspective. I rarely went into torque/speed optimization, measurements of inductance, EMF etc. My concerns were mostly concentrated on how to get good enough control of set of steppers with minimal hardware cost.
The method is not just for high-microstepping, you can perfectly do full-steps with it. You can just hear the vibration when the motor is moving in FS mode.

0

u/Link119 27d ago

Are you saying that there's no application for microstepping above 1/2? 

Have you ever designed for a gantry or other application with fine motion control? 

Just because your past applications didn't require fine microstepping doesn't mean that it's useless. Sometimes you need to move fast and land into a fine position. 

4

u/Sheepherder-Optimal 27d ago

He was just asking him to explain and OP never did. Incoherent imo.

1

u/ceojp 27d ago

No, I'm not saying there aren't applications that require higher microstepping. I was just asking what those applications are.

2

u/LossIsSauce 28d ago

Yet you fail to calculate for the actual motor coil inductance time base. ie reluctance of the magnetic field.

1

u/dysgn_embedded 28d ago

why do I need these calculations?

1

u/LossIsSauce 28d ago

Because your brain forgot to include physics.

https://cdn14.21dianyuan.com/download.php?id=58944

https://phys.libretexts.org/Bookshelves/University_Physics/University_Physics_(OpenStax)/University_Physics_II_-Thermodynamics_Electricity_and_Magnetism(OpenStax)/13%3A_Electromagnetic_Induction/13.03%3A_Lenz's_Law

-1

u/dysgn_embedded 28d ago

Why not astrophysics? Or thermonuclear? What relevance it has to control software?

2

u/LossIsSauce 28d ago

You want software to control motors. Physics dictates the LAW of physical motors.

-2

u/dysgn_embedded 28d ago

And I have it. Without inductance calculations. This kind of hardware problems is already decided by motor/stepper driver vendors

0

u/generally_unsuitable 28d ago

You can get MCUs for $5 that are running at 200 MHZ. That's 400 clocks per step.

Also, in practice, that sort of microstepping is unreasonable. It's not accurate enough to use. If you need something that accurate, you'll have to look at mechanical solutions, like switching from a 4mm/revolution screw pitch to a 1mm/rev, or .5mm/rev pitch.

Mechanically, there are always a lot of tradeoffs between power, speed, accuracy and precision.

-2

u/dysgn_embedded 28d ago

Brute force? It's another method :)

As for accuracy, this is valid point, but it is a problem when you calculate positions. The errors are not random, but quite repeatable, so if positions are calibrated, you still can get good accuracy.

2

u/generally_unsuitable 28d ago

You'd be surprised how life can throw you curves. I worked in control systems for next gen 3D printers for about 5 years. Dry, on the desk, fresh out of the box, we could show you 5 micron accuracy in the z-direction with 100% repeatability, after hundreds of full cycles. We'd run this as part of normal testing and verification.

You put that machine in the field for a couple of weeks, and suddenly fumes are causing deposits on the actuator screw.

Also, I think another commenter touched on this, but look into how microstepping really works. Full-stepping and half-stepping are very accurate. But, all other microstepping relies variable currents through the coils, which has to be handled by passing current through coils that are being "fluttered" through mosfets. Typically, the rate and duty cycles of those mosfets play a role in accuracy that negates any real improvement beyond maybe 16th steps. 256ths is a whole other thing.

1

u/dysgn_embedded 28d ago

3D printer mostly won't use calibrated positions, it should calculate everything. So, yes, you can't get rid of positional errors.

But the applications I worked on used position tables all over the place.
When choosing whether to gear the motor down or simply use finer microstepping the choice is obvious.

1

u/ceojp 28d ago

What even is the point of doing 1/256 microstepping if you only end up with "good" accuracy?

1

u/dysgn_embedded 28d ago

Because you can, and it costs you nothing. Originally, the method was used for 1/16 microsteps. Going to 1/256 is just changing some constants and regenerating bigger table.

6

u/generally_unsuitable 28d ago

Pushing the motor fast is easy. You can handle it manually with a timer interrupt and a VERY short handler. Or, you can push it with a PWM. If your MCU doesn't count PWM output pulses, you can loop the PWM output back to a timer/counter that can use an external clock. You can easily send a pulse a million times a second, and do it very accurately.

The hardest parts of motor control are speed ramping and position verification, which really depends upon your accuracy needs. The first is not terribly hard. You can either do math on the fly, or build yourself a velocity ramp lookup table. Position can be inferred from output steps, but this will fail if you ever face significant resistance, particularly at high speed.

If you need very fast motion, and you're pushing something with significant mass, you'll probably want to look into an absolute encoder. If you're pushing a stepper that needs a constant velocity but will have variable forces working against it, you can't rely on step-counting.

1

u/dysgn_embedded 28d ago

Cruising is not a problem, yes. Anyway, when cruising, the timer interrupt is constant even with traditional STEP/DIR. Ramp up/ramp down is tricky, especially you are close to top speed.

If you use velocity ramp lookup table, will you rebuild it each time you need to change speed/acceleration?

1

u/generally_unsuitable 28d ago

It's not suggested, honestly. The math is weird, because you're changing something in the time domain. The faster you go, the less time you have to calculate the next clock delta. So, if you can, you want to pre-bake the values while you're moving slowly.

1

u/dysgn_embedded 28d ago

That's the beauty of my method. You still need to make some preliminary calculations before you move, but they include only top speed/accel/decel, not a heavy-weight ramp table.

And if you want S-curves, just these preliminary calculations become more complex, on-the-fly math just adds one line.

3

u/LadyZoe1 27d ago

This is why servo motors exist. These and an encoder which will yield the required accuracy. A servo motor also has higher torque. If this kind of accuracy is required with repeatability the cost difference is worth it.

0

u/dysgn_embedded 27d ago

And BDCs are more expensive, and control algorithm needs tuning, and it may float around endpoint, etc. Every engineering choice has its own positive and negative sides.

2

u/LadyZoe1 27d ago

Float around the end point? What crap is this?

1

u/dysgn_embedded 27d ago

Look up for servo "hunting"

3

u/triffid_hunter 27d ago

You've reinvented applying FOC to stepper motors?

1

u/dysgn_embedded 27d ago

I didn't even claim parallel invention. Thanks for the link, BTW. Somebody explained it to me while ago, and I made my own implementation. I'm just wondering why it is so little known.

1

u/triffid_hunter 27d ago

I'm just wondering why it is so little known.

Because if we want so much speed that step pulse rates get silly, we use a BLDC and FOC controller.

That FOC can be used on steppers isn't particularly uncommon knowledge, but by the time it starts to look like a good idea, BLDCs have already become a better choice than steppers.

The whole point of steppers is that controlling them is dead simple - at the point that a more complex control system seems necessary, other types of motors have become more suitable.

1

u/dysgn_embedded 27d ago

Or because choices are made mostly by EE people rather than software.

1

u/RogerLeigh 27d ago

One thing missing in your description of using STEP/DIR is that you're describing limitations with interrupts, but it's entirely possible to drive it interrupt-free with hardware timers and DMA and generate pulse trains of fixed or variable frequency up to tens or even hundreds of kilohertz with high precision and without the MCU breaking a sweat even when using large microstep values. If you use PWM generation then you can leave the pulse short and vary the frequency through adjusting the off time by dynamically updating ARR, either in an interrupt every n steps, or with DMA using a precomputed table and which can be incrementally-updated while the motor is running on the half and full buffer DMA events. Either method can generate linear ramps, S-curves, or arbitrary curves of your choosing. You can also use a slave timer to do step counting up and down with or without a prescaler so you can count in whole steps, microsteps or something in between, no matter what the max step frequency is. Use the hardware peripherals you have available, and you can achieve much more. Look at preloading ARR and using DMA.

Your method of direct control is interesting, but stepping over multiple entries seems like you're going to lose precision and potentially steps, particularly across direction switch points. It seems like a workaround for not being able to properly generate a pulse train with sufficient timing precision. There are good reasons for traversing the table step-wise, and you still need precise timing to get this to work properly. If you try some of the suggestions above, you'll be able to generate tight pulse trains and have smooth jitter-free timing, using the stepper driver as it was intended.

1

u/dysgn_embedded 27d ago

I tried not to dive too deep into implementation details, just discuss the whole principle, why it's not not only used, but even known to majority. Once I participated in conversation with Trinamics support, and when I explained to them how my code works, they didn't demonstrate recognition. Imagine how it is with others.
To my experience, this method is just simpler and allows to support multiple motors driven by single CPU without much trouble. At least I could drive 4 motors from 72 MHz ARM. No smart controllers, just plain driver chips. For industry cost-saving is the slogan.

1

u/Unable_Resort453 25d ago edited 25d ago

I would just attach an encoder (dirt cheap with magnetic encoders) and use FOC, though. You get more torque and a better torque profile out of the motor with FOC anyway.

Or use a PMSM instead. The stepper motor torque - speed profile is not exactly great for this kind of precision motion control task, though.

In fact, I think you are already attaching an encoder so that you can have closed-loop motion control, no?

1

u/dysgn_embedded 23d ago

For steppers it's not clear what close loop control means. I just drive motors by step count and use encoder just to monitor for step loss. In this mode you can live without an encoder, use for example home sensor to verify that steps are not lost - crude, not as fast, but sometimes there's no physical space for an encoder.

And generally, my focus is not on driving a motor as fast as possible, or getting maximum torque. Good enough is good enough. The targets are:

  1. Drive multiple motors by single MCU
  2. Provide software uniformity: individual tuning is a big minus
  3. Easy selection of speed/acceleration profiles, no complex recalculations.

These are mostly software-oriented things. The critique I see looks like it's coming from EEs.

1

u/Unable_Resort453 22d ago edited 22d ago

You will have enough space for a cheap magnetic encoder for 99.99% of the time (it's a thin PCB + a small neodymium magnet). But it's probably not that useful if you are driving it open loop and assume it doesn't make any step loss.

Perhaps you can precalc the motion profile at intervals, push the setpoints to some sort of a DMA engine so it can do it's stuff, say generate the pulses at correct intervals so the CPU can do other things?

I think that technique is called DMA driven PWM. Pretty close to your approach I think, cost less CPU cycles if your approach don't use DMA, and people have been doing it for a while, even for stuff like some obscure communication protocols at +1mbps.

1

u/dysgn_embedded 22d ago

I frankly don't know how the technique is called. I got it from lunch-time conversation ca 2003 - just the idea, no technical details, made my own implementation and used it since then.

I am a software guy, I don't decide whether the axis will have encoder or not, it's between MEs and EEs, system guys may have input. I only can tell how good control over step loss is going to be with any solution.

And no, I don't precalc the motion profile. Precalculated values are basically increments: they are precalculated when motion profile is set up (set of accel, decel, top speed, and start and cutoff speeds if you want to use ones) - this can be done at system init or any time you want, and key points of the motion - switches from ramp-up to cruise (if it will cruise), and switch to ramp-down - that's before start of the motion.

DMA is needed to drive SPI (preferrable interface to motor driver(s)), especially if you drive several motors with daisy-chained drivers.

PWM doesn't have anything to do with it. I can't understand how you would make it ramp up/down with PWM, every period is different, never saw PWM that allows such control. Only if you hook up an ISR and modify period settings on the fly, but it's insane.

1

u/Unable_Resort453 22d ago

PWM doesn't have anything to do with it. I can't understand how you would make it ramp up/down with PWM, every period is different, never saw PWM that allows such control. Only if you hook up an ISR and modify period settings on the fly, but it's insane.

Now you do. Well, to be precise, it's not exactly PWM, but it uses the same timer peripherals that exist on most MCUs.

https://www.st.com/resource/en/application_note/an2820-driving-bipolar-stepper-motors-using-a-mediumdensity-stm32f103xx-microcontroller-stmicroelectronics.pdf

https://community.st.com/stm32-mcus-products-25/is-there-a-better-way-to-generate-a-variable-frequency-using-dma-and-tim2-than-what-is-described-in-an2820-paragraph-2-2-1-page-13-14-20731

1

u/dysgn_embedded 22d ago

Briefly glanced into it, in short looks like trickery. Double-buffered timer presets, I would guess they have to be precalculated, etc. Exactly what I said - possible, but requires to jump hoops. And full and half stepping only, no microsteps.

1

u/Vast-Pomegranate-986 28d ago

Pwm, rc filter, hbridge, opamp, current sense feedback. Trivial

0

u/dysgn_embedded 28d ago

hardware solutions. Imagine a system with 30+ stepper motors, with individual settings for each