Shop OBEX P1 Docs P2 Docs Learn Events
Stepper Motor Object for the P2: share your ideas here! — Parallax Forums

Stepper Motor Object for the P2: share your ideas here!

Hello,

We've had some requests for a complete stepper motor object from educators and CNC enthusiasts.

Q1: What would you like to see in this object to make it complete, useful, and fully exploit the P2's capabilities? Details like number of steppers, unipolar/bipolar, micro-stepping, interface, etc. I think encoder feedback from scales/slides is out of the realm of this specific object, as it becomes complicated quick and varies by application depending on backlash, feedback, but I'm not 100% certain.

Q2: To prove and demonstrate this object we'll need a bench test that has a suitable number of steppers with an ample power supply (but one which is readily obtainable from our common bench power supplies). Can you identify some smallish steppers that have all of the characteristics of the larger ones which may be used on CNC conversions? It would be nice this with some more simple hardware (using the Click, too, I think). Links would be helpful.

Tell us what you think, please.

Thanks,

Ken Gracey
«1

Comments

  • I've got some of these: https://www.amazon.com/ELEGOO-28BYJ-48-ULN2003-Stepper-Arduino/dp/B01CP18J4A (be sure to scroll down on this link, there is a hookup diagram and even arduino code.
    They would work well as a demonstration or for a small cnc that drives a pen or something low load.

    These have a little driver board that you can just do the logic level step and dir signals, but you could get them without that and use the click stepper driver.

    I personally would like it to have encoder feedback, and that is a nice way to showcase a P2 smartpin feature. I'll look around for cheap encoders that could be used for the demonstration.
  • For my SCARA project I use standard NEMA17 motors with A4988 drivers that are very common.

    Mike
  • Hi

    I built my first line follower with two of these, (the elegoo's not the Nemas's)
    Super cheap
    Includes Gearbox
    Noticeable backlash- unsuitable for precision but great for education.
    Easy to dismantle and show workings- just bend back some tabs- best just to do this once and save for demonstration as the tabs will snap if flexed too often.
    Used jar lids for wheels with brass electrical connector with screw used for hub.
    worked very well.

    Dave
  • I would think that a simple basic Step and Direction example would be best. Perhaps one of the common A4988 drivers plugged into the Edge + Breadboard with a small NEMA 17 motor attached.

    A simple single axis motion object.

    Something that covers the basic CNC G1 linear motion command. Direction, distance (number of pulses), feed rate (maximum pulses per second) and simple acceleration control.

    Make nice step by step tutorial out of it.

    Start with a blank spin2 program and show the basic configuration (for a generic program) and then work up showing the pin configurations, with detailed explanations of how that works and what the settings being shown mean. That is the hard part for us new to P2 programmers, smart pins. There are tons of code examples out there on various CNC motion control components, where we get lost is the proper way to control and generate the pulses in a P2 manner.

    Smart pins are both one the P2's greatest strengths and its greatest weakness. If you understand them, they are miracle workers, if you don't you are in for a very steep learning curve. At least until a lot of very basic step by step tutorials are released for each mode they offer.

    This is one of the first things I wanted to try with my new P2 boards (Edge + Breadboard and a ManAtWork module), only to discover that it is going to take a LOT of digging to figure out the best (proper?) way to do this with the black box of smart pins. There has to be a better P2 way to do this other than bit banging...



  • @"Kerry S" I was thinking along the same lines: number of pulses, direction, rate, accel/decel parameters would make it quite complete.

    Care to point out a preferred A4988 driver board that may even have connections for the NEMA 17 motors? I'd love to have a sample set of hardware in stock to demonstrate the object.

    Ken Gracey
  • JonnyMacJonnyMac Posts: 8,924
    edited 2021-01-24 22:30
    Smart pins will make step and direction control pretty easy. In my SPI object, I use the smart pin pulse mode to create the clock pulses. Here's the setup.
      m := P_PULSE | P_OE                                           ' spi clock mode
      x.word[0] := 2 #> (clkfreq / (khz * 1_000)) <# $FFFF          ' ticks in period
      x.word[1] := x.word[0] >> 1                                   ' ticks in low cycle (50%)
      pinstart(sck, m, x, 0)                                        ' activate smart pin, no pulses
    

    For stepper control, you'd want the setup to be fore your maximum feed rate so that you can handle multiple pulses with a single line of code like this:
        wypin(sck, 16)                                                ' clock 16 bits
    

    For acceleration and deceleration curves you'd need to calculate changing delays between single pulses.
  • There has to be a huge market for machine control of steppers using GRBL firmware and G-Codes for machining all kinds of products. I have a Shapeoko by Carbide3D.com desktop milling machine and love it, easy to use and a great addition to the shop.

    I think the P2 and EDGE would be a great match for all types of industrial and hobbyist machine controls.

  • First some basics. I think we all agree that a unipolar stepper driver with a ULN2003 is not of much use, theese days. You can only drive very small motors with little power and speed like those used for head positioning in old floppy drives. So we need an external driver like the A4988 for small motors and something like Leadshine drives for bigger motors or servo drives for real CNC machines.

    Before starting to code it's important to ask the right questions. With relaxed requirements thing are a lot easier but if you change your mind later it might happen that you have to start all over, again.

    1. Are simple 3 axis point-to-point moves with a fixed velocity (with acceleration ramps, of course) sufficient? Or do you also need complex trajectories with arcs and multiple concatenated line segments?
    2. Do we need different resolutions for different axes? Different pitches are not the problem. For example if you have 10mm pitch for the X+Y leadscrews and 5mm for Z you could simply set the microstep resolution of X and Y to twice the Z resolution. But some CNC machines have completely different mechanics, for example rack+pinion or belt drivbes for XY and leadscrew for Z.
    3. Is the resolution (steps per mm or per inch) a whole number? For leadscrews and belt drives with pulleys of well choosen number of teeth the answer is normally "yes". But for a rack+pinion drive there's the factor pi in the formula and it's not a whole and not even a fractionbal number.
    4. Do we need to change the velocity "on the fly"? This might be required for complex trajectories with rounded corners, for example. If the centripedal forces in the arc segments are to high speed has to be reduced to avoid stalling.

    I think encoder feedback is not really useful. You can use the encoder to notice that there is something wrong, that is, if the motor has stalled. But then you can't do much about it. If the motor is too weak without encoder then it's still too weak with encoder. And a true closed loop system is quite complex and has to be tuned well to achive good results. If you really need it it's better to used self contained closed loop drives or true servo systems. For smaller machines instead of investing too much money and brain into handling of errors it's better to take care about making the system as reliable as possible and avoid errors in the first place. If the step signals have low jitter and the ramps are S-shaped there is much less vibration and the probability of a stall is much lower, so the motor won't stall and you don't need encoders. (Of course, for really big CNC machines a crash can be expensive so that the extra comlexity can be justified)
  • Roy ElthamRoy Eltham Posts: 2,996
    edited 2021-01-25 09:47

    Encoder feedback is a part of any high end CNC machine and even high end 3d printers (commercial level). The reason being that it can attempt to correct missed steps and save the job or stop immediately to prevent damage and waste. The fact that you can get by without for hobby/maker level machines is more about how critical the machine and materials are... if your machine goes down as a hobby person it's annoying, but it's rarely going to be a critical issue like causing your whole line to go down and loss of production output. Even on small machines it can be important, it's more about use than size.
    I personally would like it if I could get close loop control setup on my CNC machine, even though most of the time I don't "need" it, having it could have saved me money on bits, materials, and time. If the P2 could provide it at a lower cost than existing systems, it might be a viable product to sell as an upgrade to XCarve or Shapeoko machines.

  • Ken,
    The Click Stepper module is very close to the same thing as an A4988. The ULN2003 is more low level, so while we can make a separate driver for it, it shouldn't be part of this project. Something that works with the click stepper module can also work with most of the stepper drivers, like the A4988 and even high end commercial stepper drivers since they mostly all work the same way. Although, some high end stuff has the smarts built into the motor and you just talk to them via RS485 or CAN.
    Those tiny motors I linked with the ULN2003 boards are still fine to demoing, it's hard to find them on Amazon without the driver boards, but maybe you can find another source? Going up to a NEMA motor is going to be quite a bit more expensive (the cheapest NEMA style motor I could find on amazon is $8-9 while you can get those other little guys with the drivers at a cost of $12.50 for 6 (my above link wasn't the cheapest, but I picked it because it had more info in the description).

  • There is no such thing as "missed steps" in a properly designed system. The motor is either strong enough to keep up or it stalls if a collision or mechanical overload happens. If that happens it looses all steps (coming to a comlete stop) and not just a few. Single or few "missed steps" are caused by EMI problems or bad design (setup/hold time violations for the step/dir signal pair). And that can be avoided.

    Another example: With my old 3D-printer I often had problems with the extruder motor stalling when the nozzle clogged. If the motor is strong enough then the pinion slips against the filament. If it's not then the motor stalls. The latter can be fixed or at least recognized with an encoder, the first case cannot. The better solution is to use a better quality extruder with a geared motor. With my new printer I never had any problem with it although it doesn't have an encoder.

    Agreed, for big machines costing 1000s of $ encoders are mandatory to save lost time and material in the case of somwthing going wrong. But simple things should be kept simple. If your budget is limited it's better to spend the money on avoiding problems than trying to fix them with monitoring devices.

  • So let's focus on the minimum requirements. I think it's no problem to add safety or surveillance features, later. A "watchdog" comparing nominal and actual position with the help of an encoder using a max. tolerance window should be no big deal.
    Resolution and max. speed should also be no problem. The smartpins can handle multiple Mhz of step frequency without drawing much CPU power.
    But the decision if we need integer or float math and if we need look-ahead or not makes a big difference.

  • ErNaErNa Posts: 1,742

    I only can agree to what ManAtWork states. A stepper by definition is not a motor. The task is to move to a position and stay there. If such a step is not successfully executed, a sensor can detect this and stop the system, but will never be able to correct this error. This is logical: if you can not fullfil a planned task, you will not be able to fullfil an unplanned one. There are "steppers" that need a feedback, but then it is a must, not an option and in this case a true servo can be used. There are 3-phase steppers with feedback available, but those are servos with a magnetic design similar to steppers, that is, they are permanent magnet reluctance motors, what is a hybrid design.

  • Roy ElthamRoy Eltham Posts: 2,996
    edited 2021-01-25 12:21

    I'll add one one thing, sometimes building the mechanism to the level required to not miss steps is more expensive then using closed loop motor control with encoders. P1 and BASIC Stamps are using in commercial and industrial settings, so I bet there are some potential P2 customers that would want it too.

    Anyway, I guess we'll just have to agree to disagree, because you seem to be insistent on making overarching generalized absolute statements that I know people who have worked with and built CNC machines that would never go without closed loop motor control on them, and that means something. If I was using CNC machines for my business or more extensively than for my own hobby fun, then my machine would be one with it.

  • ErNaErNa Posts: 1,742

    Roy, you know a wrong ASM code can make a program obsolete. This is true for mechanics too. A control loop lives from detecting an error and correcting this error before a system runs out of control. A stepper lives from making an error without correcting it. That is: at standstill the motor creates no (resulting) torque. That means: externally applied torque and motor torque are balanced, so the motor doesn't accelerate and stays in place. If there is no external torque, the rotor settles to a position where no internal torque is created even if there is the motor current at it's maximum. Applying an external torque results in moving the motor to leave equilibrium. The resulting position error is small but the source of the torque. There is a max torque at a certain deviation, if you reach this point using external torque, then the motor will overshoot to the next possible holding position but due to inertia the motor will just not stop in this point.

    If you are not able to control an external force you will not be able to resynchronize the motor and continue serious work. So any feed back system is only for purpose of safety to detect malfunctions, but not to have a control loop.

    That is a right as it is that a poorly designed software may run, but will surely fail.

  • Remember back in the data when the Apple I or Apple II computers had a floppy drive. To position it they would slam the head into the end stop enough times to figure it must be there and then proceed on.

    While most other manufactures at least put in a end stop to detect when the drive was at home and then moved on, but still no feed back.

    Even today with rotary voice coil hard drives there is no feed back except the data under the head does not match what should be there.

    Mike

  • We can just agree that there are applications where you want encoders and others where they are not needed. I also own a big CNC machine with 2HP servo motors on each axis. Imagine 6 horses out of control! It definitely makes sense to have a safety shutdown there if something goes wrong. But this is totally out of scope for the typical Parallax project. I think typical target is something like a 3D printer or an engraving machine, for most cases. If you want to please every CNC manufacturer you'll never be finished and it would be better to buy a Beckhoff control.

    So again, what are the requirements for the trajectory planner? Simple point-to-point movements would be sufficient for a pick&place machine, for example, and could be implemented with a few lines of code. But I guess that this is not enough, that's why I'm asking before I start coding.


  • For this example I think you should keep it simple, and something that is commonly used. A Pololu A4988 is the cheapest ($5.95), and is used in a lot of RAMPS setups for 3d printing and GRBL, combined with a ($5.00) 42 oz.in Nema 17 stepper that draws 1 amp per phase (the safe spot for an A4988 without cooling). Don't forget to add the needed 100uF capacitor that has to be placed on the motor power input to the A4988. A small 12v DC wall wart will power a single motor easily.

    This tutorial should be JUST about how the P2 does Step and Direction, not the nuts and bolts of a full CNC control system. That is too much info to start with and there are tons of example programs out there that deal with multi axis motion, position feed back, etc.

    Before any of those existing examples can be used, for example it should be possible to port GRBL or TinyG over to the P2, we need a good tutorial on how to do the pulse control. A typical stepper is 1.8 deg per step, the A4988 can do 1/16 micro steps (though 1/8 seems to be more stable). So we have 200 steps per revolution and with 1/8 micro steps that becomes 1600 steps per revolution.

    Things that need to be in the tutorial.

    How do you rotate the motor 10 turns, at 120 RPM max speed, and stop at the correct position?

    How do you ramp up the step rate on a Smart Pin as you accellerate from 0 PPS to maximum PPS?

    How do we keep track of the total pulses sent if the Smart Pin is controlling the sending so we know where we are in the motion?

    Make sure to explain EVERYTHING clearly about setting up the pins so at the end of the tutorial the reader really understands what they did, and more importantly, how to adjust the settings to get different results. Cover each parameter, what they do and how they are calculated.

    Once you have that clearly shown we can start porting other applications to make a real CNC system, or an industrial type robot, or a new PLC interface for an old CNC barfeeder (a 6' MTA in my case), or a PnP machine, or a SCARA robot, or a 3d printer.

  • Ok, I see. So let's start with the simplest possible but still useful solution.

    • linear point-to-point movement only
    • configurable speed and acceleration but constant during runtime
    • integer math only (steps per unit must be a whole number)
    • 3 axes max. with equal resolution
    • no feedback, no lookahead

    I think I could code an example and show how it works in the live forum. Some features may be easily added or extended, later, like number of axes, an encoder watchdog for error-checking...

    Wait... I've just re-read the first post from Ken. Does this mean that I don't have to do anything and somebody at Parallax wants to create an object, tutorial or whatever? 😇 I ofte make the mistake that when I hear "We've had some requests for..." I immediately start thinking about possible solutions as if it was my job. 🤪

  • hi

    @ManAtWork

    I would LOVE to see a tutorial by you on this subject. But for ME, I would like to see it done from the ground up NOT a finished piece of polished impenetrable code. By that I mean perhaps flow charts or simple pseudo code to illustrate each step of the process. I'm pretty sure I could get so far on my own having played simplistically with steppers and simplistic acceleration with good results. But handling 'complex trajectories with arcs and multiple concatenated line segments' is well beyond my ken, and it would be good to see that phased in when appropriate.

    It is clear you know what you are talking about and your thoughts on designing and producing your multi-axis control board using all discrete components was fascinating.

    I do hope you decide to do it anyway.


    Dave

  • ManAtWorkManAtWork Posts: 2,076
    edited 2021-01-26 08:33

    Ok, then let's start. The first thing we need is the actual step pulse generator. My idea is NOT to create any variable timing loops to generate the frequency sweeps like often seen on other processors. Instead I would set up a fixed time frame and calculate how many steps have to be output for each axis within each time frame. So I'd do it somehow like this:

    'Step/dir signal generator 
    ' step pins have to be a continous range to allow usage of ADDPINS
    ' stepPin[0..3] = basePin + 0..3
    ' dirPin[0..3] = basePin + 4..7
    
    CON 
     _xtlfreq = 20_000_000
     _clkfreq = 180_000_000
     timeSlice = _clkfreq / 1000 ' 1ms
    
    VAR
     byte cog
     byte basePin ' first of 8 pins
    
    PUB Start (pin1) | i
     basePin:= pin1
     repeat i from 0 to 7
       pinStp0[i]:= pin1+i
     pinStpAll:= basePin ADDPINS 3
     pinDirAll:= basePin+4 ADDPINS 3
     cog:= cognew (@StepDirCode, 0) + 1
    
    PUB Stop
     if cog
       cogstop (cog~ - 1)
    
    ' to be implemented...
    PUB SetVelocity (v)
    PUB SetAcceleration (a)
    PUB AddLinMove (vectorPtr)
    
    DAT
    ORG
    StepDirCode
               fltl  pinStpAll
               wrpin nco_mode,pinStpAll
               wxpin nco_phase,pinStpAll
               wypin #0,pinStpAll
               drvl  pinStpAll
               drvl  pinDirAll
               getct nextTick
    mainLoop
               addct1 nextTick,tickPeriod
               waitct1
               wxpin nco_phase,pinStpAll ' clear phase
               testb stepFrq+0,#31 wc   ' extract sign
               outc  pinDir0            ' set direction
               wypin stepFrq+0,pinStp0  ' set FRQ value
               testb stepFrq+1,#31 wc
               outc  pinDir1
               wypin stepFrq+1,pinStp1
               testb stepFrq+2,#31 wc
               outc  pinDir2
               wypin stepFrq+2,pinStp2
               testb stepFrq+3,#31 wc
               outc  pinDir3
               wypin stepFrq+3,pinStp3
               call  #calculateSteps  ' update stepFrq[]
               jmp   #mainLoop
    
    
    stepFrq    long 0,0,0,0 ' NCO FRQ value for each axis (signed)
    ' calculated as 2^32 / timeSlice * number of steps to be outpu
    ' smart pin Z value has to be re-synchronized each frame becaue
    ' of division remainder dropped
    
    tickPeriod long timeSlice
    nco_mode   long P_NCO_FREQ + P_OE
    nco_phase  long $4000_0001 ' phase = middle of low time, frame = 1
    nextTick   long 0
    pinStpAll  long 0 ADDPINS 3
    pinDirAll  long 4 ADDPINS 3
    pinStp0    long 0
    pinStp1    long 1
    pinStp2    long 2
    pinStp3    long 3
    pinDir0    long 4
    pinDir1    long 5
    pinDir2    long 6
    pinDir3    long 7
    
    

    Warning: this is totally un-tested and the most interesting part (functions calculateSteps and AddLinMove) are still missing. But you said I should do it step by step. 😁

  • ErNaErNa Posts: 1,742

    Just a comment: the advantage of a constant time slice is that distance and speed are equal (to a factor) as speed is distance over time. So you just have to determine the time slice for a single step and set the timer to an appropriate value to create the step pulses. Acceleration can be handled similarly: Constant acceleration just means to add a constant value to speed. And if you like to ramp at a given acceleration to a given speed, the average speed will be have the target speed and the distance to accelerate is easily calculated. This method is independed from the time scale, there can be many steps or a decision is there is a step or not. Also, once implemented, the algorithm can be cascaded. Running some axis in parallel also is no longer a problem as the trajectory can be broken up to the axes and they are just handled separately.

  • ManAtWorkManAtWork Posts: 2,076
    edited 2021-01-26 09:22

    And another interesting thing: For classical, theoretical newton dynamics time is reversible. Instead of trying to look into the future (which is difficult) you could just flip the sign of the time axis and look into the past (which is easy). So if you know your destination (where to stop) you don't need to pre-calculate the deceleration ramp. Instead, we just put a filter (which is a tapped delay line, a look into the past) over a constant velocity profile.

    So the next thing we need is a moving average filter, or several of them. I'm not good at drawing charts with the computer so I took a pencil and a scanner:

    A linear interpolator outputs a scalar value for every time slice that represents a position on the toolpath (one-dimensional). This value is filtered two times to get a trapezoid and then an S-shaped velocity profile. The 1D value is then transformed into a vector by projection onto the toolpath. The 3 (or more) coordinates are then filtered again, seperately. This is not neccessary for point-to-point movements and would make no difference in this case. But it is necessary for trajectories of concatenated line segments to smoothen the corners and avoid acceleration peaks. The output of each filter is multiplied by a scaling factor and written to the smart pins to finally generate the pulse outputs.

    It may take some time until I can show up with more code because this time I have to test it.😬☝️

  • Ok, a prototype of a variable configureable length moving average filter is working. But I won't make an universal filter object, at least not for the first go.

  • It would be nice to have in stock a low-cost system that fully mimics something larger. Based on the above comments, I think we would add this to our inventory:

    https://www.pololu.com/product/2981 and a NEMA 17 stepper motor like this https://www.amazon.com/Usongshine-Stepper-17HS4401S-Connector-Printer/dp/B0787BQ4WH/

    We would create a stepper driver object for multiple motors allowing step, direction, speed and ramping.

    How does that sound?

    Ken Gracey


  • Yup, that sounds good.

    I have always believed a basic CNC learning module using steppers with code examples is essential for hobby and education.

    It should include some sort of simple G-code handler.

    G-code is the basis for most CNC machines and it is essential to link it in with the stepping modules.

  • Yes, understood and agreed about G-code handling. For starters, we'll get an object going with G01 support. At the moment, we have nothing, and could certainly add to a starter object.


    I'll be adding the Pololu A4988 Stepper Drive to stock and a motor too.


    Ken Gracey

  • And thanks, Dennis. Learning the new forum software.


    Ken

  • Cluso99Cluso99 Posts: 18,069
    edited 2021-01-27 07:50

    Ken,

    There are now better drivers than the A4988. Unfortunately I haven’t kept up to date with those parts or their cost. Just wanted you to be aware.

    Many 3D printer users are now updating their driver boards to use the better and quieter driver boards. Even the cheap Ender 3 now offer an upgrade board.

Sign In or Register to comment.