Connect with us

Current limiting strategies for L298N?...

Discussion in 'General Electronics Discussion' started by BGB, Dec 9, 2014.

Scroll to continue with content
  1. BGB

    BGB

    154
    11
    Nov 30, 2014
    well, here is the issue:
    I am building a project (a small CNC milling machine), and for the steppers am going to be using some L298N chips.

    these will be driven from a Raspberry Pi, possibly with step-up transistors (data sheet seems to imply it is intended to be driven with 5v 30mA signals, but RPi outputs are 3.3v 3mA, with a 1k resistor).

    issue (uncertainty after reading lots of random forum posts):
    apparently, there is a need to current limit the L298N chips, so that hopefully they don't fry (apparently pretty common with these things).
    reading stuff online implies that they need 0.5 ohm to ground on sense (regardless of whether or not current sensing is used? people seemed to debate this, claiming it is safe to connect them directly to ground), and need to be current limited to around 3A so that they don't fry themselves if any inputs get stuck on for too long, as well as them needing a good heat-sink (screwing them onto an old PC heat sink with a fan?).

    there is also mention of people using a 10 ohm power-resistor into the Vs pin.


    for resistance, I have found a few possible options:
    some old clothes line from outside has some metal wire in it, which seems to have around 1 ohm per foot (measured via the voltage drop method), so about 6 inches of this wire should be sufficient for the sense pins. (it is also springy, resistant to bending, yellowish, and ferromagnetic). it also seems to accept solder well.

    could possibly wrap one or more pieces of this wire around something, and maybe put some clay on it to make some resistors. (don't really want to order power-resistors, these resistors would cost nearly as much as the motor drivers...).


    I have tested the wire, and have noted that it starts warming much past 1A, gets hot and starts blackening at 2A, faintly glows red at 3A, and basically lights up like a toaster at 5A (it did not burn up or break in these tests, but did start to become fairly limp and prone to sag, as well as glowing a bright yellow-orange color, as well as increasing its voltage drop). I have little idea what its properties will be like with prolonged use, or if heating it red-hot adversely effects its metal properties.

    so, around several feet of this wire (and a fuse?) should be sufficient to get enough resistance to keep the motor drivers safe.

    probably need to limit total power to around 3A, or 4 ohm (3A is within L298N max amps, and roughly sufficient to run 3 steppers at 1A each). for a single strand, this would be 4 feet of wire.


    another noted option is that I have some L7812CV voltage regulators, which claim to have built-in current limiting (to 1.5A), which should work. though (untested), with a 12V input, these should only produce around 10V output (they are designed for a 14V-35V input), but would require multiple regulators.

    also have some LM317 adjustable regulators. apparently these can also be used as current regulators.


    I could also build some proper current-limiting circuits for this, but this option looks like more effort. for this though, I could probably use a wire-tie ("twist tie") as a shunt (sense resistor), noting that wire tie is approx 0.15 ohm, or around 0.075 ohm if folded in half (in my tests, I got similar measurements from several styles of ties). in a test with wire ties, only slight warming was noticed at 3A. though, solder doesn't really stick well to ties IME.

    it would then be a matter of fiddling it into allowing the desired current flows.


    thoughts?...
     
  2. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    Just some initial thoughts...

    Use a PTC resettable fuse in series with the load to deal with long term overloads

    Use a more modern H-bridge IC such as the TLE5206-2S (http://www.digikey.com/product-detail/en/TLE5206-2S/TLE5206-2S-ND/1283081) or anything from this Digi-Key product filter: http://www.digikey.com/product-search/en?FV=fff40027,fff802d2,2040002,2040005,2040009,2040011,2040012,2040015,2040050,20400c4,2040119,2040433,204049b,20404b2,2040757,3fc0059,3fc005a,3fc0060,3fc0064,3fc0068&ColumnSort=-69&stock=1&quantity=1&pageSize=500

    Edit: I wouldn't recommend inserting current limiting or a series resistor in the power supply feed to the H-bridge IC.
     
  3. BGB

    BGB

    154
    11
    Nov 30, 2014
    possible, but:
    I already have the L298N chips here (the order showed up);
    those drivers listed there are generally significantly more expensive.
    as-in, any good options under around $4 per stepper motor or so?
    (well, and also don't want to order anything more right now).

    not current limiting ICs: as-in, you think it is probably unnecessary?...
    don't have any PTC's at present, automotive fuses are the main thing I have available.

    was probably going to use automotive fuses either way as a fallback, but they have the drawback of a fairly slow response time, and once they blow, they need to be replaced (these aren't exactly all that cheap either, but worst case here is a trip to the auto-parts store).


    ADD:
    I guess another option could use sense resistors (like in the design in the datasheet), but maybe rig up a circuit to toggle the Enable pins. for example, if there is a voltage drop across the sense resistor, a transistor pulls the Enable pins to ground (where Enable would be normally connected via a resistor to +5V). this would just use a few 2N3904 transistors or similar.
     
    Last edited: Dec 9, 2014
  4. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    I doubt it.
    No. Sorry to be unclear. More likely to cause problems. ICs aren't supposed to be powered from flimsy supply voltages. It's best to give the IC a stable supply and perform the current limiting in its output connections.
    They won't do you much good. Get some PTC resettable fuses. They're not expensive.
    Yeah, not suitable.
    What kind of problem are you trying to detect? A wiring short? A failure in a motor? A mechanical jam? Something else? Do you want the driver to lock out as soon as overcurrent is detected? If so, you would need a latch, and possibly a delay and retry.
     
  5. BGB

    BGB

    154
    11
    Nov 30, 2014
    yeah. cost was a partial deciding factor, along with having sufficient output current, and giving reasonably direct control over the motors' behavior.


    makes sense. rated input voltages are 7.5V to 46V.

    none of the diagrams I see show current-limiting on the motor side though (though, most include flyback diodes).


    yeah, though it may need to wait until the next time I can get some stuff ordered. parents may be a bit annoyed if I ask to order more stuff again so quickly.

    automotive fuses may work for an extended dead-short, but are of little use for quick-response, or for modulating the amount of current fed into a load.


    most likely problem case is from holding a motor in a single position for too long, in which case the inductance fields will collapse and the motor will start pulling lots of current. likewise goes for low-RPM operation (where the motor spins slowly, but will pull however much current is given to it).

    another possible issue would be the control-program crashing with the output pins left enabled (for a correctly operating program, generally the logic should reduce the duty cycle during low-speed operation or for holding a position).

    in this case, it is needed to throttle the amperage back enough, so that hopefully things don't fry.

    apparently, the way the driver is designed, the idea is that the controller will modulate the duty-cycle based on the voltage drop across an external "sense resistor".

    so, the chip provides CsA and CsB which are intended to be connected to ground via a low-impedance sense resistor. also EnA and EnB which are used to enable the internal H-bridges.

    so, likely, CsA and CsB could be linked together and fed through a shared resistor, and a transistor could pull down a signal to EnA and EnB if the current exceeds the limit, effectively modulating the bridge.

    then again, for all I know, this is more-or-less what these pins are intended for?...
     
  6. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    Yes, likewise. But the overcurrent detection is a valid approach. The question is, what do you do when overcurrent is detected?
    Oh dear. Well, if it helps, you can tell them from me (formerly a professional electronic design engineer for 20 years) that IMO you just can't buy, or put a value on, the depth of understanding that you will get from experimenting with stuff. You try something, it works partly but not properly. You figure out why. You change it and try again. And so on. This hands-on learning is mimicked in classrooms but that is never quite the same as really having to nut it out yourself, because there's always time pressure and the tutor can just fix things for you.

    My parents supported me to a moderate extent - they bought me electronics magazines (this was the 1970s and 1980s - over a decade B.I. (Before Internet). They bought me parts, and held their tongues when I was playing around with TV sets that could easily have killed me! The only thing I didn't have, that I wish I had, was mentors. But now that you've found this site, you can get direct help with your questions as well.

    Education is fantastic and very important too, of course. You need a good balance of theory and hands-on.

    BTW while I remember... why don't you put your date of birth in your profile, so the forum software will show your age. If you're young, you may get more help than if you're an old dog that might be less enthusiastic about learning new tricks, and the advice may be more appropriate for your situation.
    Yeah, I'd forget about them.
    I think the problem would be magnetic saturation, wouldn't it? I'm not sure.
    Right, same problem.

    If a stepper motor pulls too much current if powered constantly, I think that might indicate a design problem. I think the steady-state maximum current should be limited by the DC resistance of the motor windings, and/or the power supply voltage, and/or an current limiting in the driver IC, and/or an external series resistor (in series with each stepper motor winding, not the power supply to the driver IC).

    AFAIK you should be able to step a stepper motor to a particular position, then hold it there indefinitely with one winding energised. Perhaps I'm wrong about this. I haven't done much with stepper motors. What do you know about this?
    Oh, I see. You're using PWM generated by your MCU to modulate the current to the steppers. That's pretty cool.

    Here's a suggestion to consider. How about detecting overcurrent using the current shunt resistor in the emitter circuit, as you described, and have it trigger an interrupt or NMI in your controller. The controller can then force its outputs OFF immediately, protecting the L298N, and send out some diagnostic information with variable values, etc, so you can figure out what went wrong.

    To do that, you can probably just connect an NPN with its emitter to 0V and its base through a series resistor (e.g. 1 kΩ) to the top of the current shunt resistor. When the voltage across the current shunt resistor reaches ~0.65V, the transistor will turn ON and its collector will trigger the interrupt. You might need a small capacitor (e.g. 1~10 nF) from base to emitter to prevent nuisance triggering from very brief current pulses.
    Oh, I see. That's another option I suppose.

    Is this some kind of DIY project you're building up? Can you post a link to it?
    It sounds like it. We need to have a look at the project.

    Someone else here, Gryd3 I think or maybe Fish4Fun, has a lot of experience with CNC and should be able to help on this thread.
     
  7. BGB

    BGB

    154
    11
    Nov 30, 2014
    limit and wait for manual intervention?
    maybe also turn on a LED and send back a signal?
    (then software can initiate an emergency shutdown if this was unexpected?)


    I am not really all that young anymore, more like, basically just a loser.
    never got a job, never moved out, don't have a GF either, ...

    but, yeah, I was born back in the 80s. I don't really remember much from before the time of PCs and the internet though (the 90s was a pretty weird time as is).

    I had spent most of my life (since elementary school) doing programming as a hobby (primarily C, C++, and ASM), but couldn't get a job doing it professionally. likewise, none of my personal projects have made any money.

    recently (earlier this year), I had gained more of an interest in electronics and robotics, and have since started going back to college in the vague hope of getting a job eventually (probably doing maintenance work or something).

    so, it has basically been a crash-course in electronics, and trying to make parts from various materials, mostly using hand-tools (have made parts from wood and aluminum using hand tools).

    doing real-time motor control code does have a little impact on coding style, given timing issues are a fair bit more important than in typical PC software.


    probably better than nothing if a short occurs, like to keep wires from melting.

    though, if running off of a PC PSU, it will effectively disable itself well before wires start to melt down (milliseconds?).


    yes, maybe.

    in any case, motor current seems to depend a fair bit on how fast it is spinning:
    faster spinning generally results in lower current draw.

    IME, often the static resistance of the coils is pretty low, so at 12v, a stalled motor will try to pull around 36 to 80 amps (where 0.10 to 0.33 ohm seems fairly typical for motor windings).


    these steppers have approx 3 ohm windings, so at 12v will pull 4 amps from each coil (or 8A for both coils). neither the motor nor driver are rated for this much current.

    AFAICT, the L298 does not provide internal current limiting, but does provide for thermal shutdown.


    yes, but probably not at 100% duty cycle.


    it is actually PDM, but both PDM and PWM serve essentially the same role here.

    I have already run various types of motors, generally using hand-wired driver circuits.
    nevermind my sometimes mixed results with the driver circuits.

    I have run brushed DC, brushless DC, and bipolar steppers this way.

    the main reason for the motor drivers is mostly to save needing to build the driver circuits by hand.


    I may also signal back to the controller, but it wont necessarily respond if the control program has crashed or similar.

    however, potentially getting an unexpected overcurrent signal could be interpreted as grounds for an immediate shutdown (as it likely means that a motor has stalled).


    I was thinking I could probably use similar both for current limiting, and also for detecting the over-current (probably with a transistor watching for the +5v enable wire to go low, at which point this wire would rise to +3.3v).


    I was mostly writing about how to wire up the pins for the L298N.

    I drew out a diagram earlier on paper for how I might wire it up.
    ATM, still waiting on some diodes and similar to show up, and am also pretty low on perfboard (also ordered some more of this).

    partly slightly unhappy that a L298N doesn't fit into a 16-pin DIP socket (unusual pin spacing), don't necessarily want to wire-wrap or solder it to a prototype board. could maybe modify the DIP socket to fit the L298N.


    but, yeah, still stuff for the CNC.
    XYZ motors will be steppers using L298N chips, with the main tool motor driven by a hand-wired H-bridge.

    will probably label the GPIO pins:
    Xa, Xb, Xc, Xd, Ya, Yb, Yc, Yd (XY Axis Steppers)
    Za, Zb, Zc, Zd (Z Axis Stepper)
    Ta, Tb (Tool)
    Lx, Ly, Lz (Limit Switches)
    Cxyz (XYZ Overcurrent)
    Ct (Tool Overcurrent)

    actually, if possible, I may want more buttons (and both positive/negative limit switches and some control buttons), but, this would require a good way to multiplex the buttons over fewer pins (shift register, or some way to address the desired button or switch).
     
  8. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    Sounds like you're being a bit hard on yourself. You seem pretty smart - assembly language programming is not for the faint of head, and your written English is very good. You even know how to use semicolons and colons. You sound a bit like me really!

    I'd like to have a chat sometime. I'll take it to a PM though.
    Sounds like you have a few talents. Perhaps you just need to find the right company where your abilities can be put to good use.
    Sure is! And a lot more fun!
    Not that fast, I don't think. There's a few thousand µF of smoothing in the PC power supply that needs to discharge a bit before the controller will even notice there's something wrong. It would be fast enough to protect the wires, but maybe not the L298N. That's why I think you should monitor the output current using a current shunt resistor and respond pretty quickly when it goes too high.
    Oh! That's a very low resistance.
    So you need to use some trick to limit the current in situations where the motor is moving slowly or is stopped? You would either limit the actual current by reducing the bias on the driver devices, or you would use PWM to get the same effect?

    Is that normal for stepper motors?
    OK. So you need to monitor the current with a shunt resistor and protect the L298N by controlling its enable input when the current gets too high. I guess that's clear.
    That's interesting. It seems to be the same as a technique called DPWM, distributed pulse width modulation, which I saw described on some old Philips IC or other. It's just explained differently.
    Sure. It's the sensible way to go, unless you have lots of time and not much money. Oh, wait... :)
    Right, but I think that would be a sensible first action. You could have hardware that detects if the overcurrent signal has been active continuously for a short time - e.g. 10 ms - and if so, latches ON and disables the driver completely. Just in case the firmware does crash. That would be a fatal error.
    Would there be any way to recover and keep going in that situation? If so, firmware should try to handle it; if not, you might as well treat it as another pathological case.
    Not sure what you mean by the last part. But yes, you could use the transistor's collector signal as feedback to firmware, and also have simple circuitry to detect a constant high current indication for a period of time and lock out the whole driver.
    Doesn't the Raspberry Pi have much I/O?
     
  9. BGB

    BGB

    154
    11
    Nov 30, 2014
    my confidence is a bit lacking sometimes, as I don't have a whole lot to show for my time.

    I have actually written some compilers and VMs as well, which is where a lot of the ASM goes. most of my ASM experience has been for x86 in 32 and 64-bit modes, some past experience with 16-bit. also have had some limited experience with ARM, but at least thus far, I more prefer x86 (it is the little things, like being able to load something from memory, or load a large constant into a register, in a single instruction...).


    possibly.


    I have noticed that if I connect a motor directly to the PSU, if it is going to die, it dies pretty much immediately after contact (and, at most, the motor will jerk slightly).

    if I am going through some transistors (such as in an H-bridge), it seems to buffer it, and the motor can spin up without killing the PSU. basically, the transistors seem to have to some extent a current-limiting effect.


    yeah, at least this seems to be the case for higher-power low-voltage DC motors (such as power-tool motors). the windings also tend to be relatively thick gague wire as well (like 18 or 20 AWG or so).

    low-power toy motors and also larger AC motors seem to use thinner wire and have higher resistances.


    I think it is.

    a lot of people seem to interpret the rated voltage and amperage more as a guideline though.


    yeah.


    I am using Pulse Density Modulation.

    basically, instead of turning pins on and off at very specific times (harder to pull off well in software), the update is run at a fixed frequency, and the pins are turned on and off to best approximate a given duty cycle.

    the current implementation uses bit-counts and a lookup table.
    the counts are bit-packed and used as a table index. the target value is then compared with the value at the current index, and the counts are adjusted as-needed (the appropriate count is incremented after each bit is output, and occasionally the counts are right-shifted to keep them in range).

    though a linear index and smaller lookup table could be potentially more efficient, this does not currently seem to be an issue (at least vs most of the CPU time going into the delay loop).

    I have been thinking of ways to better allow low-priority code to coexist with the motor-control code and better utilize CPU resources.


    also multiple sub-projects. a preceding project was trying to build a large quadrotor, but then got stalled on needing to make some parts which were proving difficult to make, and which would be unreasonably expensive to buy (namely 20 inch propellers).

    a CNC machine could be a way forwards, so the idea was basically to try to build a reasonably low-cost CNC machine to make parts to allow moving forward on other projects. granted, most of the existing options were either too expensive or too limited (can't spend $k on a CNC machine, nor have much use for something which can only mill 4 inch blocks of plastic or similar).


    basically, it would be a combination of a HW and SW solution.
    the HW will current limit, and the SW will get back a signal and then decide what behavior is appropriate.


    it has GPIO, but all the outputs and buttons I might want would still exceed the available number of available GPIO pins on the B+.

    I have enough pins for the current set of inputs and outputs, but this uses up pretty much all of them.
     
  10. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    That's pretty impressive! Writing a compiler from scratch is no mean feat.
    I guess it depends on the design. They're not supposed to be used as current limiters though!
    Right, that's how DPWM works.
    The algorithm for DPWM is much simpler and should translate to your requirements I think. This is for 8-bit DPWM.

    Each DPWM output has an associated 8-bit duty cycle control value and an 8-bit variable called 'remainder' or similar. On each regular interrupt, you process and update each DPWM output in turn. You add the duty cycle control value into the remainder value. If this results in a carry, you set the output pin high; if it doesn't, you set it low. That's it.

    If you run a few examples through that algorithm you'll see how it works. It would be a good choice for implementing in an FPGA too!

    It's also easy to convert to any top-of-scale value. A duty cycle control value of 0 always gives an output that's permanently OFF, and in that example, the duty cycle contol value that generates a permanently ON output is actually 256, which can't be represented, unless you make the duty cycle control value wider than the remainder.

    But you can set the top-of-scale value to 255 if you change the update code in the interrupt handler so the result of adding the duty cycle control value and the remainder variable is wider than both, then compare the result to 255 (or whatever top-of-scale value you want). If it's less, set the output LOW and store the result back to the remainder variable. If it's greater or equal, set the output HIGH, subtract the top-of-scale value, and store the result back to the remainder variable.
    I would get the software to do the limiting, because that gives you more options, with a hardware override if the overcurrent condition remains present for too long (i.e. the software is not dealing with it). But I'm sure you know what you're doing. Let me know if you want any suggestions.
     
    hevans1944 likes this.
  11. BGB

    BGB

    154
    11
    Nov 30, 2014
    yeah.
    some of it is for special use-cases.

    like there are times when things don't exactly fit all that well with the standard "compile directly to native code" approach of typical compilers, ...

    for example, in its current incarnation, the C compiler compiles to an intermediate 3-address-code register-oriented bytecode, and then runs it in an interpreter, more-or-less basically similar to Dalvik. later on, I may write a JIT or AOT compiler, but haven't done so yet (another of my VMs has a JIT though).

    I am also mostly off trying to think up a good way use it to better utilize the time that is currently mostly spent spinning in the delay loop in the motor control program. even if the interpreter is slow, if it can make better use of this, it is probably a win, even if the raw linear performance is arguably lower than directly compiled native code would be.

    as-is, the motor-control program is a mess of asynchronous callbacks and event-driven code. conventional coding strategies are no-go (would introduce delays), and conventional threads don't really work so well here.

    so, the partial idea is to maybe (when applicable) be able to use the interpreter partially in place of the delay loop (it will fall back to the delay loop either for very short delays, or when the interpreter doesn't have anything to do).


    granted, though this was with H-bridges built out of discrete components.
    I have little idea about driver ICs, but from what I can gather, they are a bit more sensitive and more easily damaged.

    it seems though that when wired up normally, the power-transistors seem to be current-limited to some extent, but I haven't fully investigated.

    in particular, power-transistors rarely give output much higher than their rated current, and even then, will only give this if they are freshly turned on or have a reasonably good heat-sink (output current drops significantly if they get hot, like a 10 amp transistor may only give around 1 or 2 amps).

    though, small transistors (TO-92 variety) don't seem to exhibit any current-limiting effects.
    lots of other interesting stuff can happen though... like they can melt solder or decide to physically leave the board (all like, "screw this, I'm outta here").


    ok.
    that seems to make sense I guess.

    mine had been based on the basic algorithm used in a bitwise arithmetic coder (just repurposed and partially inverted).

    a basic version of the pin-output logic could be:
    idx=pdm_index[pin];
    if(pdm_divtab[idx]>=pdm_target[pin])
    { outputPin(pin, 0); pdm_index[pin]=pdm_nextidx0[idx]; }
    else
    { outputPin(pin, 1); pdm_index[pin]=pdm_nextidx1[idx]; }

    where index is (logically, if counts are limited to 15):
    bits 0-3: running count of 0 bits;
    bits 4-7: running count of 1 bits.

    and the tables are prebuilt as:
    pdm_divtab[(c1<<4)|c0]=(c1*256)/(c0+c1+2);
    c2=c0+1; c3=c1; if(c2>15) { c2>>=1; c3>>=1; }
    pdm_nextidx0[(c1<<4)|c0]=(c3<<4)|c2;
    c2=c0; c3=c1+1; if(c3>15) { c2>>=1; c3>>=1; }
    pdm_nextidx1[(c1<<4)|c0]=(c3<<4)|c2;

    but, could be fudged, say:
    pdm_divtab[(c1<<4)|c0]=(c1*288)/(c0+c1+2);
    c2=c0+1; c3=c1; if(c2>15) { c2=(c2*240)>>8; c3=(c3*240)>>8; }
    pdm_nextidx0[(c1<<4)|c0]=(c3<<4)|c2;
    c2=c0; c3=c1+1; if(c3>15) { c2=(c2*240)>>8; c3=(c3*240)>>8; }
    pdm_nextidx1[(c1<<4)|c0]=(c3<<4)|c2;

    where the duty-cycle is biased upwards, and the counts clamping is based on saturation, mostly to compensate for the reduction in count range.

    the current version is similar, mostly just using bigger tables and a larger count range.

    but, 768 bytes of tables is cheaper than, say, 24kB (as is needed for a 6-bit count).


    well, it is possible...


    I guess it could be possible maybe to bias it so that the software overcurrent sensing is triggered at a lower voltage than the hardware overcurrent handling.

    for example, if the software current sensing triggers at 0.25v across the shunt, and the HW current handling triggers at 0.4v.
     
  12. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    Well, only if there are other things that you need (or want) to do. Another option would be to use an FPGA for the motor control, or use a micro that has a built-in FPGA component.
    Perhaps.
    Could a table-driven system give better performance than the method I described for DPWM? I don't see how. The DPWM method doesn't need a table; it just uses one remainder variable for each output.
    Sure. Just feed the current shunt voltage into an analogue input on the controller, and also monitor it in hardware using a comparator or just a transistor's base-emitter junction, if you choose the shunt resistor so the hardware should trigger around 0.7V. Using a single overcurrent signal, with a timer for the hardware override part, would be a bit simpler, but providing the current as an analogue would give you the opportunity for smarter control.
     
  13. BGB

    BGB

    154
    11
    Nov 30, 2014
    or, maybe a Raspberry Pi + an Arduino.
    then the Arduino can be left for motor control, with the Raspberry Pi mostly for running application code.

    or maybe a Beagle Bone Black or similar... (more expensive than an RPi by itself, but price competitive with an RPi+Arduino).


    but, yeah, running motor control on the RPi does burden things a bit, since the motor control code doesn't play well with anything else using the CPU, and the thing has a single-core processor.

    part of the issue mostly has to do with scheduling latency, where the normal Linux scheduler just can't really pull off (reasonably accurate) microsecond timing delays, so I took the approach of setting up the motor-control process essentially as a high-priority real-time task, and am running most of the stuff in-program in my own scheduler, which internally does its timing with a delay loop. but, running a real-time task doing timing with a delay loop (and only occasionally sleeping) does leave anything else pretty much CPU-starved.

    thus far, it hasn't been too serious of an issue though.

    I guess another partial question could be, how much can be done on the GPU on the RPi?...

    looking, it could possibly be useful, if there is a good way to get custom code running on it (the RPi doesn't support OpenCL). the thing is basically has 4 cores each running 4 parallel threads.


    yeah.


    the performance of this isn't really a big issue at the moment.
    I am left thinking I may want to set up a test, where I can compare different strategies.

    the main things I might be looking at are mostly precision and responsiveness though.

    as-in, what strategy does best at generating a specific constant duty-cycle, and which do best at approximating a continuously changing target value (such as sine-waves at various frequency ranges, or test against an audio sample).


    ADD: tested... yeah, the algorithm you described seems to give the most accurate output both for the constant-value and sine-wave tests:
    Constant Value RMSE: DPWM=4.9, PDM8=10.85, PDM12=5.79
    Sine Test RMSE: DPWM=10.99, PDM8=16.17, PDM12=22.80


    the Raspberry Pi doesn't have analog inputs (this would require using an external ADC or similar).

    so, a single-bit digital input is more likely.

    but, yeah, the sensing could probably be implemented with a transistor and a voltage-divider (to pull the voltage up slightly so the transistor can trigger on a lower voltage, allowing a lower-resistance for the shunt).
     
    Last edited: Dec 13, 2014
  14. BGB

    BGB

    154
    11
    Nov 30, 2014
    ADD2 (seems I can no longer edit the prior post):

    here are some RMSE results:
    Const DPWM Err: Avg=4.9489 Min=0.0000 Max=5.4065
    Const PDM8 Err: Avg=10.8478 Min=0.0000 Max=27.8420
    Const PDM12 Err: Avg=5.7890 Min=0.0000 Max=10.6192
    Sin DPWM Err: Avg=10.9892 Min=4.7250 Max=85.7736
    Sin PDM8 Err: Avg=16.1658 Min=9.8554 Max=81.2399
    Sin PDM12 Err: Avg=22.7955 Min=6.0577 Max=84.6889
    Wav DPWM Err: 15.2915
    Wav PDM8 Err: 9.2706
    Wav PDM12 Err: 35.4503

    where this is the result of applying check against a low-pass filtered version of the PWM output signal (with a 16 sample kernel).

    or, put another way:
    DPWM does best on holding constant values and on the sine-wave test.


    interestingly, PDM8 seems to do best with a song (44.1kHz, with the duty-cycle updated per-sample once per output bit).

    comparing based in listening to the output:
    PDM8 best recreates the audio of the song (*);
    PDM12 also works ok, but introduces a fair bit of distortion and amplification;
    DPWM sounds the worst, introducing a fair amount of buzz and hiss, and largely eliminating most higher-frequency features...

    *: audio quality is almost passable, though there is an obvious "squeal". zooming in, shows basically a repeating sawtooth wave pattern. fiddling with the tables can eliminate the squeal and increase perceptual quality, but makes overall RMSE worse.


    not really that music is the intended use-case, but music does help point out things like frequency response and similar.
     
  15. hevans1944

    hevans1944 Hop - AC8NS

    4,521
    2,104
    Jun 21, 2012
    @BGB I'm not sure where this tread is going, but I thought I would jump in to stir the pot a little and maybe learn something too. I've not been on Electronics Point very long, but I have found the advice and comments given by @KrisBlueNZ to be accurate and helpful. We are fortunate to have him as such an enthusiastic participant here.

    I think it is very ambitious of you to build a CNC milling machine. If I were more organized I might attempt that myself. My most ambitious project so far is a largish magnetic-loop antenna that requires a small stepper motor to tune the antenna resonating capacitor. What I have on hand is an old Superior Electric SLO-SYN AC synchronous/DC stepping motor, model M061-FD08. I think this motor is similar to the Asian import you are using, but American-made sometime in the last century... and very expensive if I had to replace it. Actually, I could not afford to replace it, but we are blessed with an excellent surplus electronics dealer here in Dayton that often has similar or larger stepper motors for sale at reasonable prices. They sold me this motor for five or ten bucks IIRC about twenty years ago.

    So, anyway, I need to be careful powering my stepper since I can't afford to replace it if I let the magic smoke out. Of course I could order a replacement stepper from Asia, but that would require a whole new re-examination of whatever driver I used on the Superior Electric motor.

    Many years ago I was responsible for adding a stepper motor drive to the wavelength selection shaft of a large laboratory monochrometer. The project went well until we turned it on and discovered the stepper motor introduced oscillations in the shaft with each step. Fortunately the motor had a double-ended shaft and Superior Electric had a solution: add an harmonic dampener to the other end of the shaft. Back in those days (circa 1967) we didn't know anything about PWM drives for stepping motors. Instead we brute forced it with large series power resistors and higher voltage power supplies. I think the series "ballast" resistors dissipated more power than the motor we used. They were mounted in a relay rack cabinet with muffin fans to cool them.

    So flash forward to the 21st century and more efficient stepper motor drivers. By reading this thread I discovered the L298N H-Bridge driver and, by researching the web, its companion L297 PWM driver. I have attached PDF file application notes. I don't understand why you want to do pulse density modulation in software when there is hardware available to do the same thing? I have a Raspberry Pi that my son gave me a few years ago and I plan to use it to interface to my stepper motor controller. But first I have to get the motor running. It has modest specifications: 1.25 V DC at 3.8 A continuous duty, 0.33 Ω winding resistance, 0.64 mH winding inductance. I will purchase a L298N H-Bridge to drive the motor and an L297 PWM driver for the H-Bridge.

    Where is your CNC milling project now? Have you purchased lead screws yet? I found some nice ones at McMaster-Carr but they are pricey. I am using 1/4-20 stainless steel allthread, purchased at Ace Hardware, with a brass nut for my antenna tuning capacitors.
     

    Attached Files:

    KrisBlueNZ likes this.
  16. BGB

    BGB

    154
    11
    Nov 30, 2014
    I could have bought the L297, but that adds a little more cost, and you still need to give the thing accurately timed pulses, so it is about the same between using software PDM and an L297, apart from maybe saving a few GPIO pins and similar with the L297.

    the RPi's SoC is 700MHz, so raw speed isn't too much of an issue, just the general inaccuracy of the Linux scheduler isn't so good here (generally need reasonably accurate microsecond delays, whereas the OS scheduler seems only really accurate to around 1ms or so, which is nowhere near 1us), but this does make things a bit messy.

    yeah, my motors weren't drastically expensive, they were about $16 each.

    I am using 3/8-16 all-thread...
    could buy some acme-thread or something, but, expensive...

    I am at the stage of basically having some of the motors spinning and am working on the code. I still need to get plywood and build a box, and put in the steel rods, and make some metal motor-couplers and similar (have been using things like clay and hot-glue, neither of which would likely be sufficient for the actual machine).


    as for the PDM, I made the algorithm be settable per pin, so it is possible to select whichever algorithm is better suited to the task.

    I am also deciding between strategies for inter-board interlinking.

    possible options:
    wire-wrap pin-headers, which can be done without buying anything (lame, but cheapest);
    repurposed RJ45, which requires buying stuff and using slightly more expensive jacks, but could be pretty convenient (CAT3 or CAT5 cables with crimped on connectors);
    dupont connectors, but I currently only have a limited number of the metal inserts, and aren't really a great for lots of wires;
    ribbon cables, which requires more analysis;
    ...
     
  17. hevans1944

    hevans1944 Hop - AC8NS

    4,521
    2,104
    Jun 21, 2012
    Say what? The L297 generates its own PWM pulses with an on-board RC oscillator. You synchronize two or more (in your case three for XYZ and perhaps four if you have a stepper motor for the spindle) L297 using the built-in oscillator from just one of them to sync to the others. Did you even read the application notes I attached in post #15? The L297 is widely available at low cost, about $9.25 each from Mouser for example. E-bay prices are cheaper, but caveat emptor there.

    NO "accurately timed pulses" are necessary or required to use the L297 connected to the L298 H-bridge driver. You supply the stepping pulses at whatever rate you want the motor to step, along with a direction logic input, the L297, with feedback from the current-sensing resistors on the L298, does the rest. You do have to keep track of how many steps you send to each axis if you want to accurately control the position of the slides. There is no need for "accurately timed pulses" unless you want to control the acceleration and deceleration profiles of the slides, which is desirable because of the inertia of the slides, but this is certainly not a high-speed operation.

    Yeah, trying to get determinate response response from any time-sharing multi-tasking OS is problematical. Back in 1988 (or thereabouts) a customer wanted me to "upgrade" their hydraulically operated roll-pitch-yaw (RPY) platform from analog to digital, using the then-popular Intel 80286-based Personal Computer running an early version of Windows 3.x for operator interface and control.

    Fortunately, they didn't know jack sh*t about how to do this. PCs were taking off big time among the bean counters running Lotus 1-2-3, and someone thought they would be good for controlling their 1950s vintage RPY spacecraft simulator. After talking it over with my software team partner, we agreed that what we needed was a real-time operating system with guaranteed and predicable latencies to hardware interrupts. None of this business of setting an interrupt and waiting for the OS to "get a round tuit" to service it. Hit it, automagicaly push the PC and PSW on the stack, jump to ISR. All that in a few microseconds, not milliseconds or whenever the OS felt like it. Bear in mind that a 12 MHz clock was considered pretty fast way back when, so a guaranteed latency to respond to hardware interrupt of a dozen or so microseconds was considered state-of-the-art. for a microprocessor.

    At that time we were a DEC (Digital Equipment Corporation) shop, and if allowed to use DEC computers we would probably have chosen RT-11 for the OS. But the customer insisted that we use a PC. So we found a company that sold a Linux OS with a proprietary real-time kernel, added X-Windows for the user interface, and went on from there.

    It took us about a year to get everything working, what with designing and constructing new data acquisition hardware and all, but the end result was worth it: a ten-fold improvement in positioning accuracy and speed of response, plus arbitrary excitation waveforms for the platform. The RPY system was used to test reconnaissance systems cameras and sensors, simulating the environmental conditions these systems experienced in actual use. Our little part of the RPY upgrade paled compared to what the government spent to refurbish the hydraulics and add digitally controlled hydraulic servo valves to six hydraulic piston actuators. They also refurbished the vacuum pumps, chillers and infrared heaters inside the test chamber that simulated thermal loading at high altitudes and in space. It was quite an amazing thing to watch a ten-ton (I'm guessing the weight; it was quite large) stainless steel capsule, festooned with wires and tubing, lift off its pylon supports and go through various roll, pitch and yaw motions. That was the last "really fun" job I did.

    Inexpensive is good. They appear to be comparable to my Superior Electric, but perhaps with inferior mechanical specs for shaft run-out and bearing reliability. That's not a given (inferiority) but I have never seen a Superior Electric stepper fail... we even use them in high-vacuum environments without problems. Just zero experience with Asian parts.

    All-thread is pretty good for tinkering. If I had the money, I would buy a pre-built slide for my antenna tuner. I don't need the accuracy or load-bearing ability of an Acme thread though, just moderate repeatability to within a half-turn or so of the lead screw. Tuning a loop antenna is all analog: listen and tune for maximum noise in receiver at operating frequency, then possibly tune for minimum SWR while transmitting. I've never used a loop antenna for transmitting, so some experimenting will be in order.

    I like to use the semi-flexible spiral-cut couplers, of which I happen to have exactly one, but they are terribly expensive. If I didn't have one, I would probably fall back to a short length of rubber hose, glued in place, for coupling motor to leadscrew shaft.

    Choices are nice. Software makes that easy compared to wiring up new hardware. Main reason I fell in love with micros umpteen years ago.

    If you have a LOT of interconnecting wires, ribbon cable is probably the easiest solution. It comes in different wire sizes and spacing, but for one-off home projects, just about anything you can get CHEAP will work. You can of course parallel wires in the ribbon for more current capability if necessary. Terminations are problematical, but a lot cheaper than any multi-pin circular connectors I know of. Some people use Jones connectors if just a few power wires are involved, but I have never trusted them not to fall out of their mating socket , which usually occurs either unnoticed or at a most inconvenient moment.

    Where do you get your electronics stuff? On-line or from a bricks-and-mortar retailer? I always take a multimeter with me when I visit a local electronics surplus retailer. Have found some "amazing stuff" at really cheap prices over the years.

    Have you thought about building TWO of your CNC milling machines and offering one for sale on the Internet? Might help to offset some of your building costs.
     
  18. BGB

    BGB

    154
    11
    Nov 30, 2014
    I spent $4 each for the L298N by itself (I found some for around $3.95 each on Amazon, though the price is now $4.50 each). so, this was around $16 for 4 of them.

    if I had bought 4x L297 as well, it would have added a fair bit to the cost.

    with the L297, a clock pulse still needs to be sent, and still needs to be reasonably accurately timed for the motor to move correctly, unless you are operating it slowly or the motor has a large step size (so high RPM can be achieved at a low step speed).

    if one needs to send several-kHz pulses to move the motor as-expected at a reasonable speed, then "usleep()" isn't really a good option anymore, and a delay loop is still needed.


    in contrast, it isn't that hard to be like, "meh, I will just run my update loop at at 25 or 50kHz or something", since it isn't really all that much harder to pull this off with a delay loop (mostly just means waiting around 20 or 40 usec per update tick, rather than 200 or 400).

    for the normal PDM, the update loop is currently a fixed 10kHz, whereas for running steppers the PDM update is driven by the stepper-update tick, which is set to run at a higher frequency (currently 25kHz), which will update the PDM output pins as needed, and (when clock divisors hit 0), it updates the motor state (and resets the divisor).

    for driving BLDC motors, I also have a separate sub-step, which is 1/256 of a full step, and used for feeding a sine curve into the motor. depending on motor speed, this may update multiple steps per tick though, and is kept phase-locked with the main step. all this is done with fixed point math and lookup tables though (and is skipped if the step divisor is less than 16, at which point it drives it with a square-wave).


    it is running at 700MHz, and IIRC the delay loop spins around 30 times per usec.
    I could probably get around 100ns precision or so if really needed, but 1 usec seemed "good enough" for the basic time unit.

    in any case, this is still significantly better than one can get if trying to use "usleep()".

    the Linux OS scheduler is driven by clock interrupts, and its behavior depends a lot on these interrupts. the scheduler isn't really any more accurate than the clock interrupts, which are set to around 1kHz or so.

    (whereas a green-thread scheduler has no such limitation, and could be made to reschedule after significantly shorter intervals).


    yes, ok.
    never dealt with anything like this personally...


    well, I wouldn't necessarily consider them inexpensive, but at least the project isn't "dead in the water" if one of them breaks. I had considered some more powerful motors, but they were $25 each. for $50 each, could have gone for "ridiculously overkill" (30Nm / 22 lb-ft or similar), but not like I have that kind of money around...


    yeah, have some chunks of all-thread around.

    with some steppers (which do 200 steps/turn), and the implicit 16:1 reduction, I should probably be able to get reasonably good accuracy provided everything is stable. apparently there is an accuracy-boosting trick of using pairs of nuts with springs between them to improve accuracy over a single nut.


    I am wanting to use an aluminum coupler, probably rigid.
    I looked breifly, but didn't see any couplers for this particular motor shaft-size and 3/8-16, so this means likely needing to drill and tap an aluminum rod.

    rubber hose could work, assuming it was tight-fitting vulcanized rubber or similar.


    yeah.
    it is a lot easier to generate whatever sort of output is most useful, or doing whatever with the input, at least provided it can be done in real time.


    dunno. depending on how I wire it up, I am likely to see interconnects between the main drive board and sub-boards around 8 to 16 wires. this could probably be done using CAT3 or CAT5, but for a few areas, I may need wire that can be bent a lot without breaking (will be connected to moving structures), which likely means stranded wire.

    could use either ribbon cable, or stranded 8-conductor telephone wire. looking, the phone wire tends to come in very long rolls (1000 or 1500 feet), which would be a bit steep. ribbon cable could be more economical here (is comes in cheaper but much shorter rolls). then again, 1000 feet of ribbon cable would probably cost a lot more than 1000 feet of stranded phone wire.

    for similar reasons, it may make sense to consider more strands of lighter-gauge wire for power, vs a few strands of heavier wire, as probably continuously flexing some 14 or 16 AWG stranded wire would cause it to break after a while (whereas, say, a bundle of stranded 22 AWG wire might hold up better).


    I was mostly getting stuff from Amazon.

    I had also been looking on sites like Alibaba and similar, but generally sellers there want bulk orders (rather than the typically smaller quantities sold on Amazon).

    though, some amount of the electric motors I had gotten from Chinese sellers had a lot of bits of magnet dust and metal chips and similar in them, ... which is sort of a drawback I guess, but they were still pretty good motors... (these motors were around $10 each).


    as for making more, it is possible, if I can get enough parts and materials to do so and make a profit.
     
  19. hevans1944

    hevans1944 Hop - AC8NS

    4,521
    2,104
    Jun 21, 2012
    I somehow thought you were using a Sumtor 42H34913A4 stepper motor, but can't find that anywhere on this thread. What stepper motor are you using for the XYZ axis? What stepper motor are you using for the spindle drive?
     
  20. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    8,393
    1,270
    Nov 28, 2011
    Try aliexpress. They sell similar products in smaller quantities. Caveat emptor!
     
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day

-