Search This Blog

Sunday, April 30, 2023

USB Power Bank

 I got one of those Leed's USB power bank from my apartment building during a planned power outage.  It blew up when I tried to charge it.  There wasn't a whole lot I could reverse engineered from the dead parts. There was a 5-pin and a 6-pin chips and a bunch of passives. My understanding is that it uses an inverting buck boost converter for both charging and output as the VUSB pins of both the USB connectors are connected together.

I finally got around to rebuild it from scratch this weekend with what I have on hand.  The parts I have were from aliexpress before the big chips shortages. I use a LTC4054 Li-ion charger chip and a MT3608 boost converter. 

The charging rate is limited by heat dissipation on a tiny single sided PCB.  The output current is limited by the Schottky diode, inductor and battery discharge rate to about 1A (or slightly higher) or so matching to the original power bank.  


Power bank schematic

Q1 and the 1M pull down (R3) is used to invert the logic level of my switch to drive the Boost converter Enable pin.  The switch is also used to connect the R2 from the voltage divider feedback to the ground.  RGB LED is used as for Charging/Operating indicator.  


The converter goes into a PFM (Pulse Frequency Modulation) power saving mode for low current loads.
I used Green LED as they have the highest efficiency.  It is connected across the inductor to reduce idle power.  It only get energized only when the boost converter is supplying current to the load.  The brightness is proportional to load.  Fancy!


Your USB power bank might have a detection circuit that shuts itself off.  I could have used a low power microcontroller that wakes up every hundreds of milliseconds to detects voltage drop across the Schottky diode to turn on the converter.

The idle current is about 200-300uA while maintaining a 5V output when the external USB device not drawing power.  That seems high, until you realize that it'll take thousands of hours before the battery is drained.    

Power bank PCB

My PCB is taped to the existing stripped down PCB.  I had to cut the VBUS trace between the USB connectors.  The blue wires are for the RGB LED.

Populated PCB (I only have 1A/20V Schottky diode.)

I modified the USB A connector to include a contact switch that is grounded when the USB A is plugged in.    This is used to enable the boost converter circuit.

Modified connector to sense presence of USB plug

Red LED = Charging

Green LED = Operating.  Brightness proportional to load

Yellow is when both are connected, but that doesn't usually happen as the connector spacing is too closed together.

Tuesday, February 14, 2023

STM8 - Generating 2 phase PWM

A push pull converter uses two drivers that are 180 degrees out of phase.

It is possible to generate PWM on 2 channels that are 180 degrees out of phase in  TIM1on a STM8S003.  All the register settings are from the reference manual, but you won't find an example.

TIM1 is set up as an up/down counter in Center-aligned mode. This spaces out the 2 phase PWM signal evenly.

Since the timer is counting both up and down in 1 PWM cycle,  auto-reload value for TIM1 should be set as 1/2 of the value to generate PWM frequency. I used TIM1_FREQ of 27kHz in my code.

#define CPU_CLOCK 16000000UL
#define TIM1_FREQ 27000L
#define TIM1_PSCR 1
#define TIM1_CLK (CPU_CLOCK/TIM1_PSCR)
#define TIM1_ARR (TIM1_CLK/TIM1_FREQ/2)
#define TIM1_PSCRH ((TIM1_PSCR-1)>>8)
#define TIM1_PSCRL ((TIM1_PSCR-1)&0xff)
#define TIM1_ARRH ((TIM1_ARR)>>8)
#define TIM1_ARRL ((TIM1_ARR)&0xff) 

// Clk = 16MHz
CLK->CKDIVR = 0;
 
TIM1->PSCRH = TIM1_PSCRH;
TIM1->PSCRL = TIM1_PSCRL;
TIM1->ARRH = TIM1_ARRH;
TIM1->ARRL = TIM1_ARRL; 

// TIM1 enable, Center-aligned mode 3
TIM1->CR1 = TIM1_CR1_CEN|TIM1_CR1_CMS; 

Output enable (and polarity) bits of the corresponding TIM1 channels can be set in TIM1 CCERx.  I use CH3 and CH4.

// CH3, CH4 output enable, polarity active high
TIM1->CCER2 = TIM1_CCER2_CC4E|TIM1_CCER2_CC3E;

