Shop OBEX P1 Docs P2 Docs Learn Events
Smart pin example: PWM switch-mode power supply — Parallax Forums

Smart pin example: PWM switch-mode power supply

The P2 docs reference the following smart pin mode: "%01010 = PWM switch-mode power supply with voltage and current feedback".

Does anyone have anything (example code, schematic, anything else) that would show how this mode can be used? It's tantalizing me, but there seems to be no info on this.

Any ideas?

Comments

  • Chip did a pencil sketch showing 2 in 1 (current,voltage) feedback control. Its here in the forums somewhere, but haven't been able to find it, despite a few attempts.

    Harold S Black famously sketched his (significant!) negative feedback invention on a scrap of newspaper while on a ferry. Perhaps we could encourage Chip to take a ferry ride and sketch it again

    @Kuba recently mentioned letting the P2 run switchmode regs, not sure whether it was using this mode or another.

  • evanhevanh Posts: 15,192
    edited 2021-02-06 08:53

    I don't have any diagrams but I can interpret the terse mode description for you:

    %01010 = PWM switch-mode power supply with voltage and current feedback

    This mode overrides OUT to control the pin output state.

    The usual case here: OUT is the logic output from a cog to I/O pin. The direct associated smartpin sits in the middle and can replace OUT signal with its own. Ie: Smartpin 5 is directly associated with pin P5. With OUT overridden by the smartpin, the cog's OUT for that pin no longer goes to the output drive circuits.

    X[15:0] establishes a base period in clock cycles which forms the empirical high-time and low-time units.

    This is similar to what's often called a prescalar. In this case it forms the basic sampling period. It is the resolution and fastest reaction time of the PWM operation.

    X[31:16] establishes a PWM frame period in terms of base periods.

    This one, when multiplied by the above base period, forms the PWM switching period: 1/Fs.

    Of note is there is no mention of "capturing" of X. What capturing means here is copying the value from the writeable parameter register, in this case X, to a hidden internal smartpin register. Since this is not specified as happening, then you can assume the X register is used live in this smartpin mode. And by live I mean any programmed changes made to this register, during operation of the smartpin, have an instant effect.

    Y[15:0] establishes the PWM output value which gets captured at each frame start and used for its duration. It should range from zero to the frame period.

    This one is the PWM level. It's intended to be updated on the fly at any time. Hence the "captured" term is used here - which same as saying it's buffered. It will only action once per switching (frame) period.

  • evanhevanh Posts: 15,192
    edited 2021-02-06 08:23

    A counter, updating at each base period, counts from one up to the frame period. Then, the 'A' input is sampled at each base period until it reads low. After 'A' reads low, Y[15:0] is captured, IN is raised, and the process repeats.

    "updating" I guess means incrementing (or decrementing). So this is the frame timer ticking.

    SmartA input acts as a synchronous enable (low). I've not don't any switchmodes myself so not sure how it ties in with them.

    At each base period, the captured output value is compared to the counter. If it is equal or greater, a high is output. If it is less, a low is output. If, at any time during the cycle, the 'B' input goes high, the output will be low for the rest of that cycle.

    "captured output value" is the copy of Y register, aka PWM level. And "the counter" is the same frame timer as above. So this is the level compare for producing the actual PWM on the output pin.

    SmartB input acts as an asynchronous enable (low). Ditto for my switchmode knowledge here.

  • @evanh @Tubular Thank you both for the input and explanations. I'm still struggling with this mode, but at least I have a better idea what its supposed to do and how to get there.

  • As I interpret it it's basically the same as the normal sawtooth PWM mode except that cycles can be cancelled with the B input to implement a current limit.

    To build a real SMPS you need some feedback, for example read the output voltage with an ADC smart pin and use it as input to a PIN controller. The output controls the PWM Y value. The B input is to be connected to an overcurrent comperator. This can be implemented with a smart pin in DAC/comperator mode and a shunt resistor in the source path of a MOSFET.

    As long as the PID controller is in its linear region and the current is within limits the SMPS outputs a constant voltage. If the PID output is saturated (voltage too low) or overcurrent is detected then it outputs constant current.

  • BTW, I haven't tested the SMPS pin mode, yet. But I have used the DAC comperator mode to implement an overcurrent protection for my stepper driver project.

            wrpin   mode_cmp,#pinOvc
    ...
    mode_cmp  long  P_LEVEL_A | P_FILT1_AB | ovcLevel<<8 ' DAC comperator, filter 533ns
    

    It also uses the de-glitch flipflop filter to suppress short surges at the current sense resistor caused by switching noise.

  • cgraceycgracey Posts: 14,133
    edited 2021-02-07 12:42

    It's like this:

    WXPIN is used to set the base period (X[15:0]) and the PWM frame count (X[31:16]). The base period is the number of clocks which makes a base unit of time. The frame count is the number of base units that make up a PWM cycle.

    WYPIN is used to set the output value (Y[15:0]), which is internally captured at the start of every PWM frame and compared to the frame count upon completion of each base unit of time. If the output value is greater than or equal to the frame count, the pin outputs a high, else a low. This is intended to drive the gate of the switcher FET.

    The "A" input is the voltage detector for the SMPS output. This could be an adjacent pin using internal-DAC comparison mode to observe a voltage divider which is fed by the final SMPS output. When "A" is low, a PWM cycle is performed because the final output voltage has sagged below the requirement and it's time to do another pulse.

    The "B" input is the over-current detector which, if ever high during the PWM cycle, forces the output low for the rest of that PWM cycle. This could be an adjacent pin using internal-DAC comparison mode to observe a shunt resistor between GND and the FET source. When the shunt voltage gets too high, too much current is flowing (or the desired amount of current is flowing), so the output goes low to turn off the FET and allow the inductor connected to its drain to shoot high, creating a power pulse to be captured by a diode and dumped into a cap, which is the SMPS final output.

    I've never actually built a SMPS using this mode, but I believe the necessary logic is all there to enable a hands-free SMPS to operate.

  • SWEET! Thank you, Chip! This is exactly what I needed.

    @JonTitus I’m tagging you since this could be very helpful to your smartpin doc effort.

  • cgraceycgracey Posts: 14,133

    @JRoark said:
    SWEET! Thank you, Chip! This is exactly what I needed.

    @JonTitus I’m tagging you since this could be very helpful to your smartpin doc effort.

    Let me know if it works.

  • @cgracey said:

    @JRoark said:
    SWEET! Thank you, Chip! This is exactly what I needed.

    @JonTitus I’m tagging you since this could be very helpful to your smartpin doc effort.

    Let me know if it works.

    The MOSFET order should be here Wednesday. I plan on starting with a simple, low-freq, single FET buck-type converter driven manually by the P2 (no smart pin) just to validate the basics. Then I will let the smart pin manage it and see how it goes!

    Purple smoke in 3... 2... 1...

  • cgraceycgracey Posts: 14,133

    @JRoark said:

    @cgracey said:

    @JRoark said:
    SWEET! Thank you, Chip! This is exactly what I needed.

    @JonTitus I’m tagging you since this could be very helpful to your smartpin doc effort.

    Let me know if it works.

    The MOSFET order should be here Wednesday. I plan on starting with a simple, low-freq, single FET buck-type converter driven manually by the P2 (no smart pin) just to validate the basics. Then I will let the smart pin manage it and see how it goes!

    Purple smoke in 3... 2... 1...

    In our experience, switchers are tricky, since they need very low-impedance connections among the power components. And the inductor needs to have very low DCR (a few milliohms). I think of these circuits like time compressors. They pull current through the inductor for a relatively long time and then, in a brief period, the inductor flies back and generates a power pulse that must be captured efficiently with a fast low-drop diode and very-low-ESR caps. You probably know all this. I'm anxious to hear how it goes, anyway.

  • Chip, my favorite subject was “recess” and I was voted “most likely to create purple smoke”, so when I’m offered words of advice by people who have a better grasp of the subject matter, I definitely listen.

    Interesting analogy about the inductor. Time compressor.

  • kubakuba Posts: 94
    edited 2021-02-11 18:06

    I've had some success driving a synchronous switcher for the 1.8V input to P2, at 750kHz spread spectrum, with P2 doing all the regulation/control duties :) It bootstraps from a resistive divider from 5V, with three diodes in series acting as a crude shunt above 1.9V or so, for when P2 is not consuming enough power (in reset etc). Once P2 boots with the internal fast oscillator, the divider itself provides a fairly accurate 1.8V with 4.7V input, diodes or no diodes :)

    I didn't use the SMPS mode and basically did all the decision making in software. The SMPS pin mode makes it easier and I'll probably run the regulator at 1MHz that way. Thanks @Chip and @ManAtWork for the explanations - it makes sense now.

    There's a trick I had to discover for running fast SMPS on P2 (think 0.5MHz up to several MHz) using comparators (that also applies when using those comparators for "fast" ADCs). The comparator is non-ideal, and in the SMPS application it's "slow", but that's deterministic for any given SMPS input voltage and thus comparator slew rate. So, there's an outer control loop that has two outputs - one is the PWM duty cycle, another is the A comparator threshold. At such fast switching rates the comparator has high latency relative to the PWM period. So its threshold has to be separately regulated to yield proper output voltage - the threshold depends on the input voltage to the regulator, so some feed-forward correction can be applied as well if needed to deal with fast input voltage changes. In my application the input is the nominal 5V from the USB, so that's not a problem. I'm also using a couple DAC pins in a hybrid fast ADC to capture the switching waveforms with wide bandwidth at 10+MHz sampling rate for diagnostics. It was indispensable for development purposes - not having to attach probes to the board was super nice. The diode shunt protected the P2 from self-destruction when facing the inevitable developmental hiccups :)

  • cgraceycgracey Posts: 14,133

    Sounds great, Kuba. I read your posts several times, gleaning details. Very interesting.

  • AribaAriba Posts: 2,682
    edited 2021-02-12 01:20

    I just don't see the advantage of a P2 controlled switcher over a dedicated switcher IC. The latter has the power stage built in together with the regulator, and costs about 30 cents (or 10 cents from China).
    The FET and the Diode you need in addition to the P2 costs about the same and you occupy 2 or 3 valuable pins.

  • evanhevanh Posts: 15,192

    It was probably just a challenge. I'm suitable impressed with it being able to bootstrap that way.

    The other thing that those dedicated chips have built in is the flyback diode is replaced with a second power FET in what's called a synchronous switcher configuration. This wipes out the loses from the diode drop. It's how they achieve >90% efficiency.

  • I tend to see this @kuba mischief as a wonderful technical opus. He did it not because it is necessarily useful commercially or even a good idea or safe practice. He did it because it NEEDED (go with it) to be done. Because... reasons. :)

    And I learned something from it!

  • @JRoark said:
    I tend to see this @kuba mischief as a wonderful technical opus. He did it not because it is necessarily useful commercially or even a good idea or safe practice. He did it because it NEEDED (go with it) to be done. Because... reasons. :)

    And I learned something from it!

    yes

  • Of course, it doesn't make sense (economically) to use the expensive P2 chip to regulate low voltages like 1.8V out of 5V. There are ready-to-use ICs that do this cheaper. It's just an exercise.

    But I can imagine that there are a lot of applications where the algorithms for the control loop are quite complicated and the total cost is high enough anyway to justify the P2 and all the software development: maximum power trackers for solar panels, (large) battery chargers, induction welding, EDM, ECM...

  • Boy, Chip was right when he said switchers are fussy creatures. You just cant breadboard this stuff. Some of it seems a bit like voodoo-engineering. I’ll CNC a heavy PCB tomorrow. Somewhere I have some scraps of 4 oz board from the mid 80’s.

    Nothing works reliably. The moment the current gets over trivial levels, things get strange, so this project very clearly needs a board with short, fat, thick traces and some better caps before we even begin the troubleshooting efforts. I will probably add solder to the bare traces for some addl conductivity.

    And while I havent tried the P2 switch mode yet, there has also been a happy absence of purple smoke! We are making progress.

  • cgraceycgracey Posts: 14,133

    We made a board at Parallax once that had a switcher that didn't work. Looking at the layout, there was this thin trace that connected to the inductor. It went a little ways, went through a via, went a little further into another via, and attached to something else. That's how not to do a switcher.

  • @cgracey said:
    We made a board at Parallax once that had a switcher that didn't work. Looking at the layout, there was this thin trace that connected to the inductor. It went a little ways, went through a via, went a little further into another via, and attached to something else. That's how not to do a switcher.

    I am learning this to be true. Copper pours are your friend. There may be formal rules for this stuff, but they all seem to relate back to “lower ESR, lower DCR, and thicker copper”. There seem to be cheap switchers, and good switchers, but few good cheap switchers.

    Segue: As a child my father counted among his friends a very gifted TransAm racer named Mark Donohue. He once said, and it stuck with me as a wee lad of 10 years old, the following: “you can finally say you have enough horsepower when you leave twin streaks from one corner to the next”. This ethic also seems to cover switchers.

    More Copper.
    Less DCR.
    Less ESR.
    More FET drive.

  • ManAtWorkManAtWork Posts: 2,078
    edited 2021-02-13 11:28

    Thick copper layers and wide traces are not the only thing to consider. Often, the key is to minimize the area inside a current loop. Multilayer boards are your friend. Inductors, capacitors and power MOSFETs with heatsink are often quite big so it's not possible to further reduce the length of the traces. But can route one trace as wide copper pour on one layer and the trace back as overlapping pour on another layer. This way the area of the "coil" formed by the two traces is only the prepreg height (several 1/10 of a mm) times the length what keeps inductance (ESR) very low. And the magnetic field vector is not orthogonal to the PCB but in parallel to the surface. So it doesn't induce much EMI into other traces.

    Power electronics is artwork. Love it or leave it.

  • @Ariba said:
    I just don't see the advantage of a P2 controlled switcher over a dedicated switcher IC. The latter has the power stage built in together with the regulator, and costs about 30 cents (or 10 cents from China).
    The FET and the Diode you need in addition to the P2 costs about the same and you occupy 2 or 3 valuable pins.

    That's true of course, but as others have mentioned I've done that partly "just because", and also to re-learn the relevant control theory and make sure I understand it - and what better way to test yourself than going all out and making sure that the magic smoke stays put :)

    There's some side benefit, though: I have no feel for how long-lived certain "hot" (modern, 1MHz+) low-cost switchers are. For all I know they may go away in a couple of years. Since I've had boards remain in production unchanged for well over a decade, not having to substitute switchers (that rarely have compatible footprints) is of some relevance. I'm far from imploring anyone else to do it - it's surely unsuitable in many or even most circumstances.

    At work I'm in the middle of a P2-targeted redesign across the entire product line and am hopeful that P2 will be the only "non-jelly-bean" part, with everything else having multiple sources and multiple substitutes with matching specs. In my experience, you can easily get switchers that "last" for two or three decades on the market, but they'll cost a couple dollars in 1k quantities, and tend to be slower parts that need larger inductors etc. I've been using such parts, some even had two sources (functionally and practically "identical" part from both TI and Linear/ADI), but such supply chain reliability costs a premium. If all you need is SOT mosfets in a popular package, those can be almost always substituted without it being a major undertaking.

    The series diodes can be replaced by a jellybean LED that can be had for a couple cents, too, and is good enough to protect P2's core from damage :)

  • kubakuba Posts: 94
    edited 2021-02-19 20:44

    @cgracey said:
    We made a board at Parallax once that had a switcher that didn't work. Looking at the layout, there was this thin trace that connected to the inductor. It went a little ways, went through a via, went a little further into another via, and attached to something else. That's how not to do a switcher.

    I'm fortunate to be able to do board design like an artist would do graphics: take the time to make it both pretty and working well. Hand-sculpted copper pours have been my friend for some time now. Here's one example (from a current P2-based design, where P2 drives a switching transformer that generates analog supplies):

    An example of fancy copper pours

    For scale, the area shown would just about fit a US quarter coin - so not the tightest design, but moving to P2 has freed up a lot of the board :)

    There are a couple fills that have "gratuitously funny" shapes - those were hand-optimized to have balanced impedances (with sticky copper foil and Xacto knife on a "target" PCB sanded bare on top, and a network analyzer).

    My copper pour "adventure" began a couple decades ago when I put together a small production run of a digitizer that had polarity-switched excitation voltage to cut down on system-wide DC offsets (it did have DC drift too low to measure in our application, so that worked well). There are two ways to do such polarity switching: the sane one is to generate a slew-controlled reference voltage for one side, along with its precise mirror for the other side, carefully ensuring that their short-term average is zero or some chosen common-mode voltage that changes very slowly.

    The "hot young lad" approach, prompted by my lack of experience, was to sweep the inbalance under the desk and keep its integrated area "tiny" by making everything so fast that even the integrated common mode charge stayed out of the input amplifier's bandwidth. It also seemed cheaper, so I carefully put together state-of-the-art fast-as-lightning mosfet drivers, and it all worked quite well on the bench... except that the excitation wires leaving the board had to be Litz, so that was a bit of a bummer. I was a grad student so spinning those by hand was way cheaper than buying them :) They were carrying 20V/ns slew rates (+/-10V switching in <2ns). When I put two of those digitizers side by side, their clocks had to be synchronized or they'd badly interfere with each other. That's even though they were mostly encased in metal boxes, along with the sensors they interfaced with. Enough of the "excitation" leaked between them via power supply, even after suppression, that it was a dead end and I had learned my lesson. I couldn't afford to scrap those, so I had figured out how to sync the clock rates and phases using a software PLL loop. That came handy for other things.

    Alas, I've never had any use for mosfet drivers that fast since, so that was a bummer, since I was a driven lad and sure put myself all into solving the speed problem, whereas speed turned out the be the enemy :) Nowadays I don't really optimize the last fraction of a percent even of the power electronics I work on - having a manageable power stage that dumps a dozen watts more as waste under full load is in my world an entirely acceptable alternative to a hot-rod tweaked-to-state-of-the-art stage that uses all tricks in the books and takes a small PhD dissertation just to go over the design equations. I like reading those for sure, though, and am a closet cheerleader for the legions of power engineer grads who push the leading edge forward. Whatever "scraps" I learned from those trailblazers over the years and put to my own use have thus far seemed entirely adequate.

  • jmgjmg Posts: 15,148

    @kuba said:
    There's some side benefit, though: I have no feel for how long-lived certain "hot" (modern, 1MHz+) low-cost switchers are. For all I know they may go away in a couple of years. Since I've had boards remain in production unchanged for well over a decade, not having to substitute switchers (that rarely have compatible footprints) is of some relevance.

    That's a fair point, and could apply to the more esoteric DFN, BGA or inductor included custom packages.

    However, if you stick to the more common SO-8 and SOT26 parts, I'd expect you can get better performance, and more compact PCBs, with still some alternate sourcing (same pinout) and long design life.
    A quick look finds AP3402, AP3445 and SY8032 all share a common SOT26 pinout, with PowerGood included. All are around 13c/1k

    Making a Sync Switcher with Power Good and low RFI using discretes is going to be a challenge.

  • kubakuba Posts: 94
    edited 2021-02-19 23:04

    @jmg said:
    Making a Sync Switcher with Power Good and low RFI using discretes is going to be a challenge.

    It's definitely a challenge if it's to be a substitute for something that'd otherwise be very cheap. As soon as it's in the range where you'd use a controller with external power elements, P2 can be quite a bargain if you already have it - although it certainly is very much application-dependent. If you want to replace a couple $k worth of servo drives, roll-your-own can be very cheap if you're up to speed on the control theory needed to make it work reliably and have the means of demonstrating that the code won't maim someone. For replacing a $0.10 IC it becomes a bit questionable for sure. I'm just happy that P2 can be made to play the Rube Goldberg game well if you want it to. Seems like purpose-made silicon for demonstrating just how silly one can be :) I love it, I gotta say.

    P2 seems also to do a decent job as a series pass element LDO controller. With just a couple very cheap discretes it can generate (and monitor!) the boost voltages needed to drive emitter-loaded BJTs that have output impedance low enough to cope with heavy capacitive loads without having to be too finicky with loop compensation. The LDO market is a bit neurotic - lots of "analog-friendly" voltage+current combinations seem only supported by parts on the expensive side ($1-$2 rather than $0.20) and/or "legacy". I've been running into "here's a perfect part if only it had adjustable voltage and/or could supply 100mA more" lately over and over, and the BOM penny pincher hind-brain of mine was in a heap of bother.

    OTOH, P2 can keep up with emulating quite a few low-voltage positive PNP/P-NMOS LDOs with matching performance, and all it takes is mostly the raw pass element hooked up almost directly to the I/O pins. A 2V positive LDO basically takes a PNP BJT and 6 pins for driving/monitoring it, works great, and can even do system identification of the load impedance to calculate the transfer function of a suitably stable control loop. Detects failing decoupling caps automagically as well. Sorta hard to do on other MCUs, because it invariably eats into limited analog resources. That's just a little thing I found that works in my little niche and is probably not worth the effort otherwise. I seem to be running lots of software control loops for all kinds of "P2-in-the-loop" replacements for analog ICs lately. P2 seems to be triggering that sort of a mindset in me, and I don't mind too much. It's quite refreshing, in a way. I sometimes read about cool analog design tricks that are used in various analog controllers - even "lowly" LDOs and "simple" switchers, and I guess I got jealous. I can't design silicon for those, but I sure can play with PASM :)

  • cgraceycgracey Posts: 14,133

    Kuba, for something like a 2V LDO, are you using the compare-A-or-B-to-internal-DAC mode, unclocked?

Sign In or Register to comment.