From the Reference Manual:

110: PWM mode 1 - In up-counting, channel 1 is active as long as TIM1_CNT < TIM1_CCR1, otherwise, the channel is inactive. In down-counting, channel 1 is inactive (OC1REF = 0) as long as TIM1_CNT > TIM1_CCR1, otherwise, the channel is active (OC1REF = 1).

PWM Mode 1 when ARR =8 and CCR = 4

PWM mode 2 works similarly, but with the output polarity inverted.

111: PWM mode 2 - In up-counting, channel 1 is inactive as long as TIM1_CNT < TIM1_CCR1, otherwise, the channel is active. In down-counting, channel 1 is active as long as TIM1_CNT > TIM1_CCR1, otherwise, the channel is inactive. 

One can generate a PWM signal using a sawtooth wave and a comparator.  

 

PWM generation using analog circuit - Sawtooth wave and a comparator

The modulating signal level is the CCR value, the TIM1 counter is the sawtooth wave. The PWM modes 1 and 2 are just the polarity setting on the comparator.


PWM generation using TIM1

 One of the TIM1 channel (CH3) is set up with PWM Mode 1 while another channel (Ch4) as PWM Mode 2.

// CH3: PWM mode 1, preload, output
TIM1->CCMR3 = (6<<4)|TIM1_CCMR_OCxPE;
// CH4: PWM mode 2, preload, output
TIM1->CCMR4 = (7<<4)|TIM1_CCMR_OCxPE;

Use PWM Mode 1 for one of the channels to center an output around Timer count = 0 and Mode 2 on the other to center around Timer count = ARR. This is how you can generate the 2 phase PWM signals.

The CCR values could be set independently. In some applications, you want them to have the same PWM duty cycles. The granularity of the PWM signal is 2 TIM1 clocks. (125ns in my code)

void Set_PWM(uint16_t Value)
{
Value >>=1;
// CCR3 = n/2
TIM1->CCR3H = Value >>8;
TIM1->CCR3L = Value & 0xff;

// CCR4 = TIM1_ARR - n/2
Value = TIM1_ARR - Value;
TIM1->CCR4H = Value >>8;
TIM1->CCR4L = Value & 0xff;
}

Turn on the MOE (Main Output Enable) bit in TIM1 BKR (Break Register). An external signal can be used to disable the TIM1 outputs in the case of a hardware fault. e.g. over-current or over-temperature condition

// Master output enable
TIM1->BKR = TIM1_BKR_MOE;

This are some the output of PWM waveform at 27kHz captured on my logic analyzer.

2 phase PWM at 27kHz

Set_PWM(2) - 27kHz close to 0% duty cycle

2 Set_PWM(294) - 27kHz close to 50% duty cycle

Sunday, February 12, 2023

Optocouplers

Optocouplers are some of those things that are deceivingly easy to a beginner, but also hard to use correctly.  If you are reading the datasheet carefully, you are in for a big surprise.

CTR (Current Transfer Ratio): sensitivity of the coupler - the ratio of the transistor output current vs the LED current.  e.g. for a 50% CTR, you have to drive the LED with 10mA and the transistor switches 5mA.

The CTR spec is very loose and likely this series of optocouplers are just different bins of the same parts.  They don't even include a max value.  


This ones show both min and max value from 100% to 200%. The following shows the part to part variation of a for a small samples of a (different) optocoupler.

CTR of a small sample of PS2021 optocoupler

Analog feedback

The optocoupler is commonly used as an analog feedback in an isolated power supply.  The error voltage is pass back as a current sink or source to close a negative feedback loop of a regulator across a voltage barrier.

I played around with the isolated power supply design from previous blog with feedback from the secondary side.  The voltage regulation is very tight and virtually stays at around 5V from 5mA to125mA load.

I have no idea on how well it would work with the loose CTR specs.

Passing digital signals

They are one of those things that was made with compromises. In order to make the device sensitive, they made a big photo-transistor at the expense of large parasitic capacitance (Millar Capacitance) and and suffers from slow speed.


Reference: Vishay has a great app. note on Faster Switching from Standard Couplers.  It covers all the technical stuff.

It'll be pretty sad day if I don't try to make something slow to go fast. I played around with LTSpice and came up with something that is not covered by the app. note.  

The values I used are determined by the optocoupler CTR.

Optocoupler circuits: simple, medium and complex

To see their performance, I put them side by side and feed each of these circuits with the same 5 pulses of 100kHz signal (200kbps data rate).


Top trace: Input (cyan), bottom traces outputs from optocoupler circuits

Simple coupler circuit (green)


CBC  (base collector capacitance) aka Millar Capacitance. It slows down the transistor. Datasheet typically uses 10V and a load resistor of 100R as their test circuit.  CBC is low at higher voltages and the small pull up value help with the rise time.

Note: the scale from Low to high (left in log scale) is very different from High to low (right in linear)

The speed is much slower when you use a large pull up resistor and lowering the voltage. The values I picked is might be useful for low data rate may be lower  tens of  kilobits per second. e.g. asynchronous serial.  It should only be used with a Schimtt Trigger input to clean up the slow rise and fall time.

The middle circuit (blue)

The optocoupler is the first stage of inverter that drives a  transistor of a second stage inverter.  Its output range is clamped to a diode drop of the transistor base voltage. The operating point is not a good spot for low CBC. 

Input (Cyan), Q1 base voltage (Purple), Output (Blue)

In spite of that, it only take about 100mV change in base voltage for the transistor to turn on or off.  It is a good compromise to squeeze an extra bit of bandwidth out of the old optocoupler. There is a bit of inconsistency in the timing. A timing analysis should be made for setup/hold time for protocols that require coordination of multiple signals e.g. SPI.

The more complex circuit (Red)

It bypasses the Miller effect as it uses the transistor junction as a photo diode. The comparator threshold is set to about mid point of the input (~100mV). The speed (propagation around 500ns) is limited by the $0.20 LM393 type of comparator that is used to amplify the signal.

You can speed up the photodiode even more by using a transimpedance amplifier.  Because of the feedback, the voltage across the diode junction is maintained around 0V, the switch time is greatly minimized.  However  high speed amplifiers cost more and I don't have a whole lot of them.

Nowadays, there are specialized devices with active circuit to make them go fast. e.g. high speed logic gate coupler, IGBT/MOSFET gate drive coupler. Some of them uses capacitor or magnet coupling.  There are isolation devices for USB, I2C.  These are the ones that are too messy to to roll you own.

Friday, February 10, 2023

Isolated power supply

I have decided to show the train of thought into making an isolated power supply for powering up some small circuits across an isolation barrier.

First attempt

After seeing the voltage feedback circuit from my last post, I am trying out some ideas of using that for an isolated power supply.  Here is what I have using LTSpice simulation.

isolated power supply

It is an unregulated isolated power supply from 12V to around 5-6V.  There are 3 windings for the transformer on a ferrite.

L1 is feedback path for the oscillator.  R4 is used to limit the amount of feedback. L1 is also used as a negative feedback for the voltage across the winding..  The negative peak voltage across the winding is rectified across C4.  When the voltage high enough, the 4.5V Zener diode D3 conducts and clamps the base of Q1. 

As can be seen from the traces below, the voltage across C4 does not reflect on the output voltage.  It regulate the peak voltage of the winding.  The voltage regulation of this circuit is about as bad as those old transformer wall warts.  The voltage output is about 6.6V at 5mA load and drops down to 5V at 50mA. 

The regulation can probably be improved with a bit of components tweaking.  A linear LDO regulator at the output can be used for tightening the regulation.

Output voltage (green) vs the feekback voltqge (blue) at C4

L2 is the primary winding for the flyback converter.  I limit the inductor current with the help of Q2 and R3. Small inductor value and high supply voltage results in high di/dt. Some of these energy ends up as high voltage spikes at self resonant frequency of component parasitic.

L3 is the secondary winding for the flyback circuit.  I use a ferrite bead to filter the switching noise.

I use a RCD snubber in the circuit.  It merely clamps the collector voltage of Q1 (rated for VCE = 40V) to a safe value. A RC snubber could eliminate the ringing by dumpling the excessive energy.  It is something to think about for EMI reasons.

Q1 collector voltage with and without snubber

Update

I played around with the simulation and tweaked a few values.  It seems to me that the voltage feedback limits the power too much such that the output cannot maintain regulation at 50mA load.

I also found some serious problem with the current LTSpice Zener diode database. There are a whole bunch of these in that picture that I didn't highlight. So I wouldn't want to use them without checking their datasheet.  I used to use them a few years back without issues.  I filed a support ticket with Analog.

LTSpice diode/Zener database

so the "4.5V" is the normal working voltage of the circuit it is supposed to protect not Zener voltage.  Its Zener voltage is 6.8V.

FTZU6.2E is a 6.2V Low capacitance Zener Diode.  Why does TDZV6_2 which is also a 6.2V Zener has Vbrkdn as 6.8V?

At first find the part number a bit funny, but didn't think much about that as the values are what I expected to see.  Zener diodes tend to start conducting well before their Zener voltage and aren't very precise and harder to tweak.

Analog feedback

I played around with the design with feedback from the secondary side.  The voltage regulation is very tight and virtually stays at around 5V from 5mA to125mA load.  I don't know if I can trust the TL431 3rd party behavior model.  It is nice but it has too many parts.

Adding analog feedback from across the isolation barrier

Simplifying the design

So far I have been thinking like a typical analog designer adding a piece here and there and tweaking their value.  A discrete design is fine to a certain point, but each piece you add increase the complexity and may also suffer from system level interaction.  It is time to sit back and approach the problem in a different direction with a blank slate.

I came up with an unregulated supply using the MC64063A switching regulator.  It has BJT transistor output and slow switching, but it is a cheap switching regulator made by multiple vendors.  Having learnt the lesson of chip supply outage, that's one hell of a good reason to at least give it a try.


The MC64063A is operating as an inverting regulator driving the primary winding of the flyback inverter. L1 inductor ramps up and the energy is stored in magnetic field as the driver is on.  When the driver is off,  the magnetic field collapse and primary side voltage goes from +10V and changes to a negative polarity. Current drain from the inductor through D1 to charge C2. Both windings are magnetically coupled, so the primary winding voltage could be used as a rough proxy of the secondary side.

Note: There are no nasty spikes on the primary side with this flyback circuit. The ringing at the secondary side can be ignored by the rectifier circuit.


However, there is a gotcha.  The primary side voltage drops off to a lower point (-2.65V) than the secondary side at the beginning of the cycle that C2 is being charged. The voltage across C2 is what the MC64036 is regulating to.

Voltage waveforms: Primary side (Green) and Secondary side (Red)

The following waveform shows the rectifier currents on both sides.  I use a BJT Q2 as a synchronous rectifier for the output. I have tried both a Schottky diode or a MOSFET and the BJT turns out working better.  It has low drop (0.187V at the current peak), but slow enough without adding ringing from self resonant.  The negative spike at the left side is also ignored by Q2.

Diodes waveforms: Primary side (Blue), Secondary side (light blue)

Note: D1 conducts at the lowest point in the primary side which is a not a perfect symmetry point in the waveform.

1K load: 4.85V
100R load: 4.31V

Load regulation isn't great, but it is good enough to be used with a LDO.

I found some decent isolation for coupled inductor. e.g.  Bourns SRF0703 series with 500V RMS Hi-pot.


Saturday, February 4, 2023

Solving a few power supply cold cases

 I spent a week or so clearing a few power supplies off my bone piles recently.

The case of the phone charger

I have a flip phone USB charger that went out of regulation outputting 7V.  I did the usual check on the electrolytic capacitors and found nothing wrong with their values.  I left it on my bone pile for scraps.

Top side of the PCB

In the left side of the PCB below, there is a slot (for isolation) between primary and secondary circuits.  Normally you would find an optoisolator used as a feedback bridging both sides.  There was a footprint for a 4-pin device, but it isn't hooked up correctly.  It is probably a left over from a previous version of the design.
 
I hooked up my bench supply (max out about 63V) to the AC input of the charger.  It was sufficient to get 6V at the output..  Feeling a bit brave (or foolish?), I poke around a bit with my multimeter and found another spot across the capacitor measuring 6V at the primary side.  I traced the circuit and annotated in the picture below.

There is winding for a feedback for the oscillator.  There is another branch of it with a simple rectifier + capacitor.  The negative voltage across is an approximation of the output voltage.  A Zener diode is connected between this voltage and the base of the flyback driver transistor.  At some point when the output voltage is high enough, the Zener diode conducts and pulls the base towards ground.  This stops the oscillation and closes the negative feedback loop for the output voltage.

Bottom side of the PCB

Funny that the old diode didn't fail completely but ended up having a higher Zener voltage.  I fool around putting resistor and Zener diodes in parallel (4.7K, 10K) to see if that has an effect on the output.  Yes!

I managed to find one scrap Zener diode that sets a reasonable voltage: No load: 5.2V and 4.76V at rated load of 350mA.  The diode drop difference between no load to full load across the output Schottky diode would probably account for most of the droop.  It is good enough for the USB specs.

The case of the flickering LED

Back in 2017, I installed a LED driver (Modding 220V LED for 110V - LED rectrofitting).  It is the outer ring that is only switched on for extra brightness.  It became the main light when the inner rings failed in 2019.  

Recently the LED starts to flicker once every few hours.  The bulk capacitor has started to fail under heat.  The PCB is discolored (around the driver chip) due to heat.  This Chinese no-name brand capacitor was actually a quality part as it survived about 3 years of abuse under heat.

It still have about 1/2 of its value, so the LED flickers when there is a slight dip AC . I don't have an exact replacement (400V 10uF) nor was I looking for one.  I replace it with a 47uF 450V capacitor that I have in stock.  

I leave a bit of a gap between the base of the capacitor and the PCB.  As the capacitor replacement has a higher value and lower ESR, I also added in a NTC Inrush current limitor to protect the tiny bridge rectifier.  (There is a 0.5A fuse in series I added for protection.)
 
LED driver PCB + defective cap (desoldered)

The case is there to cover the high voltage circuits.  It is discolored over time due to the high heat.  The case is mounted horizontally with standoffs. There is space above and below the case to allow for convection.   I have decided to improve the cooling by drilling some holes in the case.  I used an EMI shield as template for the holes.

 I kept the holes small  to prevent flying insects getting into the case.  Part of the case crack because it was too thin, brittle and weak.  I stitched the cracks together with some dental floss.


I hope this would last for another few years.

The case of the blow input stage PSU

This is the donor of the PSU case for my previous article.  There was a bag with a blown bridge rectifier diode and two flyback transistors with it and a missing fuse.  I assumed that those were the broken parts from my previous diagnostic a long time ago.  I don't remember whether I blew it or it was already DOA when I picked up a few PSU from a surplus place.  Scrapping it was the correct decision. 

I found a $20 store brand PSU in my box.  It was the replacement I bought for the one that caught fire.  Funny thing about that PSU as its parts still lives on in a few things.

It lived long enough to its retirement.  So why bother fixing the other one?  When I opened it up to clean it, I realized that the bean counters have been working overtime as a lot of the EMC and filtering parts on the PCB have been jumpered off.   The heatsink are about 1/3 as thick vs the your usual computer store silver box special.


So I took a chance by taking the flyback transistors from this board.  In the process of removing the input filter cap from my dead PSU, I also found a loose pin in the main filter capacitor.  I finally have a rough idea of what happened.

Simplified generic 200W PSU schematic showing the damaged parts

They used a bridge rectifier rated for 2A (max) in a "250W" PSU. We use 115V here, so the part is under spec.  Even in the cheap out PSU, they use larger diodes (probably 3A rated ) for the 115V.

So basically what might have happen is that the diodes were overloaded and at some point they failed shorted together shorting all the AC inputs and the negative output together.  This blew up the lower filter capacitor, two flyback transistors and the 5A fuse.

In general, I would use all part at least rated for the fused value (5A) for the input circuit.  I replaced it with a 600V 7A part that fits the mounting hole.  I replaced the two filter caps with the ones from the PSU that caught fire.  The two flyback transistors were from the accountant optimized PSU.  They have slightly lower rating.

I used the old trick of using a 40W incandescent light bulb in series of the AC input for testing the "fixed" power supply.  The light grows briefly and went out.  I shorted the enable pin to ground with the "PSU tester" block that came with one of my PSU and the fan spin up.  The PSU is fixed!

Now the fun part of finding a case for it as I have repurposed its old one.  I foolishly think that I would fit inside a Dell 200W PSU as the PCB are the same dimensions.  The Dell case is nice to work with as it allows access to the trace side of the PCB. Wrong!  Dell decided that they want mounting holes in a slightly different locations than the "standard" ones used in generic PSU. I leave the EMC ground pad for the high voltage as is but offset the rest of the mounting hole, drill some new ones.  I have to trim off the excess metal bits so that they don't short circuit the PCB traces on the secondary side.  I soldered some nuts to the frame to make life a bit easier.  I clean up and redid all the wiring.  I added an On/Off switch from the el Cheapo PSU.

Fixed PCB fitted into a Dell PSU case

Component side of the PCB

The case of the leaky capacitors

This one is build by a certain consumer electronics/entertainment corporation in Japan for another certain fruity electronics/entertainment corporation.  I modified its output from 7.5V output to 5V a long time ago.  I took it out of storage and it died after a few minutes.

Bad leaky capacitors is not what I would expect to see here.  There are 3 electrolytic capacitors that leaky and they spill oily black liquid that attacked the solder mask and cause some minor corrosion to copper traces and wires. I had to remove some of the components to clean and assess the damages.

Two caps and an inductor (top)

Trace side of the PCB showing corrosions and dirty build up due to the leak

I have decided to use tantalum capacitors as  I don't want the same part to fail again.  They handle heat a lot better as they don't dry up.  They cost a lot more, but I have a big pile.

The three fail capacitors are located right next to the heatsink for the rectifier and heat is trapped between the subassemblies or corner of the case.

The 2 replacement capacitors, bad main capacitor and common mode filter PCB

The PSU with case with no vents  = heat trap

82uF cap

for feedback circuit power.  It is non-critical, so I used two 22uF 25V in parallel.

180uF cap: Output cap after LC Pi filter.  

I used three 47uF 10V caps in parallel:: 140uF,  ESR of 0.266R and ripple current of 1.3A

1200uF cap: Main capacitor

This is the capacitor that I missed in my initial replacement.  The capacitance value was roughly correct and I don't have the right equipment to measure its ESR.  The power supply fails to reach its correct value and would fail at 50% load.  It took me a few days to figure out that it might be the problem.  I soldered in a 1000uF 50V caps and the output was fine.

I used twenty 47uF 10V caps in parallel: 940uF, ESR of 0.04R and 8A of ripple current. I only need 2-3A or so to match the original spec. I used heat shrink around the capacitor to prevent short circuit. (Stacking caps warped in heat shrink and operating in a heat trap would likely derate the ripple current rating a lot.)

I have some much higher value caps in parallel, but their ESR might be too low and affect the feedback circuits.  I also have a lot less of them.

stack of 20 capacitors 

47uF 400V:  Input filter capacitor

It has not failed, but I replaced it anyway.  Caps next to heatsink is not good.  I use 47uF 450V cap from my left overs.

Testing

5V: no load 5.2V
5V @ 1.9A (2A rated): 4.7V

Verdict: poor regulation. It has same regulation as the phone charger that doesn't even have secondary feedback. I traced out the feedback circuit and it is much more complex than it needed to be.   It uses 1 dual opamp, a lot of passives and a TL431 just for voltage and current feedback.  All that extra junk for poor load regulation.  Almost tempted to rewire the feedback circuit...


Voltage and Current Feedback circuit (daughtercard)

As a point of comparison, I hacked a 12V +5V module into a 17Vcurrent limited charger/adaptor for my old laptop in my younger foolish days.  It worked fine and I managed to get the proper one on ebay.  So yeah, I know what I am talking about.  

I wounded a small current transformer, a transistor and a few resistors for the current limit. It measure the AC current from the secondary winding to trigger the transistor to fool the feedback circuit to lower the output voltage.  The existing voltage feedback uses a TL431, a few passive and an optocoupler would look like circuit on the right hand side.  It is very simple and work well.  See TI app note sluaa66 (.pdf) for how to design the circuit on the right hand side.