Computing stuff tied to the physical world

Posts Tagged ‘Electronics’

From PWM to voltage

In Hardware on Jun 30, 2013 at 00:01

The Arduino library has always had an “analogWrite()” function, even though the ATmega doesn’t have any way to generate a varying voltage. So why the name?

Well, what most microcontrollers can do is generate a pulse-width modulated signal, also known as PWM. That’s just a fancy way of saying that the microcontroller periodically generates a pulse, of which the width can be varied under software control.

Here’s a diagram from the Arduino PWM tutorial page:


It’s very easy to generate an approximate voltage between 0 and VCC by simply adding a resistor and capacitor to act as low-pass filter:


That image came from an excellent article by Scott Daniels about this same topic on the website. Check it out for much more background information.

So how do these two little components turn PWM into a voltage?

To see what’s going on, we can tie the resistor to a PWM pin, call “analogWrite(N,128)” to set a 50% duty cycle, i.e. halfway, and then watch the result on the oscilloscope:


(the above was generated with a 10 kΩ resistor and 0.1 µF capacitor – see this calculator)

What you’d want to see, is a 1.65 V output. As you can see, the real thing is indeed centered around that value, but with a lot of “ripple” (yellow = PWM, blue = Vout).

The reason for this is that the PWM is charging and discharging the capacitor. The average value will be the ratio of on-to-off time against the digital voltage, i.e. 3.3V, so a 50% duty cycle will lead to half VCC, i.e. 1.65V. But it’s still charging & discharging.

Can we get a cleaner signal out, without that up-and-down wavering? Yes: by increasing the repetition rate, i.e. the PWM frequency (while keeping the on-off ratio the same). There’s a page on the Arduino site about this. Here’s the result, with a 64x higher rate:


The purple line is a third probe on the same output signal, but set to AC coupling and much higher sensitivity, to show that the ripple is still there, but much much lower.

Now I can get to the point of this post: my intention was to see if I could generate a clean sawtooth wave, to use as supply voltage (after amplification) for testing circuits at various VCC levels – as used a few times in recent posts. Here’s the code I came up with:

void setup () {}

void loop () {
  for (int i = 0; i < 256; ++i) {
    analogWrite(5, i);

The result is this:


And now there’s indeed a sawtooth, but as you can see, sudden changes like the down edge take some time to pass through the RC filter, somewhat messing up the signal.

No problem, if we increase the delay time in the above loop by a factor of 50:


Voilá – things are fine now. A pretty smooth voltage ramp from 0 to VCC every 2 seconds, all from a single digital output pin on the ATmega – we’ve created a DAC!

What if the signal lines are very long?

In Hardware on Jun 19, 2013 at 00:01

Welcome to the weekly What-If series, also available via the Café wiki.

This question came from figuring out how to drive an SPI chip over a few meters distance. Normally, you’re not supposed to do that: I2C and SPI in particular are designed for use on a PCB, i.e. distances in the order of dozens of centimeters at best. Fortunately, in this case speed was not an issue, so what if we simply take the clock signal way down, to say 10 KHz (50 µs on + 50 µs off). Can we create a solid SPI setup across a few meters of wiring?

To try this out, I decided to take a reel with some 70 to 80 meters of multi-core wire:


Being untwisted and unshielded, this is probably as bad as it gets for signalling purposes. Then I started with a clean 10 KHz square wave of 0..5V from the signal generator:


Here’s what happens to the signal on the signal generator side (i.e. same probe placement), when simply connecting the open wires of the above cable to signal and ground:


This is caused by the load and the reflection of the signal on the end of that long cable. Think of it as an echo of that voltage change, propagating back and forth and colliding with the signal – causing this fairly substantial change in signal rise time and shape..

But to really see the effects, we have to also look at the signal at the other end, where it’s going to be picked up and used. I made the following setup, with three different probes:

JC's Grid, page 81

(sorry for the confusion: “B” and “M” were mixed up in this drawing)

  • YELLOW probe on the incoming signal generator end
  • MAGENTA probe on the outgoing signal
  • BLUE probe on the outgoing ground connection
  • RED is the MAGENTA minus the BLUE level (as math function)

All the vertical scales are set to the same 1V per division from now on:


Note that there are some really strange effects in there: the magenta output signal is “ringing”, as is to be expected with such a long coil of wire and lots of stray capacitance, inductance, and resistance. But the blue “ground” level is also ringing, almost as much in fact! And the yellow input is funny, too. Let’s zoom in a bit on that rising edge:


What does this mean for signal propagation? Well, as you can see, everything rattles and shakes in situations like these. It really makes a difference for example as to how the end is connected to power. If you use the (blue) output ground as reference, then the signal will appear as the difference (i.e. the red line), which has less extreme ringing than if you use the (magenta) output referenced to the incoming ground pin.

None of these effects are problematic at this 10 KHz signalling rate. If you need to pass signals like these, it definitely pays to A) keep the signalling rate low, B) reduce the steepness of the edges, and C) add a fairly substantial load resistance at the end of the wire (between signal and ground, say 330..1000 Ω). The reasons and details of all this will have to wait for some future posts.

What I do want to mention, is that you can actually see the speed of light in action here. Let’s zoom even further into that rising edge (sorry, blue and magenta are reversed now):


It takes over 400 ns for the yellow rising edge to reach the other end. In vacuum, light travels some 120 meter in that amount of time – not so very different from the 80 meter or so of cable the electricity has to traverse. Pretty amazing what you can do these days, with nothing more than a signal generator, a modern oscilloscope, and a coil of wire!

MPPT hunting

In Hardware on May 21, 2013 at 00:01

Solar panels are funny power sources: for each panel, if you draw no power, the voltage will rise to 15..40 V (depending on the type of panel), and when you short them out, a current of 5..12 A will flow (again, depending on type). My panels will do 30V @ 8A.

Note that in both cases just described, the power output will be zero: power = volts x amps, so when either one is zero, there’s no energy transfer! – to get power out of a solar panel, you have to adjust those parameters somewhere in between. And what’s even worse, that optimal point depends on the amount of sunlight hitting the panels…

That’s where MPPT comes in, which stands for Maximum Power Point Tracking. Here’s a graph, copied from, with thanks:


As you draw more current, there’s a “knee” at which the predominantly voltage-controlled output drops, until the panel is asked to supply more than it has, after which the output voltage drops very rapidly.

Power is the product of V and A, which is equivalent to the surface of the area left of and under the current output point on the curve.

But how do you adjust the power demand to match that optimal point in the first place?

The trick is to vary the demand a bit (i.e. the current drawn) and then to closely watch what the voltage is doing. What we’re after is the slope of the line – or in mathematical terms, its derivative. If it’s too flat, we should increase the load current, if it’s too steep, we should back off a bit. By oscillating, we can estimate the slope – and that’s exactly what my inverter seems to be doing here (but only on down-slopes, as far as I can tell):

Screen Shot 2013-05-14 at 15.35.03

As the PV output changes due to the sun intensity and incidence angle changing, the SMA SB5000TL inverter adjusts the load it places on the panels to get the most juice out of ‘em.

Neat, eh?

Update – I just came across a related post at Dangerous Prototypessynchronicity!

Supply noise sensitivity

In Hardware on May 19, 2013 at 00:01

Yesterday’s post showed how with 3 resistors, one capacitor, and a P-MOSFET, you can set up a circuit to measure battery voltage with a voltage divider, even for voltages above VCC.

The whole point of this is that it can be switched off completely, drawing no current between measurements.

While trying this out, I started with a 1 MΩ pull-up on the P-MOSFET gate, and got this:


A very odd switch-off pattern, looked like an oscillation of some kind. Even with with the 100x faster switch-off using a 10 kΩ pull-up instead, the problem persisted:


This turned out to be a problem with the power supply. I was using a little USB plug with a switching regulator. These tend to work fine, but they do create a bit of “ripple voltage”, i.e. the 5V output is not exactly 5V DC. Here are the fluctuations, typical of units like these:


In other words: that little ripple was greatly amplified near the point where the P-MOSFET was starting to turn off, thus creating a regular but highly exaggerated turn-off pattern. Because – in a certain range – MOSFETs act like amplifiers, just like regular transistors.

It all went away when I switched to the lab supply, but it sure took some head-scratching…

Anyway, in real use this won’t matter, since the whole point is to use this with batteries.

Zero-power measurement – part 2

In Hardware on May 18, 2013 at 00:01

After a great suggestion by Max, on yesterday’s post, here’s a another circuit to try:

JC's Grid, page 73

It adds a capacitor and a resistor, but it allows using a P-MOSFET and a divider ratio which can now use the entire ADC range, not just 1 V or so as in yesterday’s circuit. Note however that if VCC is not fixed to the same value under all conditions, then the ADC’s reference voltage can float, and use of the 1.1V bandgap may still be needed.

Here’s the voltage at the top of the divider, showing how it switches on and off:


That’s with the pull-up resistor value R set to 1 MΩ, which takes 208 ms to turn the MOSFET back off. We don’t need that long, a 10 kΩ resistor for R will do fine:


That still gives us 2 ms to measure the supply level. Note that turn-off is automatic. DIO needs to be turned high again, but that can happen later. In my test code, I left it low for 1s to, then high for 7s.

Here’s a neat set of superimposed measurements (using persistence), while varying the high voltage from 3.5 to 12.0 V in 0.5 V steps:


Warning: for 12V, the divider ratio must be changed so the centre tap stays under VCC.

Note that with higher voltages, the MOSFET will turn off sooner – this is because there is now more current flowing through the pull-up resistor. But still plenty of time left to measure: 1 ms is more than enough for an ADC.

Tomorrow, an example of how these measurements can sometimes go awry…

Zero-power battery measurement

In Hardware on May 17, 2013 at 00:01

As promised, here’s a circuit which can be used to measure a voltage higher than VCC without drawing any current while not measuring:

Screen Shot 2013-05-15 at 13.40.54

Besides the fact that this needs an N-FET + I/O pin, there are several finicky details.

First of all, note that the following circuit will not drop the power consumption to zero:

Screen Shot 2013-05-15 at 14.38.42

The idea in itself is great: set DIO to logic “0″ before performing a measurement, acting as GND level for the resistor divider (10 + 10 kΩ would be fine here). Then, to switch it off, set DIO to an input, so that the pin becomes high-impedance.

The problem is that the pin divider is still connected and that the AIO pin cannot float any higher than VCC + 0.6 (the drop over the internal ESD protection diode). The top resistor remains connected between PWR and VCC + 0.6, therefore it’s still leaking some current.

That also explains why the first circuit does better: the MOSFET disconnects all I/O pins from that PWR line, so that there is just a resistor from AIO to ground (which is harmless).

But there’s a catch: we need to be able to turn the N-channel MOSFET on and off, which means we need to be able to apply a voltage to its gate which is a few volts above the drain pin (the bottom one, attached to AIO). With a resistive divider of 10 + 10 kΩ on a 6V PWR line, that voltage will immediately rise to 3V, and there’s no way the DIO pin can keep the MOSFET on (it can only go up to logic “1″, i.e. 3.3V).

The solution is to use a different divider ratio: say 50 + 10 kΩ. Then, a 6V PWR level leads to a 1V level on the AIO pin, i.e. on the drain of the MOSFET. With DIO set to “1″, that means the MOSFETs gate will be 2.3V above the drain – enough to keep it turned on.

BTW, all this tinkering over the past few days has left me with a bunch a funky headers :)


Anyway, to summarise the zero-power battery monitor:

  • to work with 6V PWR, use a 50 (or 47) kΩ top resistor and 10 kΩ for the bottom one
  • use an N-channel MOSFET with low turn-on voltage (called a “logic level MOSFET”)
  • to measure the voltage, set DIO to “1″
  • measure the voltage on the AIO pin, where 0..1V will correspond to 0..6V on PWR
  • to turn off the divider, set DIO to “0″

As you can see, this approach requires an active component to switch things and an extra I/O pin, but then you do end up with a circuit which can completely switch off.

For simple uses, I’d just use yesterday’s setup – sub-microamp is usually good enough!

Measuring the battery without draining it

In Hardware on May 16, 2013 at 00:01

In yesterday’s post, a resistive voltage divider was used to measure the battery voltage – any voltage for that matter, as long as the divider resistor values are chosen properly.

With a 6V battery, a 10 + 10 kΩ divider draws 0.3 ma, i.e. 300 µA. Can we do better?

Sure: 100+100 kΩ draws 30 µA, 1+1 MΩ draws 3 µA, and 10+10 MΩ draws just 0.3 µA.

Unfortunately there are limits, preventing the use of really high resistor divider values.

The ATmega328 datasheet recommends that the output impedance of the circuit connected to the ADC input pin be 10 kΩ or less for good results. With higher values, there is less current available to charge the ADC’s sample-and-hold capacitor, meaning that it will take longer for the ADC to report a stable value (reading it out more than once may be needed). And then there’s the leakage current which every pin has – it’s specified in the datasheet as ± 1 µA max in or out of any I/O pin. This means that a 1+1 MΩ divider may not only take longer to read out, but also that the actual value read may not be accurate – no matter how long we wait or how often we repeat the measurement.

So let’s find out!

The divider I’m going to use is the same as yesterday, but with higher resistor values.

Let’s go all out and try 10 + 10 MΩ. I’ll use the following sketch, which reads out AIO1..4, and sends out a 4-byte packet with the top 8 bits of each ADC value every 8 seconds:

#include <JeeLib.h>

byte payload[4];

void setup () {
  rf12_initialize(22, RF12_868MHZ, 5);
  DIDR0 = 0x0F; // disable the digital inputs on analog 0..3

void loop () {
  for (byte i = 0; i < 4; ++i) {
    analogRead(i);                    // ignore first reading
    payload[i] = analogRead(i) >> 2;  // report upper 8 bits

  rf12_sendNow(0, payload, sizeof payload);

This means that a reported value N corresponds to N / 255 * 3.3V.

With 5V as supply, this is what comes out:

L 10:18:14.311 usb-A40117UK OK 22 193 220 206 196
L 10:18:22.675 usb-A40117UK OK 22 193 189 186 187
L 10:18:31.026 usb-A40117UK OK 22 193 141 149 162
L 10:18:39.382 usb-A40117UK OK 22 193 174 167 164
L 10:18:47.741 usb-A40117UK OK 22 193 209 185 175

The 193 comes from AIO1, which has the 10 + 10 kΩ divider, and reports 2.50V – spot on.

But as you can see, the second value is all over the map (ignore the 3rd and 4th, they are floating). The reason for this is that the 10 MΩ resistors are so high that all sorts of noise gets picked up and “measured”.

With a 1 + 1 MΩ divider, things do improve, but the current draw increases to 2.5 µA:

L 09:21:25.557 usb-A40117UK OK 22 198 200 192 186
L 09:21:33.907 usb-A40117UK OK 22 198 192 182 177
L 09:21:42.256 usb-A40117UK OK 22 197 199 188 183
L 09:21:50.606 usb-A40117UK OK 22 197 195 187 183
L 09:21:58.965 usb-A40117UK OK 22 197 197 186 181
L 09:22:07.315 usb-A40117UK OK 22 198 198 190 184

Can we do better? Sure. The trick is to add a small capacitor in parallel with the lower resistor. Here’s a test using 10 + 10 MΩ again, with a 0.1 µF cap between AIO2 and GND:


Results – at 5V we get 196, i.e. 2.54V:

L 10:30:27.768 usb-A40117UK OK 22 198 196 189 186
L 10:30:36.118 usb-A40117UK OK 22 198 196 188 183
L 10:30:44.478 usb-A40117UK OK 22 198 196 186 182
L 10:30:52.842 usb-A40117UK OK 22 198 196 189 185
L 10:31:01.186 usb-A40117UK OK 22 197 196 186 181

At 4V we get 157, i.e. 2.03V:

L 10:33:31.552 usb-A40117UK OK 22 158 157 158 161
L 10:33:39.902 usb-A40117UK OK 22 158 157 156 157
L 10:33:48.246 usb-A40117UK OK 22 158 157 159 161
L 10:33:56.611 usb-A40117UK OK 22 158 157 157 159
L 10:34:04.959 usb-A40117UK OK 22 159 157 158 161

At 6V we get 235, i.e. 3.04V:

L 10:47:26.658 usb-A40117UK OK 22 237 235 222 210
L 10:47:35.023 usb-A40117UK OK 22 237 235 210 199
L 10:47:43.373 usb-A40117UK OK 22 236 235 222 210
L 10:47:51.755 usb-A40117UK OK 22 237 235 208 194
L 10:48:00.080 usb-A40117UK OK 22 236 235 220 209


Note how the floating AIO3 and AIO4 pins tend to follow the levels on AIO1 and AIO2. My hunch is that the ADC’s sample-and-hold circuit is now working in reverse: when AIO3 is read, the S&H switches on, and levels the charge on the unconnected pin (which still has a tiny amount of parasitic capacitance) and the internal capacitance.

The current draw through this permanently-connected resistor divider with charge cap will be very low indeed: 0.3 µA at 6V (Ohm’s law: 6V / 20 MΩ). This sort of leakage current is probably fine in most cases, and gives us the ability to check the battery level in a wireless node, even with battery voltages above VCC.

Tomorrow I’ll explore a setup which draws no current in sleep mode. Just for kicks…

What if we want to know the battery state?

In Hardware on May 15, 2013 at 00:01

Welcome to the weekly What-If series, also available via the Café wiki.

One useful task for wireless sensor nodes, is to be able to determine the state of the battery: is it full? is it nearly depleted? how much life is there left in them?

With a boost converter such as the AA Power Board, things are fairly easy because the battery voltage is below the supply voltage – just hook it up to an analog input pin, and use the built-in ADC with a call such as:

word millivolts = map(analogRead(0), 0, 1023, 0, 3300);

This assumes that the ATmega is running on a stable 3.3V supply, which acts as reference for the ADC.

If that isn’t the case, i.e. if the ATmega is running directly off 2 AA batteries or a coin cell, then the ADC cannot use the supply voltage as reference. Reading out VCC through the ADC will always return 1023, i.e. the maximum value, since its reference is also VCC – so this can not tell us anything about the absolute voltage level.

There’s a trick around this, as described in a previous post: measure a known voltage with the ADC and then deduce the reference voltage from it. As it so happens, the ATmega has a 1.1V “bandgap” voltage which is accurate enough for this purpose.

The third scenario is that we’re running off a voltage higher than 3.3V, and that the ATmega is powered by it through a voltage regulator, providing a stable 3.3V. So now, the ADC has a stable reference voltage, but we end up with a new problem: the voltage we want to measure is higher than 3.3V!

Let’s say we have a rechargeable 6V lead-acid battery and we want to get a warning before it runs down completely (which is very bad for battery life). So let’s assume we want to measure the voltage and trigger on that voltage dropping to 5.4V.

We can’t just hook up the battery voltage to an analog input pin, but we could use a voltage divider made up of two equal resistors. I used two 10 kΩ resistors and mounted them on a 6-pin header – very convenient for use with a JeeNode:


Now, only half the battery voltage will be present on the analog input pin (because both resistor values are the same in this example). So the battery voltage calculation now becomes a variant of the previous formula:

word millivolts = map(analogRead(0), 0, 1023, 0, 3300) * 2;

But there is a drawback with this approach: it draws some current, and it draws it all the time. In the case of 2x 10 kΩ resistors on a 6V battery, the current draw is (Ohm’s law kicking in!): 6 V / 20,000 Ω = 0.0003 A = 0.3 mA. On a lead-acid battery, that’s probably no problem at all, but on smaller batteries and when you’re trying to conserve as much energy as possible, 0.3 mA is huge!

Can we raise the resistor values and lower the current consumption of this voltage divider that way? Yes, but not indefinitely – more on that tomorrow…

Energy, power, current, charge

In Hardware on May 14, 2013 at 00:01

The International System of Units, or SI from the French Système International is a wonderfully clever refinement of the original metric system.

Took me a while to get all this clear, but it really helps to understand electrical “units”:

  • power says something about intensity: volts times amperes, the unit is watt
  • energy says something about effort: power times duration, the unit is watt-second
  • current says something about rate: charge per time unit, the unit is ampere
  • charge says something about pressure: more charge raises volts, the unit is coulomb

Of course, some units get expressed differently – that’s just to scale things for practical use:

  • a kilowatt (kW) is 1000 watts
  • a watt-hour (Wh) is 3600 watt-seconds
  • a kilowatt-hour (kWh) is 1000 watt-hour
  • a milli-ampere (mA) is 1/1000 of an ampere
  • a micro-coulomb (µC) is 1/1000000 of a coulomb

But there are several more useful equivalences:

  • When a 1.5 V battery is specified as 2000 mAh (i.e. 2 Ah), then it can deliver 1.5 x 2 = 3 Wh of energy – why? because you can multiply and divide units just like you can with their quantities, so V x Ah = V x A x h = W x h = Wh
  • Another unit of energy is the “joule” – which is just another name for watt-second. Or to put it differently: a watt is one joule per second, which shows that a watt is a rate.
  • A joule is also tied to mechanical energy: one joule is one newton-meter, where the “newton” is the unit of force. A newton is what it takes to accelerate 1 kg of mass by 1 m/s2 (i.e. increase the velocity by 1 m/s in one second – are you still with me?).
  • So the watt also represents a mechanical intensity (i.e. strength). Just like one horsepower, which is defined as 746 W, presumably the strength of a single horse…
  • Got a car with a 100 Hp engine? It can generate 74.6 kW of power, i.e. accelerate a 1000 kg weight by 74.6 m/s2, which is ≈ 20 km/h speed increase every second, or in more popular terms: 0..100 km/h in 5 seconds (assuming no losses). But I digress…

The point is that all those SI units really make life easy. And they’re 100% logical…

Maxing out the Hameg scope

In AVR, Hardware on May 10, 2013 at 00:01

Yesterday’s post was about how test equipment can differ not only in terms of hardware, but also the software/firmware that comes with it (anyone hacking on the Owons or Rigols yet to make the software more feature-full?).

Here’s another example, where I’m using just about all the bells and whistles of the Hameg HMO series scopes – not for the heck of it, but because it really can help gain more insight about the circuit being examined.

This is my second attempt at understanding what sort of start up currents need to be available for the new JeeNode Micro v3 to properly power up:


I’m applying a 0..2V power up ramp (yellow line) as power supply, using a 1 Hz sawtooth signal. This again simulates an energy harvesting setup where the power supply slowly ramps up (the real thing would actually rise far more slowly, i.e. when using a solar cell + supercap, for example). The current consumed by the JNµ v3 (blue line) is measured by measuring the voltage drop across a 10 Ω resistor – as usual.

The current consumption starts at about 0.85V and rises until the power supply reaches about 1.4V. At that point, the current consumption is about 77 µA. Then the ATtiny84A comes out of reset, enters a very brief high-current mode (much higher than the peak shown, but this is averaged out), and then goes into ultra low-power sleep mode. The sketch running on the JNµ is the latest power_down.ino, here in simplified form:

#include <JeeLib.h>

void setup () {

void loop () {}

Note that since this is the new JNµ v3, the RFM12B module never even gets powered up, so there’s no need to initialise the radio and then put it in sleep mode.

The red line uses the Hameg’s advanced math features to perform digital filtering on top of the averaging already performed during acquisition: the averaging keeps the power-up spike visible (albeit distorted), at the cost of leaving some residual noise in the blue trace, while the IIR digital low-pass filter applied to that result then makes it possible to estimate the 77 µA current draw just before the ATtiny84A starts running.

Here’s the zoomed-in view, showing the interesting segment in even more detail:


The IIR filtering seen here is slightly different, with a little spike due to the following power-up spike, so the 86 µA reported here is slightly on the high side.

Note how the Hameg’s storage, high sensitivity, averaging, adjustable units display, variable vertical scale, math functions, on-screen measurements, on-screen cursors, and zooming all come together to produce a pretty informative screen shot of what is going on. Frankly, I wouldn’t know how to obtain this level of info in any other way.

So what’s all this fuss about measuring that 77 µA level?

Well, this is how much current the JNµ draws before it starts running its code. There’s nothing we can do to reduce this power consumption further until it reaches this point. In the case of energy harvesting, the supply – no matter how it’s generated – will have to be able to briefly deliver at least 77 µA to overcome the startup requirements. If it doesn’t, then the supply voltage (presumably a supercap or rechargeable battery) will never rise further, even though a JNµ can easily draw less than a tenth of that current once it has started up and goes into ultra-low power with brief occasional wake-ups to do the real work.

What I’m taking away from this, is that a solar energy setup will need to provide at least 0.1 mA somewhere during the day to get a JNµ started up. Once that happens, and as long as there is enough power to supply the average current needed, the node can then run at lower power levels. But whenever the supercap or battery runs out, another period with enough light is needed to generate that 0.1 mA again.

It all sounds ridiculously low, and in a way it is: 0.1 mA could be supplied for over two years by 3 AA batteries. The reason for going through all this trouble, is that I’d really like to find a way to run off indoor solar energy light levels. Even if it only works near a window, it would completely remove the need for batteries. It would allow me to just sprinkle such nodes where needed and collect data … forever.

Oscilloscope firmware

In Hardware on May 9, 2013 at 00:01

Oscilloscopes are very complex instruments. The “front end” is all about being able to capture a huge range of signals at a huge rate of speeds. This is what lets you hook up the same probe to AC mains one day, and pick up millivolt signals another day, and to collect many minutes of data on a single screen vs displaying the shape of a multi-MHz wave. This isn’t just about capture, at least as important is the triggering part: how to decide what to pick up for display on the screen.

For low sampling rates, it’s very easy to use an ADC and just collect some data points – as shown in this older weblog post, even AC mains, although triggering can be an issue.

With the Xminilab presented recently, a lot of this has been solved in software, supporting a pretty impressive range of options, even for triggering. The Xminilab is particularly interesting because the full source code is available.

But for serious work, you’ll need an Owon or Rigol scope. These can sample at up to 1 Gsa/s, i.e. one billion samples per second. Truly, truly capable front-ends, able to handle very wide voltage and acquisition speed ranges.

The Hameg HMO2024 is more expensive, and many of its specs are not much better than the Owon (worse even, in some cases: a smaller display size and less sample memory).

The devil is in the details. Here’s a recent screen from the HMO2024 (borders cropped):


And here’s my first cut at acquiring the same info on the Owon (click for full size):


Let me add that I now have lots of experience with the Hameg, and only just started using the Owon, so there might be relevant features I’ve failed to set up in an optimal fashion.

A couple of quick observations:

  • This is not a “typical” measurement setup: a very slow, low-amplitude signal is nothing like the usual measurements one would come across, with higher signal levels, and faster sampling rates. Then again, that’s part of the whole point of an oscilloscope: it’s so versatile that you end up using it in lots of situations!
  • As you can see, the Owon has a lot more pixels to display a signal on, so I was able to increase the voltage sensitivity one notch to get more detail, and capture a bit longer.
  • Some differences are obvious but not that important: the Owon provides less information on-screen about the current settings, and it does not use anti-aliasing for the traces (i.e. intensity variations to produce a fake “sharpening” effect of steep lines).

The two major differences are that: 1) the Hameg lets me apply additional digital signal processing to effectively reduce the random variations and smooth out the signal (this is done after capture, but before drawing things on-screen, i.e. all in software/firmware), and 2) the Hameg includes support for a “reference trace”, i.e. storing a previous trace in its built-in memory, and displaying it in white next to a new capture – to compare power consumption with and without WiFi, in this case.

Note that the Owon capture depth was set to 1,000 samples instead of the maximum 10 Msa, otherwise the screen would have shown a very wide red trace, almost completely swamping out the signal shown on screen. With this reduced setting, the current consumption is still fairly easy to estimate, despite the lack of low-pass filtering.

Is this a show-stopper for the Owon? Not really. It still gives a pretty good impression of the current consumption pattern during starup of the Carambola 2. If you really wanted to improve on this, you could insert an analog filter (a trivial RC filter with just 2 passive components would do). With a bit of extra work, I’m sure you can get at least as good a current consumption graph on the Owon.

The trade-off is (recurring) convenience and setup time vs. (up-front) equipment cost.

PS. The Rigol DS1052E does have a low-pass filter – every scope has different trade-offs!

PPS. For a great view into oscilloscope development over the past 5 years, see Dave Jones’ comparison video of the Rigol DS1052E and the new – phenomenal!DS2000 series.

Carambola 2 power consumption

In Hardware, Linux on May 7, 2013 at 00:01

The Carambola 2 mentioned yesterday is based on a SoC design which uses amazingly little power – considering that it’s running a full Linux-based OpenWrt setup.

There are a couple of ways to measure power consumption. If all you’re after is the average power on idle, then all you need to do is insert a multimeter in the power supply line and set it in the appropriate milliamp range. Wait a minute or so for the system to start up, and you’ll see that the Carambola 2 draws about 72 mA @ 5V, i.e. roughly a third of a watt.

If you have a lab power supply, you can simply read the power consumption on its display.

But given an oscilloscope, it’s actually much more informative to see what the power consumption graph is, i.e. over time. This will show the startup power use and also allows seeing more detail, since these systems often periodically cycle through different activities.

The setup for “seeing” power consumption is always the same: just insert a small resistor in series with the “Device Under Test”, and measure the voltage drop over that resistor:

JC's Grid, page 51

Except that in this case, we need to use a smaller resistor to keep the voltage drop within bounds. Given that the expected currents will be over 100 mA, a 100 Ω resistor would completely mess up the setup. I found a 0.1 Ω SMD resistor in my lab supplies, so that’s what I used – mounting it on a 2-pin header for convenience:


With 0.1 Ω, a 100 mA current produces a voltage of 10 mV. This should have a negligible effect on the power supplied to the Carambola 2 (a 1 Ω resistor should also work fine).

Here’s the result on the scope – white is the default setup, yellow is with WiFi enabled:


Sure takes all the guesswork out of what the power consumption is doing on startup, eh?

Meet the Owon SDS 7102V – part 2

In Hardware on May 5, 2013 at 00:01

Today’s post continues where we left off yesterday. Here are the front-panel controls:


Nice and tidy. Absolutely effective, as far as I could establish in my first impressions. As with all modern scopes, there are lots of features behind all those buttons, and many of them lead to “soft menu’s”, i.e. menu’s shown on screen (on three sides sometimes: right, left, and bottom). That’s what the right and bottom buttons next to the screen are for. There’s one “multipurpose” rotary encoder knob, which is used when selecting from the occasional menu popping up on the left.

The only downside is that you can end up moving your hands around a lot while setting things up and while making adjustments. Coming from a different brand, I had some trouble remembering where averaging, FFT, trigger settings, etc. were, but that’s bound to get easier over time as muscle memory sets in. Because operating any complex instrument with lots of knobs and features really is about motions and muscle memory. It just takes a bit of time and practice.

One remarkable feature of this scope is its very deep 10 megasamples acquisition depth (it’s adjustable, from 1,000 samples up). This makes it very easy to take a single snapshot of an event, and then to zoom in to see specific events in full detail.

One use would be to decode serial communication signals such as UARTs and I2C data packets. There is no built-in decoding, so this needs to be done manually. Then again, you can save all 10 million samples to a USB stick so with some software it would be possible to perform such decoding automatically on a standard PC or Mac, albeit after-the-fact.

Power consumption is very low: 0.77W standby, 18W when turned on.

You might be wondering how this oscilloscope compares to the Xminilab and the Hameg HMO series – which are about a fifth and five times as expensive, respectively. But with such an extreme price range, it’s impossible to answer this question other than: the more you pay, the more you get. Pretty obvious, and also pretty useless as guideline, I’m afraid.

Would I buy the Xminilab if I had no more than $100 to spend? Yes. While it’s limited and does require a lot more ingenuity and patience, it can still help to understand what’s going on, and to address problems that couldn’t be solved without a scope.

Would I recommend the Owon for serious electronics use? Definitely. It lets you capture all the info you need, and “see” what’s going on – both analog and digitally – for frequencies up to dozens of MHz. With much larger display & more memory than the Rigol DS1052E.

Would I purchase a Hameg HMO series again, even though it’s so darn expensive? Yes. The software, the math features, the logic analyser, and the serial decoding – it all adds up, yet it’s still half the price of the “low end” Agilent models. And, not to be ignored: its (cropped but informative) screenshots are perfect for the 604 pixel width of this weblog!

I’ll explore the capabilities of the Owon SDS 7102V scope in more practical scenarios in the weeks to come. Stay tuned…

Meet the Owon SDS 7102V

In Hardware on May 4, 2013 at 00:01

Here’s another “loaner” from David Menting, this time it’s his scope, the Owon SDS 7102V – which is sales-speak for a dual-channel 100 MHz digital storage oscilloscope:


This unit is available in the Netherlands from EleShop, for € 450 incl VAT, which makes it only marginally more expensive than the ubiquitous Rigol DS1052E with 320×240 display and 50 MHz bandwidth.

This thing is amazingly thin (total size is 7 x 34 x 16 cm), yet packs an 800 x 600 pixel color LCD screen to present a really detailed display (click to see the full size image):


In a way, more is better. But keep in mind that the 8-bit ADC’s typically used in modern “affordable” scopes can only measure 256 different voltage levels full-scale. To really benefit from 512 or more vertical pixels resolution, you either need a 9-bit ADC or some sort of oversampling and averaging. Having said that, I would definitely consider 320×240 as low end nowadays – this screen is a huge improvement, in displaying much finer detail as well as in helping estimate voltage levels at a glance.

Here’s an example of just how much screen real-estate this scope has:


You might recognise the two waveforms above as the 10 MHz and 25 MHz signals generated by my signal generator – same as used in this recent weblog post.

Tomorrow, I’ll show you the front panel and I’ll add some comparative notes…

Instrument limits

In Hardware on May 3, 2013 at 00:01

Last week’s post illustrated some limitations of electronic measuring equipment. In this case, I was using the TTi TG2511 Arbitrary Waveform Generator (which I have yet to use for “arbitrary” waveforms) and the Hameg HMO2024 Digital Storage Oscilloscope.

The TG2511′s rise and fall times are specified in the neighbourhood of 10 ns, which has a fairly atrocious effect on a 25 MHz “square wave” signal:


(the scope’s own rise time is under 2 ns)

Both are excellent instruments, but already fairly high-end for hobbyist use. To put it in perspective: the total cost of this sort of equipment is more than a hundred JeeNodes with sensors! Add to that the fact that you only need the higher specs of these instruments once in a while (how often depends of course on your level and depth of interest), and it’s pretty obvious that it can be very hard to justify such expenses.

I’ve always been annoyed by this. And I’ve always been on the lookout for alternatives:



That’s the Xminilab, mentioned recently, and a sine-wave generator from eBay. The total cost for both is around €100.

Unfortunately, lower-end equipment really does have lower-end specifications. The measurements made yesterday could not have been done with the above, for example: sine waves are not square waves, and the 2 megasamples/second of the Xminilab scope is not fast enough to analyse rise times at 1 MHz, let alone 10 MHz.

Tomorrow, I’ll explore (“review” is too big a word for it) a more affordable modern oscilloscope, to show what can and cannot be done with it.


In Hardware on May 2, 2013 at 00:01

The other day, someone gave me an autotransformer – a hefty 10 kg of metal and wires:


Made by Philips, probably well over half a century ago (even before Philips had a logo?):


AC mains did not include grounding at the time, just 2 banana jacks spaced 19 mm apart:


So what does it do? Well, an autotransformer (a.k.a. Variac) allows you to generate an adjustable AC voltage from the fixed AC mains voltage. At the time, AC mains was 220V – nowadays, it’s 230V in Europe, so the output should now reach 260/220*230 ≈ 272 VAC.

Here’s the schematic, similar to the one printed on the side of this device:


(this isn’t fully variable, like the unit above, but the taps are a first approximation)

One way to explain what’s going on – at least as first approximation – is that it works like a transformer, but with a variable number of turns on the secondary side. Think of the incoming voltage as generating an alternating magnetic field of a certain strength, with X Volts per turn. The “tap” (which is a mechanical wiper) makes contact with one of the turns of all the turns laid out in a circular fashion, creating a circuit with a variable number of turns. The more turns, the higher the output voltage.

The intriguing bit is that the output voltage can actually exceed the input voltage, by adding a few more spare turns at the top – or equivalently: by placing the input voltage on a tap and not entirely at the end of the coil.

Note that the output of such an autotransformer is not isolated from the input, unlike regular transformers with separate primary and secondary coils.

The other difference is that part of the energy is not transferred as magnetic flux, but directly through the shared windings. It merely acts “more or less” like a regular transformer, in practical use.

I’m very pleased with this gift, which will allow me to explore the effects of a varying AC mains voltage on all sorts of appliances, power supplies, etc. – from very low voltages to somewhat over the normal 230 VAC.

Meet the Manson NSP 3630

In Hardware on Apr 30, 2013 at 00:01

It’s always nice to explore more equipment, to see how it behaves in the lab. I already have a very nice dual-voltage lab power supply, but this one is interesting due to its relatively low cost (€90 + shipping), fairly high power, and very convenient small size:


It’s the Manson NSP 3630, available from Reichelt in Germany by mail-order. At 27 x 15 x 7 cm, it really should easily fit in most home labs. With many thanks to David Menting for letting me play with it a bit and report some first impressions.

The display is quite simple, yet still nicely readable:


Power consumption, without any load is 0.07W when turned off with the power switch on the back of the unit, and about 2.0W when turned on, without load.

There are two (optical encoder) rotary knobs to adjust the maximum voltage and current, respecively, over a range of 0.7 .. 36V and 0 .. 3A – i.e. plenty for most situations.

A drawback with this particular supply, is that it’s a bit of a hack to pre-set the current limit. You can turn it down during use to reduce the limit to the point where the voltage starts dropping, but if you want to set it up ahead of time, then the way to do it is to short out the power supply while adjusting the knob, to see the value it displays.

This is a switched-mode power supply, which explains why it is so small and requires only a small fan, but it does lead to some residual noise on the output. Hooking it up to the scope, still under no-load conditions, you can see that the output varies between about +10 mV and -20 mV of “ripple” above and under the preset value, respectively (5V in this case):


To produce this image, the scope was set to “peak-detect” mode, which captures the high and low value at each point in time, and the trace is drawn in “envelope” mode, which is a variation of persistent display showing the most extreme values ever reached as long as the scope is kept on. The last trace is the one shown in the middle, while the top and bottom lines are the largest variations ever reached – I think I left it running for a minute or so.

It’s a pretty good result, actually, for a switching power supply. Variations of this kind should not cause any problems for most digital circuits, which usually can tolerate fairly large variations on the power supply lines.

Three laws – part 3

In Hardware on Apr 29, 2013 at 00:01

Yesterday’s post was about Kirchoff’s Current Law.

Now let’s look at the second version of that law, Kirchhoff’s Voltage law:

JC's Grid, page 72

This law says something about the voltages in a circuit: voltages cancel out, regardless of which way you follow a path in the circuit, i.e.:

V1 - V2 - V3 = 0    (hence V1 = V2 + v3)

But also:

V3 - V4 - V5 = 0    (hence V3 = V4 + V5)


V1 - V2 - V4 - V5 = 0    (hence V1 = V2 + V4 + V5)

The signs are based on how the arrows are drawn: voltages are always relative, so it all depends on the direction of each of those arrows. Since V2 and V3 are opposite to the direction of “following” a single path through the circuit, they end up negative in the above equation. Same for V4 and V5.

Now this version of Kichhoff’s law is really useful. If each of the resistors has the same value (it doesn’t matter what the value is), then we can reason about the voltages in different parts of the circuit, even when only V1 is known at the start.

Let’s look at this circuit again in terms of voltages, with V1 set to 3V:

JC's Grid, page 72

Since V1 = V2 + V3, and all resistors have the same value, it’s a safe guess that the voltage over both will be the same. A more exact reasoning is to include the currents, and since they are the same for the two resistors on the left, we know that the voltages will be the same (Ohm’s law, regardless of the value of these resistors – as long as they are the same).

Perhaps a bit more surprising is that V4 is 0V. This is again a consequence of Ohm’s law: since the pins on the right are not connected, no current will flow. With no current, the voltage over a resistor is always 0V (Ohm’s law, again).

Since V4 is 0V, and V2 = V4 + V5 as we saw above, V5 must be 1.5V, the same as V2.

Note how a voltage over a resistor can be zero, and over two open pins can be non-zero.

If we use a multi-meter with a really high input resistance (any modern multi-meter will do, usually they have 10 MΩ or more), to make sure no current starts flowing, then we can indeed measure the voltage to be half of the 3V between top and bottom, i.e. 1.5V.

The main point to take away from this, is that the three laws are intimately inter-connected. Given known resistors, which is often the case, Ohm’s law dictates the relationship between voltage and current, and with the two variants of Kirchhoff’s law, it is usually possible to “reason your way into” the different points in a circuit, given an externally applied power supply.

One last example: what is the equivalent resistance of two resistors of 1000 Ω in parallel? Well, say we apply voltage V1, then the current through one resistor will be V1/1000. The same current will go through the other resistor, since it too has V1 on both pins. So the total current of the two in parallel will be 2 x V1 / 1000 = V1 / 500. What is the resistance when we apply V1 and see a current V1 / 500 flowing? Again, Ohm’s law: R = U / I, i.o.w. R = V1 / (V1 / 500) = 500. So the general answer is: the equivalent resistance of two resistors in parallel is half their resistance. A direct consequence of Ohm’s and Kirchhoff’s laws.

Get used to the three laws, and with a bit of practice, the rest should fall into place!

Three laws – part 2

In Hardware on Apr 28, 2013 at 00:01

After Mr. Ohm yesterday, let’s see what Mr. Kirchhoff has to say.

Kirchhoff’s First Law is about current. In a nutshell – what goes in, must come out:

JC's Grid, page 72

I’ve drawn resistors, but that’s really irrelevant here – each component could be anything.

The current I1 must be the same as the current I2, It does not matter what I3 is in this case (assuming the two pins next to it are not feeding or drawing any outside current).

Also, if I3 is zero, i.e. if the pins are not connected to anything at all, then the current through the leftmost resistors is identical. In this case, they are essentially in series, with the resistor on the right not doing anything at all (no current = no voltage drop = Ohm’s Law).

This makes it possible to reason about that point in the middle, where the three resistors meet. The currents at that point must cancel out: that’s what Kirchhoff’s Current Law says.

Suppose all three resistors are 1 kΩ, and the current I1 is 1 mA:

JC's Grid, page 72

If the two pins on the right are left open, no current will flow there. So the same current I1 (which is also the same as I2) will flow through both resistors on the left. Total voltage drop from top to bottom will be 1 mA x 1 kΩ = 1V on the top resistor and another 1V on the bottom one, for a total voltage of 2V across the left two pins.

Or to put it more practically: if you place a 2V supply across those left two pins, then 1 mA will flow. The voltage in the center point will be halfway, i.e. at 1V.

What will happen when we short the pins on the right?

JC's Grid, page 72

Again, there’s 1 mA flowing in from the top, so there will be 1 mA coming out the bottom. The bottom-left and right resistor will together see a current of 1 mA going through them. Since they are both the same 1 kΩ, it should not come as a surprise that each resistor will get half the current, i.e. 0.5 mA each. Total voltage from top to bottom will be 1.5V.

This isn’t such a great example in terms of practical use, since normally the reasoning goes the other way around: what current will flow when I apply voltage X to the entire circuit?

That’s the other version of this law, described tomorrow.

Three laws – part 1

In Hardware on Apr 27, 2013 at 00:01

It’s always a puzzle to predict just what will happen when you hook up some components.

But as mentioned in the what-if series, it’s really useful to be able to do so, to avoid surprises and damage. Also for questions such as: Why does a higher voltage cause a higher risk of damage in one case and less so in the other? Why do I need a resistor in series, and of what value? What if I don’t have the right resistor or a different voltage?

Lots of complex issues, but the simplest and most important case usually is static analysis and DC (direct current) voltages, i.e. when only one or two states are involved, and not so much the switching and AC (alternating current) behaviours.

You just need to get familiar with three “laws” of electricity:

  • Ohm’s Law – given two of: voltage, current, and resistance, we can predict the third.
  • Kirchhoff’s Current Law – current always adds up: what goes in, must come out.
  • Kirchhoff’s Voltage Law – how voltages “spread” across interconnected components.

That and learning what the basic behaviour is of resistors, diodes, capacitors, etc, and you’ve got all the knowledge you need to “see” what a circuit does, before even building it and trying it out. And by this I really mean literally “visualising” what is going on – it only takes a little practice to turn this into a very intuitive skill.

You just have to grasp the essence of those three laws. So let’s get on with it, eh?

Ohm’s Law

This is by far the most important one. It says everything about resistance. The unit of resistance is – not surprisingly – the “Ohm”: a resistor of 1 Ohm will let 1 Ampère of current flow when you apply 1 Volt of electric potential difference over it. The formula is:

U = I x R

(U = voltage, I = current, R = resistance)

Same law, different uses, by simple algebraic manipulation: I = U / R, and R = U / I. If you know two of the units, you can calculate the 3rd.

  • What happens when I touch both poles of a car battery?
    My skin resistance will be some 100 kΩ, so I = U / R = 12 / 100,000 = 0.000,12 A = 120 µA. A tiny current, I wouldn’t sense a thing, so the answer is: “nothing happens”.

  • What happens when I place a metallic nail across that same 12V car battery?
    Let’s say the resistance of that nail is 0.1 Ω, i.e. almost a short, so I = U / R = 12 / 0.1 = 120 A, a huge amount of current. The nail will heat up like crazy, it might even melt!

Same battery, very different outcomes.

And it’s not just useful to predict such extreme cases. It also helps understand why some hookups are inherently safe: if my power supply delivers no more than 5V, and I am playing with resistors of 1 kΩ or more, then no matter how I hook things up (apart from shorting things out), there will never be more than I = U / R = 5 / 1,000 = 0.005 A = 5 mA of current through my circuit. A 1 kΩ resistor in series with just about any component will “limit” the current to 5 mA, which virtually prevents damage to just about any component.

Another example: suppose I am using a 12 V power supply, and want to turn on an LED with it. Most LED’s glow nicely at 20 mA. So if I put a R = U / I = 12 / 0.020 = 600 Ω resistor in series with the LED, I can be certain that the LED won’t get damaged. Better still, if I only have a 1 kΩ = 1000 Ω resistor, I can predict that it’ll probably work just fine in this same circuit as the current will be at most I = U / R = 12 / 1,000 = 12 mA. Using a 100 Ω resistor would be a bad idea (max current 120 mA), and using a 10 kΩ resistor probably also wouldn’t work (1.2 mA might be too little to make the LED light up).

These are all approximations, but they are extremely useful – even as such.

Some consequences of the simple ” U = I x R ” formula Georg Simon Ohm gave us:

  • twice the voltage => twice the current
  • twice the resistance => half the current
  • twice the current => twice the voltage drop

One thing to take away from all this, is that it’s not a bad idea to buy some 100 Ω, 1 kΩ, and 10 kΩ resistors. Having a bunch of spare resistors can often come in handy, as a way to limit the current (and hence avoid damage), and these three values are often all you need to try out a few things in circuits running at 1.5 .. 12V.

Tomorrow, we’ll give the stage to Gustav Kirchhoff!

What if I mix 3.3/5.0V – part 3

In Hardware on Apr 26, 2013 at 00:01

Welcome to the weekly What-If series, also available via the Café wiki.

There’s still much more to say about all this – as can be expected. One of the suggestions made in the comments was to use a few diodes in forward direction. Since these each have about 0.65V drop, three of them ought to bring down the voltage from 5.0V to 3.3V.

Time to hook up the signal generator and scope again. Be prepared for some surprises!

As I mentioned in my original post, the “official” way to handle this, is to use a “level converter” chip, which is based on some active circuitry, i.e. some transistors or MOSFETs. The resistor solutions described yesterday are less accurate, as you’ll see…

Here is a 1 MHz square wave @ 5V (yellow) feeding yesterday’s 4.7 kΩ + 10 kΩ resistive voltage divider to produce a 3.3V signal (purple):


That’s quite a different signal coming out! A typical capacitive charge / low-pass effect.

Note that the signal generator has a ≈ 10 nS rise-time, i.e. the edges are not completely vertical, and that the Hameg scope probe has a 14 pF loading capacitance, according to the specs. So some of these effects are artefacts of this measurement setup.

Let’s raise the frequency to 10 MHz (the horizontal scale is now a very fast 10 ns/div):


Hardly a square wave, and no well-defined 0-to-3.3V transitions either, as you can see.

Now let’s try this circuit:

JC's Grid, page 71

The reasoning being that the diodes will “drop” the voltage from its high 5V level to 3.3V:


Quite an asymmetric effect, although lowering the resistor to 1 kΩ ought to improve it.

The above is again a 1 MHz square wave input, and here’s the same at 10 MHz:


This final setup is so far off the desired voltage levels that it probably won’t work.

Given these outcomes, I’m inclined to stick with a single 10 kΩ resistor in series. Or perhaps drop it to 1 kΩ to get better rise and fall times. Active MOSFET-based level-shifting circuits are starting to make a lot more sense now – they exist for a reason!

What if I mix 3.3/5.0V – part 2

In Hardware on Apr 25, 2013 at 00:01

Welcome to the new weekly What-If series, also available via the Café wiki.

Yesterday’s post was about mixing 3.3V logic levels with 5V logic levels.

The real trouble, apart from things not working, is damaging some component, of course. And in electronics, almost all damage comes from overheating. At some point (well over 100 °C, usually), chips really do get “fried” and irrevocably damaged occasionally.

The trick is to avoid overheating. This in often easy to do by limiting the current that can flow. How do you limit the current? Simple: make sure there are some resistors in series!

But first, let’s examine what’s really going on when we connect a 5V logic “1″ to an input which handles only 3.3V logic levels:

JC's Grid, page 71

On the left, the typical circuit inside a digital chip at each I/O pin. The essential ingredients are two ESD protection diodes to VCC and GND, respectively, and the MOSFET input gate.

The diodes are placed in the “blocking” direction, i.e. they normally do nothing but block the current. The MOSFET gate is a very high impedance input, essentially it acts just like a capacitor, in fact. The rest of the input circuitry can be ignored for our purposes.

So normally, input signals on such a pin just “float” and follow whatever voltage is applied. Until the voltage is too high, or too low, that is.

On the right, I’ve redrawn the exact same circuit, but “lifting” the input well above VCC level. To make this clear, I’ve drawn the input pin above the VCC pin, as an intuitive way to represent voltage as height in the diagram.

Now you can see what happens above VCC + 0.65 or so: the top diode will start to conduct in this situation. So if the input is set to 5V, and VCC is 3.3V, then the diode will become a conductor and try to pull either 5V down or 3.3V up, to reach equilibrium again.

This is a danger sign. The amount of current flowing will rise as long as these voltages are more than about 0.65 V apart. If both power supplies are very strong, there could be several amps of current – the 5V supply could even start powering the 3.3V circuit!

And that’s where the damage-through-heat comes in: a 1 A current over a diode with a 0.65 V difference leads to 0.65 W of heat being dissipated. Far more than these tiny on-chip diodes can handle. In fact, they really are only designed to carry up to a milliamp or so. The result: a “blown” on-chip diode, and since the voltage difference continues to exist, the damage will probably propagate to other diodes and components on the chip.

There are a few ways to prevent this. One is to use special “level-converter” chips, designed to take one voltage on the input, and then generate a different voltage on the output.

But there are much simpler ways to deal with such small differences, especially when the pins are all close together and on the same board:

JC's Grid, page 71

On the left, a traditional 4.7 kΩ + 10 kΩ resistive “voltage divider”, which takes one voltage and divides it down to a lower voltage. This works, but in this case we can even get by with a single resistor, as shown on the right.

The reason the single resistor works, is that current will start to flow through the diode as before, but now also through the 10 kΩ resistor. Since the circuit seeks equilibrium, in this case, there will be about 5.0 – 3.3 = 1.7 V across resistor + diode, i.e. ≈ 1 V across the resistor. With a 10 kΩ resistor, it only takes 0.1 mA of current to generate a corresponding voltage drop, so that’s when equilibrium will be reached. These current levels are completely harmless and can easily be sustained by the on-chip diode.

So there you have it: we’ve explained why direct connections might lead to overheating, and how a 1..10 kΩ resistor in series can prevent it, while still allowing the circuit to work.

All this required, was some theory and a basic understanding of the internal circuitry.

PS. These resistor solutions are sensitive to noise and capacitive loading (they act as low-pass filters), so this only works well when signal lines are short, a few cm or so. For reliable high-speed signaling over longer distances, a level-shifter chip would be a better way to go.

What if I mix 3.3V and 5V?

In Hardware on Apr 24, 2013 at 00:01

Welcome to the new weekly What-If series, also available via the Café wiki.

As you probably know, mixing 3.3V logic with 5V logic is usually a bad idea, but why and what if you need to do it anyway?

This topic is too complex for a single post, but let’s just start and see where it leads to:

  • VCC in these examples is the supply voltage, i.e. either 3.3V or 5.0V, depending on which chip we’re looking at. The goal being to connect a mix of these.

  • Digital I/O pins work by treating everything below a certain voltage as “0″ and everything above another voltage as “1″. In between, the levels are undefined and could be interpreted either way, depending on temperature, stray capacitances, moon phases, who knows…

  • For the ATmega328, for example, everything between -0.5V and 0.3 x VCC is treated as “0″ and everything between 0.6 x VCC and VCC+0.5V as “1″.

  • For 5V signals, that translates to: under 1.5V is “0″ and over 3.0V is “1″, respectively.

  • Also relevant, is that unloaded output pins tend to be very close to the 0V and VCC ground and power supply levels, respectively.

So mixing is in fact not a problem at all for the following scenario: 3.3V levels for output signals, tied to 5V levels for the input signals. If all you need, is to read logic levels on say a 5V Arduino Uno from a 3.3V JeeNode, then just tie the signals together and you’re all set.

Connecting a 3.3V level output pin to a 5V level input pin works fine.

The problem occurs in the other direction: a “1″ output on a 5V logic level is about 5V, whereas the maximum allowed input level for a “1″ on a chip powered by 3.3V is 3.3+0.5, i.e. at most 3.8V.

Hooking these together without taking care of the problem will lead to problems, such as overheating chips and even smoke or fire (although this is almost impossible with simple battery- or USB-powered hookups).

Tomorrow I’ll describe the cause of these problems, along with some simple solutions.

Cheap power analysis

In Hardware on Apr 21, 2013 at 00:01

Remember this screen shot?


It was a carefully captured analysis of the power consumption of a JeeNode, running the RoomNode sketch, and sending / receiving wireless RFM12B packets. There’s a fantastic amount of info in there, to help understand which part of the code and which activity is drawing the most power. It was a great help at the time to reduce power consumption, allowing these nodes to run well over a year on a couple of AA batteries.

Trouble with this, is that you need an expensive piece of equipment, called an oscilloscope. Long-time readers might remember that I’ve written extensively about this. These things cost anywhere from a few hundred Euro, to thousands, or even tens of thousands for high-end units. I ended up settling for a Hameg HMO2024, which is a great instrument, but with a pretty hefty price of well over €1000.

So how would you go about analysing the power consumption of your sketch without plunking down this sort of cash? Well, there really are not that many alternatives, you have to see the current-vs-time graph to be able to understand what’s going on.

Luckily, there is a fairly capable little unit from Gabotronics, called the Xminilab. It pushes an ATXmega (note the “X”) to its limits, allowing it to capture quite a bit of information, just like its bigger brothers. It even includes things like FFT analysis, an 8-channel Logic Analyser, and an AWG Signal Generator! Last but not least, the software is open source.

Interested in how capable this $69 device is? Well, check this out:


Do you recognise the waveform? The Xminilab has captured a packet transmission, a bit like the one shown at the start of this post (it’s a different sketch, i.e. radioBlip2, hence a different pattern). It may not look like much, but it should be sufficient to see the effect of changes in the code and to optimise power consumption with it.

So, do you need a scope? IMO, anyone wishing to explore electronics should have one. Whether second-hand or the above-mentioned Xminilab, it really helps to be able to see things in a way where our human senses fall short – such as these brief events. It’s the most versatile instrument in the lab, if you ask me – even with a 128×64 pixel LCD screen.

PS. I don’t recommend the even lower-cost $49 Xprotolab (which I also have). It has the same functionality, but with its tiny OLED display it really is too hard to read, IMO.

Direct relay switching – final

In Hardware on Mar 19, 2013 at 00:01

To conclude this little excursion into relay switching, here is the final circuit:


I’ve re-wired everything to use two DIO pins, and removed the extra 10 Ω resistor:


Bottom side:


The sketch can now switch both I/O pins using a single instruction, and avoid the brief shorting out of the I/O pins on the ATmega:

void setup() {
  digitalWrite(5, 0);
  digitalWrite(6, 0);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

static void setLatch (bool on) {
  // change both I/O pins in the same clock cycle
  if (on)
    PORTD |= bit(5) | bit(6);
    PORTD &= ~ (bit(5) | bit(6));

void loop() {

This also gets rid of the inductive kickback, or rather, it “diffuses” that effect into the slow capacitor charge and discharge ramps. All in all, I think this setup is a viable circuit for low-power switching of this tiny relay.

I’ve ordered a few more of these units, and intend to try them out with live 230 VAC mains switching. Note that this is pushing it, and that it will most definitely not meet all rules and regulations for mains separation and isolation – but for just controlling small lights, and other small devices such as power adapters and chargers, I think it’s still usable, and am willing to try it – at least for personal use around the house here at JeeLabs.


Direct relay switching with a cap

In Hardware on Mar 18, 2013 at 00:01

Let’s explore this direct relay switching a bit further …

As suggested by @tmk in one of the comments, it is also possible to drive this thing with a single I/O level change by inserting a capacitor in the circuit, i.e. using just 2 I/O pins:


The idea is that the (opposite) charge and discharge currents pulses will be sufficient to make the latching relay switch state. The electrolytic cap takes the place of the pulse software, which can now be simplified to just switch high and low:

static void setLatch (bool on) {
  if (on) {
    bitSet(PORTD, 6); // D.6
    bitSet(PORTC, 2); // A.2
  } else {
    bitClear(PORTD, 6); // D.6
    bitClear(PORTC, 2); // A.2

The extra 10 Ω resistor in series with the cap is used to measure the current in the circuit and show it on the scope:


I’ve added the integral of the current in red, which allows calculating the total charge consumed by this circuit when switching the relay. A quick visual estimate tells me that the surface under the current pulse is about 50 ms x 50 mV, and since I’m measuring over 10 Ω, that corresponds to 50 ms x 5 mA = 250 µC. The actual integral is more like 350 µC. This corresponds to drawing 350 µA for one second, every time the relay is switched – which would presumably be done only a few times a day, so this is still within the capabilities of a battery-powered JeeNode.

There’s a strange hump at the start – here it is again, zoomed in:


I suspect that it is caused by relay contact bounce, and the change in inductance as the latching relay core toggles to its alternate state. The relay’s inductance is about 95 mH, according to my low-cost LCR meter – i.e. a 40 Hz resonant frequency combined with that 100 µF cap, so this can’t be a resonance issue (that would have to be in the 25 ms range).

Tomorrow, the last post about this topic, with the final circuit and code…

Direct relay switching – part 2

In Hardware on Mar 17, 2013 at 00:01

Yesterday’s post turns out to uncover a lot of trouble spots and mistakes on my end w.r.t. switching small relays. Get ready for some scope shots ahead, to see what’s going on…

But first, the code I’ve been using:

void setup() {}

static void setLatch (bool on) {
  pinMode(5, OUTPUT);  // DIO2
  pinMode(15, OUTPUT); // AIO2
  pinMode(6, OUTPUT);  // DIO3
  pinMode(16, OUTPUT); // AIO3

  digitalWrite(5, on ? 0 : 1);
  digitalWrite(15, on ? 0 : 1);
  digitalWrite(6, on ? 1 : 0);
  digitalWrite(16, on ? 1 : 0);

  pinMode(5, INPUT);
  pinMode(15, INPUT);
  pinMode(6, INPUT);
  pinMode(16, INPUT);

void loop() {

Basic idea: set the pins as outputs, set the levels right, wait 3 ms, then set the pins as input again, i.e. in high-impedance mode, to stop driving the relays.

There are two very serious problems with this code. The first one is that the I/O pins are set to inputs at the end. This means there is no good path for the inductive kick energy to go, leading to this very nasty waveform across the relay – same as shown yesterday:


Note the extreme voltage levels across the coil – way beyond the ± 3.3V you’d want to see in a good 3.3V totem-pole configuration.

It turns out that there is a surprisingly simple solution for this – don’t make the I/O pins inputs, but put them all the same output level, so that no current flows through the relay (as before), but with the I/O pins still being outputs, i.e. able to conduct current.

Here’s is the entire pulse again, at maximum scale this time:


(the lines are so thick because the input is set to peak-detect mode in the scope)

No more funny business! A fairly clean on and off transition, just a bit of “sagging” as the two I/O pins in parallel struggle (successfully) to supply the required current. It looks like the inductive kickback is now absorbed by the output pins which are all set to “0″, i.e. conducting to GND.

I’m surprised by how well this seems to work. I’m guessing that the CMOS switches in the ATmega’s pin driver are able to conduct in both directions when enabled, and that the ESD protection diodes are absorbing any voltage excursions outside the 0 .. 3.3V range.

But a much bigger problem probably, is that the original sketch was shorting out the DIO and AIO pins against each other – producing a very bad intermediate voltage level:


The time scale is completely different now, and as you can see, the voltage level goes through a strange middle state. This is caused by the fact that the digitalWrite() code is very slow, compared to the actual speed of the ATmega. It’s taking 4 µs to process each call, and as the first one is set to one value, the other pin connected to it can still be in the other state. So this is – briefly – shorting out two I/O pins, set to different values!

Very very bad – this may well reduce the lifetime of the ATmega µC. As it turns out, my choice of I/O pins makes it impossible to set both I/O pins simultaneously. But the least I can do without re-soldering, is to use the much faster bitSet() and bitClear() calls – even though this makes the code slightly harder to understand:

static void setLatch (bool on) {
  if (on) {
    bitSet(PORTD, 5); // D.5 = DIO2
    bitSet(PORTC, 1); // A.1 = AIO2
  } else {
    bitSet(PORTD, 6); // D.6 = DIO3
    bitSet(PORTC, 2); // A.2 = AIO3


  bitClear(PORTD, 5); // D.5 = DIO2
  bitClear(PORTC, 1); // A.1 = AIO2
  bitClear(PORTD, 6); // D.6 = DIO3
  bitClear(PORTC, 2); // A.2 = AIO3

The switching times are now dramatically closer together, more like 0.12 µS in fact:


Note that you’re looking at the superposition of both the rising and the falling switching waveforms in this case, as an easy way to see both in one screen shot.

For more information about inductive kickback and protection diodes: there’s an article by Douglas Jones – it’s full of useful information, even though it’s geared towards driving DC motors and stepper motors. The same principles apply when driving the coil in a relay.

So the conclusion seems to be that this specific relay could be driven from 4 I/O pins, without requiring any further circuitry. And since it’s a latching relay, this can easily be done on battery power: it merely takes a 3 ms pulse to make it switch, i.e. about the same amount of energy as sending out one RF12 packet!

Direct relay switching

In Hardware on Mar 16, 2013 at 00:01

There are small relays which are just weak enough to be switched directly by the ATmega’s I/O pins, even at 3.3V. I’ve been chasing and trying out these types of relays for some time, especially the latching types which only require power to switch, not to stay on.

Today, I received a very nice surprise package from @eljonco, who sent me a nice little latching relay (from eBay) which I’ve immediately mounted on a Proto Board:


Bottom side connects DIO2 + AIO2 to one side of the coil, and DIO3 + AIO3 to the other:


Why both? Because one pin drive is not strong enough to make these units switch at 3.3V:


…whereas driving them both in parallel works, resulting in a clear clicking sound and a very nasty “inductive kick-back” switching pulse across the coil on power-off:


There are horrific things going on here, electrically speaking, which I’ll look into later.

For now, let me just explain what’s going on and how this single-coil latching relay is being switched, using four I/O pins (port 2 and 3 on a JeeNode in this case):

JC's Grid, page 68

The relay core can be switched with a brief pulse, reversing the polarity to reverse the action. So we connect it to two different I/O pins and drive it as an H-bridge. When both pin levels are the same (or when the I/O pins are floating), nothing happens. By putting one pair in “0″ state and the other in “1″ state, current flows through the coil.

So to turn the relay on, the actions are:

  • set DIO2 = AIO2 = 0
  • set DIO3 = AIO3 = 1
  • wait 3 ms
  • set DIO3 = AIO3 = 0 (same as DIO2 and AIO3), or make them float, i.e. inputs

To turn it off, we simply exchange the 0′s and 1′s in the above.

More on this tomorrow. Stay tuned…

Unwanted RF

In Hardware on Mar 15, 2013 at 00:01

Houten is not a good place to be if you want to analyse signals in the 100 MHz range …

After looking into some switching regulator artefacts for a while, I’ve concluded that there is nothing wrong with my circuit after all. It’s all due to a nearby FM broadcasting tower!

(367 m high and about 10 km away: the Gerbrandytoren in Lopik – for the Dutch readers)

Getting rid of RF electromagnetic waves is hard. You need a Faraday cage, but you also have to prevent all unwanted RF from entering via measurement and power cables – and it has to work at all the frequencies you’re examining!

I doubt I’ll find a way to get rid of this, but the least I can do is to measure it:


Whoa – nice FM antenna!


Now let’s do the right thing and use a coax cable with internal 50 Ω termination in the scope turned on, and the input sensitivity increased to 1 mV per division:


Again, nice antenna. The “noise floor” is now 20 dB (100x) lower – a much cleaner signal:


And finally, just to make sure it’s really the loop that is picking up the signal, let’s replace that loop by a 50 Ω terminator on the input side as well:


Ah, now we’re getting to the bottom of this – a 30 .. 35 dB reduction:


Note that we’re still picking up very weak FM signals (no cable shielding is perfect). But it’s clear that the incoming signals are coming from antenna-type pick-up of electric fields, not some fault in the measuring setup, or that switcher I was investigating.

Let’s just hope I never have to really chase and analyse signals in this frequency range!

What’s a measly 2 cm?

In Hardware on Mar 12, 2013 at 00:01

As promised, one last post about decoupling capacitors. Unlike yesterday, this one is about that 0.1 µF ceramic capacitor again – the kind which gets used all over the place in through-hole designs such as the JeeNode:

Screen Shot 2013-03-10 at 19.49.17

Let’s compare the 200 kHz .. 20 MHz sweep signal absorption when connected far away from the cap (white), i.e. with long leads, vs. connected right next to the cap (yellow):


Whoa! – a substantial effect at higher frequencies if we include the long leads!

If you try to think about this in a simple “DC electricity” way, then 2 cm of extra wire is nothing: let’s for the argument’s sake assume that electricity travels at the speed of light. Then 30 cm = 1 ns, i.e. 2 cm is less than 70 picoseconds. A 16 MHz frequency has a 62.5 ns period, i.e. 19 meter wavelength, which completely dwarfs those measly 2 cm wires.

But propagation is not what’s messing things up here, not with those “low-end” 16 MHz ATmega’s I’m experimenting with anyway. The effect shown above comes from any wire adding some parasitic impedance (and capacitance) to the circuit. Plus some transmission line effects, probably. As you can see, those little extra 2 cm cause a noticeable degradation of the 0.1 µF cap’s decoupling capability.

This also applies to traces on a PCB, by the way. The guideline to add de-coupling caps as close as possible to the source of the switching disturbances is a serious matter!

With thanks to Martyn, for helping me understand the issues presented in these posts.

PS. Part of the impedance increase in all the screen shots made in the last few posts has been identified as a bad cable from my signal generator to the test setup. Doh! – with a much better cable (90% coax with clips at the end), the extra rise towards 20 MHz is gone. Still, this does not significantly affect the general shape or outcome of these experiments.

Resonator and crystal

In Hardware on Mar 11, 2013 at 00:01

Today, some more experiments with a sweep frequency to see how different components respond to it, beyond the cap-which-is-also-an-inductor of yesterday.

The first one I’d like to show is the 16 MHz resonator used in JeeNodes:


As you can expect it has a very sharp impedance change at its 16 MHz frequency:


(The bottom half is a greatly zoomed-in section from the far right of the entire sweep)

The blue area sticking out the back is the current through the resonator. As you can see, there is a very noticeable yet narrow range of frequencies at which things change. Plus a little parasitic inductance, indicated by a modest rise in signal amplitude near the 20 MHz end of the range.

An even more pronounced frequency-dependent component is the crystal, as used in just about every digital device around us these days. Crystals can have several different “modes” of oscillation, and can in fact resonate on different frequencies if the oscillator circuit around it is not designed properly.

Here, you can in fact see two modes of oscillation: a series-resonant “dip”, followed by a parallel-resonant “peak”. Note that this is a 10 MHz crystal, taken from an RFM12B module, with the total sweep scale from left to right being only 9.99 .. 10.01 MHz:


The resonant frequency seems to be about 150 ppm low, which is not surprising, since the crystal is not being driven by a real oscillator at all, nor with the proper capacitive loading – it’s simply “resonating along” with the frequencies applied to it.

These pictures as not just gimmicks. If you think about it, the behaviours shown above in a way almost define what these resonators and crystals do. It is precisely this “little” effect on impedance which allows us to create oscillators that resonate at very specific frequencies. Without them, we’d still be living in Tesla’s and Marconi’s age of sparks: maybe enough to get some morse code across, but a far cry from fitting dozens of HD television channels into separate adjacent frequency bands – or a fiberoptic cable, for that matter.

Tomorrow, I’ll have one final surprising result to show you w.r.t. “parasitics” …

It’s no longer a capacitor!

In Hardware on Mar 10, 2013 at 00:01

Yesterday’s post was about plotting the response of a decoupling capacitor versus frequency. It might not seem like much, but this is in effect exactly what a Spectrum Analyser with “Tracking Generator” does! You put a signal with a known frequency and amplitude into a circuit, and you look at the amplitude of the signal that comes out. As you saw, these plots give instant insight in what an analog circuit is doing to signals. And if we were to somehow also measure the phase shift of the signal, we’d in fact have a Vector Network Analyser – an instrument which usually costs more than an average car!

But let’s go back to decoupling…

First, let me show you the exact circuit setup I’ve been using:


The green dotted line is the AWG signal generator, and it has an internal resistance of 50Ω. You can ignore the 1Ω resistor, it was intended to measure current through the cap, but it turns out that the 50Ω helps us get the same sort of information.

Imagine this circuit hooked up next to a digital chip, with high-frequency “noise” reaching the top of the cap. As you can see in yesterday’s plot, the 0.1 µF cap becomes more and more a conductor as the frequency increases – which is exactly what we want, because that means the remaining voltage will consist of just the remaining low frequency changes, which are more easily dealt with by the power supply source.

Another way to look at this circuit is as a low-pass RC filter. It lets the lower frequencies through, and shorts the higher frequencies to ground.

The plots so far have all been from 1 kHz to 1 MHz. Let’s now raise the frequency sweep range a bit – from 200 kHz to 20 MHz (just ignore the blue trace):


Now that is odd – the amplitude starts to rise again with frequencies nearing 20 MHz! In fact, there seems to be a “saddle point” roughly in the middle. This is about 2 Mhz (the scale is still logarithmic, so every 5 divisions is now a factor 10 with these sweeps).

What’s going on here?

The answer is that all electrical circuits and components have parasitic effects. In this case, the capacitor also has some inductance. An inductance (i.e. a coil which generates a magnetic field) is just the opposite of a capacitor: it’s impedance rises with frequency.

So this 0.1 µF cap is in fact not able to short out high frequencies at all – it leaves them unaffected. Note that with an ATmega running at 16 MHz, we’re very solidly in that range of frequencies where the decoupling cap is becoming less effective!

To give you an idea how odd these caps behave: let’s add a 0.01 µF capacitor in parallel. You’d expect the result to be equivalent to a 0.11 µF cap – with the saddle point simply moving to a different place on the plot, right? Not quite:


They each do their thing and have their effects super-imposed, generating a double saddle. That, by the way, is why the more demanding circuits use exactly this very same approach to decouple various frequencies at the same time – just put some different caps in parallel.

Tomorrow, I’ll take a few other familiar components through this sweep setup…

Frequency sweep

In Hardware on Mar 9, 2013 at 00:01

This is the continuation of yesterday’s post about decoupling capacitors. As promised, some more information now about a test setup which can visualise some interesting – and quite surprising – effects.

The first part of the idea is to generate a “sweep” across a frequency range, i.e. a signal which increases in frequency from 1 kHz to 1 MHz within 10 seconds, and then repeats:


Such a signal can be generated with a “frequency generator”, in my case this AWG.

The second part is to inject this signal into the “Device Under Test” – i.e. a 0.1 µF ceramic capacitor in our case – and let an oscilloscope “sweep” across in lock-step with that signal:


Since the frequency increases with time, we end up with a display of the frequency on the X axis versus the signal amplitude on the Y axis:


The scope was set to display in peak-detection mode, to make the display “fill” with a band of the oscillating signal. The second signal is used to trigger each scan, which takes 10 seconds to complete (plus one second on each side for the previous and next sweeps).

As you can see, the amplitude of what gets through the cap decreases. Decreases? – yes, well, I simplified things a bit. There’s a resistor in series and the setup is actually measuring the voltage over the cap. As its impedance decreases, it shorts out the signal more and more. I’m deliberately skimming over some details to keep things short for this weblog post.

Looks like all is peachy, right? Not so fast…

First, let’s change the way things get measured a bit. Instead of linearly increasing the frequency from 1 kHz to 1 MHz, I’m going to switch to a logarithmic scale. This means that every 3.33 seconds, the frequency gets increased by a factor of ten by the AWG. So while the previous image had the frequency increase by some 100 kHz per division, now we have 33.3 KHz in the middle of the screen instead of 500 KHz:


It’s exactly the same result, but it doesn’t emphasise the higher frequencies as much. Note that we’re not really interested in the exact values, more in the shape of these curves – so I’ll omit the on-screen info from now on.

So why is that frequency response flattening out in such a clear way? Stay tuned…

Update – All arrangements have been made: JeeDay will be held in Houten, with excellent train access, on Friday evening April 19th and Saturday all-day April 20th.

Decoupling caps

In Hardware on Mar 8, 2013 at 00:01

As I wait for some fresh inspiration (oh, and some more JeeNode Micro v3′s) to arrive, let’s go into something that has intrigued me for a long time:

> What’s that “decoupling” stuff all about when designing electronic circuits?

The following information comes from a fantastic discussion with martynj, exploring ways to make this visible on the scope. I really learned a great deal – thank you, sir!

As you probably know, all chip datasheets have these little capacitors connected near the main chips, “for decoupling”. You’ll often see schematics with several of them:



What is decoupling? And decoupling what exactly?

Well, the problem is that power supply lines can get very noisy – lots of fluctuations you don’t really want, and if they get really bad, the chips will start to malfuction, mistaking a “0″ for a “1″ level or vice-versa. Not to mention the fact that high frequency signals will radiate into free air, turning a circuit on a PCB into an illegal transmitter – whoops!

Let’s not go into the “deeper” stuff: parasitic capacitance & inductance, dielectrics, etc. Instead, let’s just run some experiments with these humble little 0.1 µF “caps”:


As you’ll soon see, they are not capacitors at all – obnoxious little buggers, they are!

But first, the basic idea: due to digital switching, chips tend to generate a lot of very sharp current transitions. On an ATmega running at 16 MHz, these pulses are likely to be most pronounced at around 16 or 32 MHz, i.e. both the up and the down flanks of the main clock causing all semiconductors inside to switch.

Drawing a lot of current very abruptly is like suddenly pulling on a pendulum: it doesn’t immediately follow your request, but lags and has some trouble meeting the requested change. And when released, it tends to overswing, making the problem even worse.

Same with current changes – the power supply can’t quite match it, and so the voltage near the chip drops (and later overshoots) while trying to keep up. It’s the same effect as the lights dimming briefly when turning on a very power-hungry appliance in the house. It’s all about inductance if you really want to know, but let’s just ignore that for now.

Capacitors near the chip are like tiny (but very responsive!) reservoirs of energy, and they can be very effective in compensating for this dip.

So the general advice is: put decoupling caps between VCC and GND, as near the chip as possible, and the cap will “dampen” the demand to give the much longer connections to the power supply time to replenish the energy. Capacitors are great for this – and the closer they are to the consumer, the better they can handle even extremely brisk “spikes”.

Another way of saying this is: capacitors have an infinite resistance at 0 Hz (DC), i.e. they do not leak DC power, but as the frequency increases, they pass more and more current. This “frequency-dependent resistance” is actually called impedance – so as frequency increases, the cap’s impedance decreases. Spikes are – by definition – high-frequency. And the lower the impedance, the more these spikes get… s(h)orted out!

Tomorrow I’ll describe a little test setup to clearly demonstrate the effect of higher and higher frequencies being more and more absorbed by that 0.1 µF capacitor shown above.

Fourier analysis

In Hardware on Dec 8, 2012 at 00:01

The three scope shots shown yesterday illustrated how the output signal moves further and further away from the “ideal” input sine waves, near the limits of the AD8532 op-amp.

This was all based on a vague sense of how “clean” the wave looks. Let’s now investigate a bit deeper and apply FFT to these signals. First, the 500 KHz from my frequency generator:


You can see that peak #1 is the 500 KHz signal, but there’s also a peak #2 harmonic at 1 MHz, i.e. twice that frequency, and an even weaker one at 1.5 MHz.

My frequency generator is not perfect, but let’s not forget to put things in perspective:

  • peak #1 is at roughly 10 dBm
  • peak #2 is at roughly -40 dBm, i.e. 50 dB less

First off: I really should have set to scope to dBV. But the image would have looked the same in this case – just a different scale, so let’s figure out this dBm thing first:

  • 0 dBm is defined as 1 mW of power
  • the generator was set to drive a 50 Ω load, but I forgot to enable it
  • therefore the “effective load” is 100 Ω (off by a factor of two, long story)
  • the signal is swinging ± 1 V around a 2V base level, i.e. 0.707 V (RMS)
  • so the signal is driving ± 7.07 mA into the load (plus 14.14 mA DC)
  • power is I x V, i.e. 7.07 mA x 0.707 V x 2 (for the termination mistake) = 10 mW

Next thing to note is that dB and dBm (decibels) use a logarithmic scale. That’s a fancy way of saying that each step of 10 is 10 times more or less than the previous. From 0 to 10 dBm is a factor 10, i.e. from 1 mW to 10 mW. From 10 to 20 dBm is again a factor 10, i.e. 10 mW to 100 mW, etc. Likewise, -10 dBm is one tenth of 0 dBm (0.1 mW) etc.

The 500 KHz signal (peak #1) is therefore 10 mW (10 dBm), and the 1 MHz harmonic is roughly 100,000 times as weak at 0.1 µW (-40 dBm). It looks like a huge peak on the screen, but each vertical division down is one tenth of the value. The vertical scale on screen covers a staggering 1:100,000,000 power level ratio.

That 500 KHz sine wave is in fact very clean, despite the extra peaks seen at this scale.

Now let’s look at the same signal, on the output of the op-amp:


Not too bad (the second peak is still less than 1/30,000 of the original). Which is why the output shape at 500 KHz still looks very much like a pure sine wave.

At 1 MHz, the secondary peaks become a bit more pronounced:

SCR05 . SCR06

And at 2 MHz, you can see that the output harmonics are again a lot stronger:

SCR07 . SCR08

Not only has the level of the 2 MHz signal dropped from 9.23 dBm to 6.59 dBm, the second harmonic at 4 MHz is now only a bit under 1/100th the main frequency. And that shows itself as a severely distorted sine wave in yesterday’s weblog post.

In case you’re wondering: those other smaller peaks around 1 MHz come from public AM radio – there are some strong transmitters, located only a few km from here!

Anyway – I hope you were able to distill some basic intuition from this sort of signal analysis, if this is all new to you. It’s quite a valuable technique and all sort of within reach now, since most recent scopes include an FFT capability – the bread and butter of the analog electronics world…

Let’s now get back to digital again. Ah, bits and bytes, sooo much simpler!

Op-amp limits

In Hardware on Dec 7, 2012 at 00:01

Let’s look at that AD8532 dual op-amp mentioned yesterday and start with its “specs”:

Screen Shot 2012 11 24 at 22 54 50

The slew rate is relatively low for this unit. Its output voltage can only rise 5V per µs. In a way, this explains the ≈ 0.1 µs phase shift in the image which I’ll repeat again here:


As you can see, the 500 KHz sine wave takes about 200 ns to rise 1 division, i.e. 0.5V, so it’s definitely nearing the limit of this op-amp. Let’s push it a bit with 1 and 2 MHz sine waves:



Whoa! As you can see, the output cannot quite reproduce a 1 MHz input signal faithfully (there’s an odd little ripple), let alone 2 MHz in the second screen, which starts to diverge badly in both shape and amplitude. The vertical scale is 0.5V per division.

Sine waves are “pure frequencies” – in a vague manner of speaking. It’s the natural way for things to oscillate (not just electrical signals, sine waves are everywhere!). The field of Fourier analysis is based on one of the great mathematical discoveries that all repetitive signals (or motions) can be re-interpreted as the sum of sines and cosines with different amplitudes and frequencies.

You don’t have to dive into the math to benefit from this. Most modern oscilloscopes support an FFT mode, an amazing computed transformation which decomposes a repetitive signal into those sine waves. One of the simplest uses of FFT is to get a feel for how “pure” signals are, i.e. how close to a pure sine wave.

Unfortunately, I have too many FFT scope shots for one post, so tomorrow I’ll post the rest and finish this little diversion into signal analysis. It’ll allow us to compare the above three signals in a more quantitative way.

Power booster

In Hardware on Dec 6, 2012 at 00:01

The trouble with the Arbitrary Waveform Generator I use, is that it has a fairly limited output drive capability. I thought it was broken, and returned it to TTi, but they tested it and couldn’t find any problem. It’ll drive a 50 Ω load, but my habit of raising the signal to stay above 0V (for single-supply uses) probably pushed it too far via that extra DC offset.

I’d like to use a slow ramp as sort of a controllable power supply for JeeNodes and the AA Power Board to find out how they behave with varying input voltages. A simple sawtooth running from 0.5V to 4V would be very convenient – as long as it can drive 50 mA or so.

Here’s one way to do it:

Volt follower

This is an op-amp, connected in such a way that the output will follow exactly what the input is doing – hence the name buffer amplifier or “voltage follower”.

Quick summary of how it works – an op-amp always increases its output when “+” is above “-”, and vice versa. So whatever the output is right now, if you raise the “+” pin, the output will go up, until the “-” pin is at the same value.

It seems pointless, but the other property of an op-amp, is that the input impedance of its inputs is very high. In other words: it draws nearly no current. The input load is negligible.

The output current is determined by the limits of the op-amp. And the AD8532 from Analog Devices can drive up to 250 mA – pretty nice for a low-power supply, in fact!

Here’s the experimental setup (only one of the two op-amps is being used here):

DSC 4273

Here you can see that the input voltage is exactly the same as the output:


(yellow = input signal, blue = output signal, a 500 KHz sine wave between 1V and 3V)

Well, almost…

As you can see, there’s a phase shift. It’s not really a big deal – keep in mind that the signal used here is a high-frequency wave, and that shift is in fact less than 0.1 µs. Irrelevant for a power supply with a slow ramp.

Tomorrow I’ll bombard you with scope shots, to illustrate how this op-amp based voltage follower behaves when gradually pushed beyond its capabilities. Nasty stuff…

Keep in mind that the point of this whole setup is to drive more current than the function generator can provide. As a test, I connected a 100 Ω resistor over the output, and sure enough nothing changes. The AD8532 will simply drive the 10..30 mA through the resistor and still maintain its output voltage.

The beauty of op-amps is that all this just works!

But there is a slight problem: the AD8532 can drive up to 250 mA, but it’s not short-circuit proof. If we ever draw over 250 mA, we’ll probably damage it. The solution is simple, once you think about how op-amps really work (from the datasheet):

Screen Shot 2012 11 24 at 20 26 21

The extra resistor limits the output current to the safe value, but the side-effect is that the more current you draw, the less “headroom” you end up with: if we draw 100 mA, then that resistor will have a 2V voltage drop, so the maximum output voltage will be 3V when the supply voltage is 5V.

If you look at my experimental setup above, you’ll see a 22 Ω resistor tied to each output.

That’s it. This simple setup should make it possible to explore how simple circuits work with varying supply voltages. A great way to simulate battery limits, I hope!

Watts, Amps, Coulombs

In Hardware on Nov 26, 2012 at 00:01

Sometimes I see some confusion on the web regarding the units to measure power with.

Here’s a little summary, in case you ever find yourself scratching your head with this stuff:

  • Electric potential is sort of a “pressure level” when using the water analogy, expressed in Volts (V)
  • Current is the flow of electrons, and is expressed in Amperes (A)
  • Charge is the “amount of electricity”, and is expressed in Coulombs (C)
  • Power is the product of volts and amperes, and is expressed in Watts (W)

Another measure of power is Volt-Amperes, this is not the same as Watts in the case of alternating current with reactive loads, but let’s not go there for now…

To summarise with the water analogy:

  • Volts = how high has the water been pumped up
  • Amps = how much water is flowing
  • Coulombs = the amount of water
  • Watts = how much energy is being used (or generated)

You can probably guess from this list that pumping water up twice as high (V) takes twice as much energy, and that pumping up twice as much (A) also takes twice as much energy. Hence the formula:

    Watt = Volt * Ampere

Other equations can also help clarify things. They all add time into the mix (in seconds).

Current is “charge per second”:

    Ampere = Coulomb / second

This is also the way I estimate average current consumption when diving into ultra-low power JeeNode stuff: using the oscilloscope to integrate (sum up) all the instantaneous current consumptions over time, I get a certain Coulomb (or micro-coulomb) value. If that’s a periodic peak and the system is powered-down the rest of the time, then the estimate becomes: X µC used per Y sec, hence the average current consumption is X / Y µA. The advantage of working with Coulombs in this way, is that you can add up all the estimates for the different states the system is in and still arrive at an average current level.

Another one: power consumption is the amount of energy consumed over time. This is often expressed in Watt-hour (Wh) or kilowatt-hour (kWh):

  • two 100 W lightbulbs running for 5 hours = 2 x 100 x 5 = 1000 Wh = 1 kWh
  • one LED strip drawing 2 A at 12 V for 3 hours = 2 x 12 x 3 = 72 Wh

And then there’s the “mAh” unit used with batteries, i.e. milli-ampere-hour. Quite simple again, once you get used to this metric system, and realise that you also need the voltage:

  • 2 AA batteries of 1.5V @ 2000 mAh each provide 2 x 1.5 x 2000 = 6000 mWh = 6 Wh
  • a 5 mA load on batteries of 2000 mAh will run for 2000 / 5 = 400 hours

Battery capacities are roughly as follows for the most common types:

  • an AA cell has 2500 mAh @ 1.5V = 3.75 Wh
  • an AA rechargeable cell has 2000 mAh @ 1.2V = 2.4 Wh
  • an AAA cell has 1000 mAh @ 1.5V = 1.5 Wh
  • an AAA rechargeable cell has 800 mAh @ 1.2V = 0.96 Wh
  • a CR2032 coin cell has 200 mAh @ 3V = 0.6 Wh

Wanna be able to run for a week on a coin cell? Better make sure your circuit draws no more than 200 / (24 x 7) = 1.2 mA on average under optimal conditions.

Wanna make it run a year on that same coin cell? Stay under 22 µA average, and it will.

With 2 or 3 AA batteries, you get an order of magnitude more to consume, so if you can get the average under 200..220 µA, those batteries should also last a year (ignoring the fact that batteries always have some self-discharge, that is).

The difference between 2, 3, or 4 AA batteries in series only affects the voltage you get out of them. Chips do not run more efficiently on more voltage – on the contrary, in fact!

For low-power use: run your circuit on as low a voltage as possible, but no lower (wink).

It’s a current source!

In Hardware on Nov 24, 2012 at 00:01

Let me answer yesterday’s question first: “Is this circuit actually useful for anything?”

You bet: this is called a Current source.

The circuit will deliver a constant current by varying the voltage drop, even when the load varies. You can see this in the fairly flat curve on the Component Tester screenshot included yesterday: no matter what level positive voltage you apply to this thing, it’ll draw about 2 mA (just ignore the negative end of the scale).

Actually, I cheated a bit. The real two-transistor current source circuit looks like this:

Curr source

By moving that 10 kΩ resistor away from the load, and tying it directly to “+” the circuit works even better. I’ve simulated it with an external power supply to drive that resistor separately, and get this CT screen:


Totally flat! – And that 2 mA current level is set by the 330 Ω resistor, by the way.

One use for this could be a constant-current LED driver (although its efficiency would be very low – you really need a switching circuit with an inductor to get good efficiency).

So how does this mind-bending circuit actually work?

The key point to note, is that the emitter-to-base junction is essentially a diode (which is probably why transistors are drawn the way they are!). And it has a fixed forward-drop voltage of about 0.65V. As long as the base is less than 0.65V above the emitter voltage, the transistor will be switched off. As soon as the base is raised higher, current will flow through that forward diode and the transistor will start to conduct.

This is also why you always need a current limiting resistor: the base voltage cannot rise above 0.65V, it’ll simply conduct more current. Until the current limits are exceeded and the transistor is destroyed, that is…

First, imagine that the leftmost transistor is absent: then the 10 kΩ will pull up the base of the rightmost transistor and cause it to fully conduct. The circuit now essentially acts as the load in series with the 330 Ω resistor. With a maximum load (a short-circuit), the whole supply voltage will end up across that 330 Ω resistor.


With the leftmost transistor in place, something special happens: as soon as the voltage over the 330 Ω resistor rises above 0.65V, the leftmost transistor will start to conduct, pulling the base of the rightmost transistor down. It will continue to do so until the voltage over the 330 Ω resistor has dropped to 0.65V again. Because at some point the base of the rightmost transistor will be pulled so low that it no longer fully conducts – thus reducing the current through the 330 Ω, and thus lowering the voltage drop across it.

You’re seeing a neat little negative feedback loop in action. These two transistors are going to balance each other out to the point where the 330 Ω resistor ends up having a voltage drop of exactly 0.65V – regardless of what the load is doing!

To get 0.65V over 330 Ω, we need a 0.65/330 = 1.97 mA current.

And so that’s what this circuit will feed to the load. As you can see in that last scope capture, the regulation is extremely good between 0.65 and 9V.

By simply varying the 330 Ω value, we can set any desired fixed current level.

The reason I’m bringing this up, is that this circuit is in fact used in the OpenTherm gateway – see this schematic (look for the upside-down PNP version). With some extra circuitry to set the resistor to either 100 Ω or 28 Ω (100 Ω in parallel with 39 Ω). So the gateway is driving either 7 mA or 25 mA through the thermostat.

Welcome to the magical world of electronics – it’s full of clever little tricks like this!

Mystery circuit

In Hardware on Nov 23, 2012 at 00:01

Here’s a little puzzle for you – what does this circuit do?

DSC 4257

That’s two BC549 NPN transistors and two resistors. Let me draw the schematic:


Better still, here’s what it shows when hooked up to my Component Tester:


Horizontal scale: -10 V .. +10 V, vertical: -10 mA .. +10 mA.

Bonus question: is this circuit actually useful for anything?

High-side switching

In Hardware on Nov 12, 2012 at 00:01

If low-side switching is so troublesome, then why not just flip everything around, right?

High side partial

Not so fast. The I/O pin is tied to a microcontroller running at 3.3 or 5V, so its voltage level will vary between 0 and a few volts. Whereas “+” is more likely to be 5V, 12V, or even 24V.

This means that to keep the PNP transistor switched off, we need to keep the base voltage at nearly the same level as that “+” line. Unfortunately, this is impossible – not only could high voltages on I/O pins of a µC damage them, there is also some protection circuitry on each pin to protect against electrostatic discharge (ESD). If you were to look inside the µC chip, you’d find something like this on each I/O pin:


What that means is that if you try to pull an I/O pin up to over VCC+0.7V, then that topmost diode will start to conduct. This is no problem as long as the current stays under 1 mA or so, but it does mean that the actual voltage of an I/O pin will never be more than 4V (when running on 3.3V). Which means that PNP transistor shown in the first image will always be on, regardless of the I/O pin state.

We’ll need a more complex circuit to implement a practical high-side power-on switch:

Npn pnp

The workhorse, i.e. the real switch, is still the PNP transistor on the right. But now there’s an an extra “stage” in front to isolate the I/O pin from the higher voltages on the base of that PNP transistor. There’s now essentially a low-side switch in front of the PNP.

When I/O is “0″, no current flows into the base of the NPN transistor, which means it won’t conduct, and hence no current flows into the base of the PNP transistor either.

When I/O is “1″, the NPN transistor will conduct and pull its collector towards ground. That leaves a 10 kΩ resistor between almost ground (0.4V) and almost high (“+” – 0.7V), since the base-to-emitter junction of a transistor is more or less a forward-conducting diode. So the base of the PNP transistor is pulled down, and the PNP transistor is switched on. The resistor values are not too critical here – making them both 10 kΩ would also work fine. But they have to be present to limit both base currents.

A similar circuit can be created with two MOSFETs. With the proper choice of MOSFETs, this will in fact be a better option, because it can handle more current and will have less power loss (i.e. heat). The resistors will need to be placed differently.

Note that all circuits can be analysed & explained in the same way, as long as there are no feedback loops: step-by-step, reasoning about the effect of each stage on the next.

Low-side switching

In Hardware on Nov 11, 2012 at 00:01

Yesterday’s post brought up some good comments, which I’d like to expand on a bit.

To summarise, this is about how to switch power to an electric circuit using an I/O pin.

Yesterday’s solution worked for me, but would fail if the voltage range is not as nicely predictable, i.e. trying to control say between 2 and 12V with an I/O pin which supplies 1.8 to 3.3V. In this case, the 0.7V diode drop of the base-to-emitter junction of a transistor won’t always be of much help.

Let’s examine some approaches. First, what is perhaps the most obvious way:

Low side

With a “normal” (BJT) NPN transistor, you feed it some current by making an I/O pin high, and it’ll conduct. There needs to be a resistor in series, large enough to limit the current, but small enough to drive the transistor into saturation (10 kΩ should work for loads up to say 25 mA, you can reduce it to switch more current).

With an N-MOSFET, you pull the gate up, again by setting an I/O pin high. In this case there should be a resistor to pull the gate down until the I/O pin is set up as an output, to prevent power-up glitches. This resistor can be much larger, 1 MΩ or more. MOSFETs need almost no current (“flow”), they just need voltage (“pressure”) to function.

The benefit of these circuits is that you can easily switch 5V, 12V, or even 24V – with an I/O pin which remains at very low voltage levels (say 1.8 to 3.3V)

In a perfect world, these would both be fine, and be very convenient: “1″ is on, “0″ is off.

Unfortunately, a transistor is not a perfect switch, so there will be some residual voltage drop over it (0.2..0.4V for the BJT, under 0.1V for the MOSFET). Also, the selected MOSFET has to switch on at low voltages – many types need 4V or more to fully switch on.

One problem with these “low-side” switches (i.e. in the ground wire), is that the circuits will start to float: with a small voltage drop over the transistor, all signal levels to this circuit will be raised slightly, and sometimes unpredictably. So if the circuit has any other connections to the microcontroller (or anything else, for that matter), then these levels will vary somewhat. It’s like shaking hands with someone while standing on a treadmill :)

What’s even worse: when the power is switched off, the circuit ends up being tied to its power supply “+” side, but disconnected from ground – this can cause all sorts of nasty problems with electricty finding its way through other connected pins.

Having said that: if the circuit to be switched has no other outside connections, then either of these setups will work just fine. One example is LEDs and LED strips – which is why the MOSFET Plug uses N-MOSFETs exactly as outlined here. All you need to do is stick with “Common Anode” type RGB LED’s, i.e. tie all the “+” pins (anodes) together to the power supply, and let the MOSFETs do the switching between the “-” pins (cathodes) and GND.

For anything more elaborate, we need “high-side switching” – coming up tomorrow!

Switching with a lower voltage

In Hardware on Nov 10, 2012 at 00:01

The SMA Bluetooth relay described yesterday has to switch the power to the RN-42 module using an I/O pin on the ATmega. Currents are fairly small: up to about 50 mA.

I tried directly powering the RN42 from two I/O pins in parallel, but it looks like they don’t have enough current drive capacity for this purpose. So the task is to find a simple way to switch on power somehow.

The simplest solution would seem to be a P-MOSFET in the “high side” supply, i.e. between PWR and the RN-42′s supply pin, but there is a problem: PWR will be somewhere between 3.3 and 5V (actually it’s more like between 3.6 and 4.0V with the 3xAA Eneloop batteries I’m using), but the I/O pin on the ATmega won’t be more than 3.3V – since the ATmega sits behind a 3.3V voltage regulator. I tried the P-MOSFET, before realising that it’d always be driven on – the I/O pin voltage is sufficiently low to switch the MOSFET on, even with a logic “1″ – not good!

MOSFETs are driven by voltage whereas transistors are driven by current, so an obvious thing to try next is to use a PNP transistor in more or less the same configuration. Voltage differences wouldn’t be so critical, if no current flows. Also, there’s the extra base-to-emitter voltage drop or so that each normal transistor has. Still, a simple PNP transistor might switch on if the difference in voltage is large enough – this can be overcome with a PNP Darlington transistor, which is simply two PNP transistors, cascaded in a certain way. The property of these things – apart from their high amplification (hFE) – is that you need to drive the base with a slightly larger voltage. A lower voltage in this case, with PNP types. Could also have used two discrete PNP transistors.

Here’s the circuit:

Screen Shot 2012 11 07 at 15 15 47

And sure enough, it works. I happened to have an SMD “BCV 28″ lying around:

DSC 4238

The 10 kΩ resistor in series with the base limits the drive current to under 1 mA – more than enough to drive the Darlington into saturation, i.e. the state where the collector-to-emitter voltage drop is at its lowest.

That’s it. Every 5 minutes, a reading arrives on the central JeeLink, as shown by JeeMon:

Screen Shot 2012 11 07 at 15 21 56

Drat, cloudy again! Oh well, just the usual gray November day…

All about Easy Electrons

In Hardware on Jun 29, 2011 at 00:01

Long-time readers will probably remember the Easy Electrons series of posts on this weblog – as the first post says: “a series which will cover various aspects of electronics from the viewpoint of a technology enthusiast with a non-electronics background.”

There have been 14 posts so far, covering everything from resistors and capacitors, to the basics of power consumption and heat, as well as diodes, transistors, and MOSFETs.

It’s been great fun to write, and the response to it has been absolutely overwhelming. Never did I expect that so many people would enjoy reading about these topics…

I tried to write these posts to convey my intuition on most of the topics covered. There’s a lot of theory out there on electronics, with as much maths and physics as you’re willing to muster, even. But none of that is really needed, if all you want is hook up some circuits with say a few sensors, some display, and a microcontroller such as the JeeNode, Arduino, or chipKIT.

So the point of the Easy Electrons series was really to try and bring across that essential understanding which can help avoid damaging stuff. It should after all be fun…

I say “was”, because I’ve decided to stop writing Easy Electrons installments. First of all, there’s a summer break coming up, but more importantly, I don’t really want to go too deeply into topics which are well covered by other sites on the web.

There are plenty of getting started sites, but the one I’d like to highlight is All About Circuits – it’s a goldmine of information, and it has a very active discussion forum area. Best of all, it’s not aligned to any particular supplier (as far as I can tell), so I would expect the information in it to be generally useful (and much broader and deeper than what I could possibly come up with). There are some ads on the site – to which I’m usually allergic, but they tend to be quite small and unobtrusive, IMO.

There’s bound to be info for everyone. I particularly liked Volume IV of their extensive documentation – filled with interesting experiments, with all the details and background info one could possibly need.

If all you want is to get started in electronics, perhaps because you have a computer software background, then skimming through the first 5 chapters, such as this section on voltage and current, ought to go a long way.

I’m not ruling out new posts which might still get tagged as part of the Easy Electrons series, but don’t wait for full-scale coverage of all electronics aspects one could think of. There’s no point duplicating what others are doing, and doing better and more thoroughly, in fact.

I’m delighted that there are such good resources, freely available to anyone with an internet connection. Would have loved to have had that access as a teenager!

So now I can focus my energy on exploring and blogging about all the new adventures ahead :)

Easy Electrons – Pull Ups and Downs

In Hardware on Feb 13, 2011 at 00:01

Time for another installment of the Easy Electrons series. This one is about the why’s and how’s of pull-up and pull-down resistors.

There are many ways to generate digital output signals. They almost always work with “high” and “low” voltages – for suitable definitions of high and low. As it turns out, there are lots of tricks you can play with this.

The high-end solution is to use a “push-pull” driver with two transistors. Similar to the H-bridge circuit described in an earlier post. By switching either one of the transistors on, you get an output which can carry current in either high or low states (“sourced” to ground, or “drained” from the supply rail, respectively):

Screen Shot 2011 02 12 at 11.32.02

The CTRL A & B pins are set up in such a way that one transistor conducts, and the other blocks. When a PNP/NPN pair is used, tying them both together turns out to work exactly as needed. This is what an Atmega pin does in OUTPUT mode, essentially.

But you don’t really need such a setup in many cases. That upper transistor can also be replaced by a resistor:

Screen Shot 2011 02 12 at 22.40.17

Resistors are cheaper, but more importantly, resistors offer more flexibility. The effect is that when the only remaining lower transistor is conducting, then it draws the signal to ground, and when it is not, then the resistor pulls the now-floating signal to a high level. This works as long as you don’t draw too much current. A common value for such a “pull-up” resistor will be between 1 kΩ and 100 kΩ. In that last case, you can’t put a load of more than a few microamps on the circuit, but again: for signaling purposes that is often just fine.

Why is this useful?

Well, for one, the voltage levels can be different. It’s possible to control a 0..12V digital signal using just one transistor and a pull-up to… 12V. This is also perfect for 3.3V -> 5V conversion, for example, and it even works when the output voltage is lower than the signal input (which goes through a current-limiting resistor anyway).

Another nice property is that you can tie several such outputs together. The output signal will drop to 0 whenever any output is low, and stay at 1 when all the outputs are high. i.e. it acts as an implicit AND-gate. This makes such a circuit suitable for “bussing”, i.e. putting multiple devices on a single signal line. You still need to collaborate between the devices to make sure only one of them talks at any given time, but electrically they can all be tied together with no extra circuitry. An output which is high is in effect not participating in the state of the bus signal.

Third, the single-transistor can still drive larger currents, but only in the “0″ state. So you can still use this to turn on a LED (+ resistor), as long as you tie the LED/resistor combo between output pin and the supply voltage, not between output pin and ground.

And fourth, perhaps not as important as the rest: shorting such an output to ground when it only has an active-low transistor cannot harm the circuit (unlike shorting it to the positive supply rail). All that happens is that the pull-up will be supplying a little bit of current as it ends up getting the full supply voltage.

Note that putting a positive voltage on the transistor base willl cause it to conduct, and than tying something between the output pin and the supply voltage will cause it to get power when the transistor is conducting current from the output pin to ground. So loosely speaking, a “high” input voltage leads to an energized output state, even though the effect is to pull the collector low.

A slight variation is to use one transistor and leave the resitor off altogether. This is called an “open-collector” (OC) output, for obvious reasons. Sometimes, that extra resistor is not needed, i.e. when all you care about is energizing a lamp / motor / LED, or not. Sometimes a pull-up is still required, but then a single one will be sufficient, even with multiple OC outputs tied together. This is a way to reduce the total component count a bit further.

The I2C bus is an example which uses the open-collector output plus pull-up resistor approach, to implement a bus with multiple devices, exchanging information between them in any direction.

On an ATmega, you can enable a pull-up resistor on any pin by setting the pin up as an input pin, while writing a “1″ as if it were still an output pin. The result will activate a weak pull-up resistor of 20..50 kΩ. One side-effect is that the input pin will read as a clear “1″ when nothing else is connected. A pull-up resistor is a bit like slanting the table, i.e. the signal tends to stay in the high state unless a certain amount of current pulls it low.

What about pull-downs?

Technically, all this pull-up trickery can also be done with pull-down resistors and transistors tied between supply and output pin, but it is less comoon to do so. Due to the way transistors work, such a “high-side” switch is easiest to implement with a PNP transistor – and these used to be less common and more expensive. Furthermore, a “high” input signal would now cause no output current to flow. So the sense of operations is inverted. Are these essential reasons to avoid such an approach? No. But the NPN low-side switch approach has become prevalent. It has become second nature to use NPN transistors, and to tie small loads directly between the output pin and the positive supply voltage.

The ATmega has no built-in pull-down mechanism.

Easy Electrons – MOSFETs, part 2

In Hardware on Feb 7, 2011 at 00:01

Yesterday was about MOSFETs and the heat they generate. Pretty impressive, those components which can control a 15A current with just a little bit of voltage.

Unfortunately, it’s not quite as simple as that. We have to check what happens with a lowly 3.3V applied to the gate. This can be found in the IRLZ34N datasheet:

Screen Shot 2011 02 06 at 20.43.00

This is an important graph for MOSFETs. Each line corresponds to a different voltage applied to the gate – this graph is in fact eight graphs in one.

You can see that they really do have some limits at lower voltages. At 3.3V, the IRLZ34N will not go much higher than 7A – quite a bit lower than the 30A maximum specs on the front page of the datasheet. Most MOSFETs are still at the end of their range when driven by a 3.3V microcontroller.

What this graph also shows, is the drain-to-source voltage at different current levels. This makes it very easy to estimate power consumption: at 3V and roughly 5.5A, that voltage will be 1V. In other words: 5.5W – quite manageable if the MOSFET is mounted on a suitable heat sink. But again: quite a bit lower current handling capacity than the 15A from yesterday. Note that we could drive it at a higher voltage by adding an extra stage in front, using either a BJT transistor or a MOSFET to get better current handling capacity.

As you can see, there is a very distinct switch-over point at each gate voltage level, where the MOSFET stops conducting more current. Under the switch-over point MOSFETs act essentially like a pure (low-value) resitor, but above that point they start acting more like a current limiter. This has major implications for power consumption, since the drain-to-source voltage will rise.

With this particular IRLZ34N, driving it at 3.3V, it is best not to push it beyond about 5..6A, and to use a heat sink when power consumption rises above say 1W (i.e. at 62°C/W, that makes the bare MOSFET rise 62° above ambient). Looking at the 3V line in the graph, I’d estimate that this MOSFET would work just fine without heat sink up to at least 2A, perhaps even 3A.

But what if we want to regulate the current? I.e. what if we want to use the MOSFET in an analog manner, and not just as on-off switch?

We could lower the gate voltage somehow, to force the current down. It won’t be a linear relationship, and I’m not even sure a MOSFET will conduct any current at all when the gate voltage is lower than 1 or 2V.

But in general, it’s a bad idea. The reason is (again!) power consumption. Say we use the following circuit:

Screen Shot 2011 02 06 at 22.17.58

(the resistor is a pull-down, explained in a future post)

That’s a 12W incandescent light bulb, powered by 12V, and controlled by a MOSFET, in other words: it draws 1A when full on. Let’s say we want to dim the light by halving the current through it. The lamp acts like a resistor (it just get pushed so hot that it starts glowing, that’s all). So half the current is what you get when you apply half the voltage to it. In this case 6V.

Suppose we figured out exactly what gate voltage to apply to get a drain-to-source voltage over the MOSFET of 6V. That would essentially accomplish our goal: the lamp would be dimmed. Another way to look at this, is that we’re tweaking the gate voltage until the MOSFET acts like a 12 Ω resistor between drain and source. Then the lamp and the MOSFET both get half the voltage.

What about power? Well, the MOSFET will have to have 6V across it, as we just saw. At 0.5A, this means that it will have to burn 6 (V) x 0.5 (A) = 3 Watts of power.

This is totally counter-intuitive: when we switch a lamp full on, the MOSFET will consume less than 0.1 W (as gleaned from the graph), but to dim it, that same MOSFET would need a heat sink!

There is some logic in this, though, if you think about it. The 12V supply voltage is a given. So if we want to apply less voltage to the lamp, we have no other choice but to waste the excess energy. Which is exactly what the MOSFET (or BJT transistor for that matter) will do. So although we’re reducing the total power consumption in this circuit by halving the current, we’re forced to do so by wasting power – as non-visible light, i.e. heat.

Can we do better? Yes, fortunately, we can.

This is where “pulse-width modulation” (PWM) comes in. Instead of eating up the excess power, we can take advantage of the fact that incandescent lights are fairly sluggish in their response. What we do is pulse the power on and of in very rapid succession. So the lamp will constantly heat up and cool down, and the result is that it won’t be burning at full brightness.

Why is PWM so incredibly useful? Several reasons:

  • we don’t need a way to generate a regulated analog gate voltage, we can simply generate digital on-off pulses with no extra circuitry needed
  • the MOSFET is again being used as pure on-off switch, and remains maximally efficient – so we probably won’t need a heat sink
  • power is no longer wasted, it is now effectively throttled instead – in very short and rapid bursts

It turns out that PWM works in a lot more cases than just incandescent light bulbs. DC motors are also sluggish, so controlling their speed with PWM also works extremely well. And better still, even LEDs work well with PWM, even though they respond instantly – because it turns out that our own vision is sluggish too!

See also an earlier post about PWM on this daily weblog.

So there you go. MOSFETs are the workhorses of power control, due to their incredible properties, and PWM is the technique of choice when it comes to throttling power devices (lights, heaters, motors, and more).

Easy Electrons – MOSFETs (and heat)

In Hardware on Feb 6, 2011 at 00:01

To continue this Easy Electrons series, this time I will go a little bit into MOSFETs.

To me, MOSFETs rank high up there, next to operational amplifiers as one of the foundation components in electronic circuits which are extremely useful and practical. The most amazing detail is that MOSFETs only exist since a few decades – newbies when you consider the time scale of most electrical components.

In a way, a MOSFET is like a BJT transistor. Even the symbol for it looks similar (from Wikipedia):

80px Igfet n ch enh Labelled.svg

This “N-channel enhanced MOSFET” type is the most common one, and like the NPN transistor, current flows into the top (D = drain) and comes out the bottom (S = source), all controlled by a third pin (G = gate).

One key difference between a BJT transistor and a MOSFET, is that a BJT is driven by current, whereas a MOSFET is driven by voltage. You feed a (small) current into a transistor to make it conduct, whereas you apply a (small) voltage potential to make a MOSFET conduct. The gate of the MOSFET doesn’t conduct current – it just senses the voltage. Bit like a capacitor.

You could say that a transistor is like a water wheel: you have to keep churning the crank to keep the water flowing through it. Whereas a MOSFET is more like a flexible tube: you pinch (well, “un-pinch”) to control the flow, but that pinch doesn’t consume energy. You could use a small mechanical clamp to maintain the pressure and keep the flow going.

This also explains why a transistor won’t conduct if the base is left unconnected (no current coming in), whereas a MOSFET could be doing anything when its gate is left unconnected, depending on how much charge was left when last connected. Early MOSFETs were in fact incredibly sensitive to static electricity – just touching the gate with a finger would often destroy a MOSFET. Nowadays, they are ESD protected.

MOSFETs are perfect for controlling large currents via a microcontroller. Even the weakest output pins can drive them, as long as the voltage is high enough. In the past, MOSFET’s needed at leat 4.5 to 5V to make them conduct, but nowadays voltages in the 2.5..3V range are sufficient in these so-called “logic-level” MOSFETs.

I’ll take the MOSFET Plug as example. It has two MOSFETs tied directly to two ATmega output pins:

Screen Shot 2011 02 05 at 13.35.58

Let’s look at a manufacturer’s datasheet for that “IRLZ34N” MOSFET, because there’s a lot of useful information in there.

The IRLZ34N datasheet is a great example. Seven pages, full of details, facts, graphs, circuits, pinouts, drawings, etc. It’s worth getting used to reading datasheets. They are loaded with info. To me, datasheets are the user interface of electronics. Give me a part number, and I’ll grab the datasheet to understand what it can do.

Here’s the first part:

Screen Shot 2011 02 05 at 13.42.00

  • logic level – aha! it can probably work with 3.3V
  • VDSS – that must be the max switching voltage, 55V .. plenty!
  • RDS(on) – will come to that in a minute
  • ID – max current through the drain, a whopping 30 amps
  • 175°C – looks like it can witstand scorching hot temperatures

Ok, there’s your helicopter view of this component. What I’m interested in is: will it be able to switch my <insert-some-high-power-device-here> ?

Well, we’ve seen the max voltage and current specs. But what really matters is power consumption. Because that’s the heat that gets generated, and that’s usually what breaks things.

Power is voltage x current (E x I). The voltage in this case is the voltage across the MOSFET. But we don’t know that – not directly. What we do know is its “RDS(on)” – this is the resistance between drain and source when turned on. Heh, how obvious. And exactly the value we want. It’s a mere 0.035 Ω.

Ohm’s law says V = I x R, so the voltage across the device is the current through it times its resitance.

Combine these two and we get P = E x I = (I x R) x I = I x I x R. Power consumption is proportional to the square of the current. Aha – that explains why large currents can be so destructive!

Let’s try this. Let’s go all out and push 30 amps of current through the MOSFET. Its power consumption will be 30 x 30 x 0.035 = 31.5 Watt. That’s a fair bit of heat (small lightbulb).

But will it work?

To find out, we need to do a thermal calculation. What’s going to happen to those 31.5 Watt of power? Well, they will come out as heat, but how much heat?

Time to look at another bit of info on the datasheet:

Screen Shot 2011 02 05 at 13.57.09

Let’s take the last value first: R(theta)JA, or Junction-to-Ambient thermal resistance = 62°C/W. In other words, each watt of power at the junction (i.e. inside the MOSFET package) will leed to a whopping 62°C temperature rise when the component is suspended in “ambient”, i.e. free, air.

Hmmm: 31.5 x 62 = nearly 2000°C. Yikes, our MOSFET is going to evaporate!

What we need to do is mount this part on a massive heat sink to make sure those temperatures are never reached, by drawing the heat away and keeping the MOSFET (relatively) cool.

Fortunately, there are two other values. The way these work, is that they tell you how much “heat resistance” there is when it flows away from the junction where all the heat is being generated. And it’s really easy to work with:

  1. draw a picture of the MOSFET and how it’s mounted
  2. find out the heat resistance in each step
  3. add them up to get a combined °C/W value
  4. re-calculate 31.5 x <that-value>
  5. make sure it stays under the max temp you want stay under (175°C would be too hot for a plastic case, for example – or even for a printed circuit board)

I’ll use a quick example, just to see how far we can push our MOSFET. Let’s assume the MOSFET is mounted on a (very good) heat sink which has only 5°C/W. Then we add up: 2.2 (junction to case) + 0.5 (case to heat sink) + 5 (heat sink to air) = 8.7°C/w.

With 30A current, we get 30 x 8.7 = 261°C. Whoops, can’t be sustained without damage.

Ok, let’s aim a bit lower: 15 amps. Now the power consumption becomes: 15 x 15 x 0.035 = 7.9 Watt. Without heat sink: 7.9 x 62 = 490°C – still way too hot, but with heat sink we get 7.9 x 8.7 = 69°C.

This value is a relative value. It means 69°C above the ambient temparature. So in a 25°C room, the whole thing would become 94°C. Still very hot, but not a problem for the MOSFET!

In other words: take a MOSFET, mount it on a big heat sink, and you can see how a tiny little microcontroller could control a 15A light or a motor which has a 15A peak current. That’s what makes MOSFETS so magical…

Careful with heat sinks, though. To get it right, you really have to include all the paths to “ambient”. If you mount the heat sink in a big box (which can withstand 94°C), then the temperature inside will rise. And those 69°C we calculated will make the whole setup rise accordingly! – it doesn’t take much to get a “thermal runaway”: core heats up, ambient heats up, core heats up further, etc. Until disaster strikes. Not quite Tchernobyl, but hey… be careful.

Soooo… what started out as a MOSFET introduction, has turned into a power and heat calculation. As you can see, it’s not very complex. It’s not a bad idea to find out up front whether a power circuit will self-destruct or not. Now just add a 2x safety margin, and you should be OK. Or better still: build the circuit, and confirm that the results match these predictions, especially under stress and near design limits.

Ehm… I’ve swept a little detail under the rug:

Screen Shot 2011 02 05 at 14.22.04

These calculations assume that we’re driving the gate to 10V, but we’ll only be applying a feeble 3.3V or so. Whoopsy daisy. Let’s go into that tomorrow.

SMD lab supplies

In Hardware on Feb 1, 2011 at 00:01

With SMD becoming more and more common, I really wanted to get a supply of different resistor values – a bit like this binder with through-hole components:

Dsc 2443

So I decided to get 100 of each of the E12 series, thus named because it has 12 values per order of magnitude – spread out in a logarithmic scale: 10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82.

Here are all the values from 1 Ω to 10 MΩ:

Dsc 2439

Nothing fancy, but pretty low cost. And as a bonus: 0 Ω resistors! Don’t laugh, these can actually be quite handy as bridges over other traces. You could even use a single-sided PCB by adding a couple of these as “wire jumpers”!

Here’s the final result, as stored in the lab. I keep a set of 100 Ω, 1 kΩ, 10 kΩ, and 100 kΩ around for quick-and dirty uses, but this way all the usual values are available when I need ‘em:

Dsc 2442

Each drawer has 3 compartments, with two values of the E12 series in each. So that’s two drawers per order-of-magnitude (“decade”), times 7, plus the extra 0 Ω and 10 MΩ. All that’s left, is to add a couple of labels on the drawers to quickly pick the right one.

Ready to do lots more experiments here at JeeLabs! :)

Easy Electrons – Transistor circuits #3

In Hardware on Jan 24, 2011 at 00:01

A third installement about transistors in this Easy Electrons series.

So far, I’ve shown how to get more current out of an I/O pin from an ATmega, since this will probably be the most common reason to use transistors in combination with a micro-controller. But these circuits all act as switches, i.e. they turn current on and off (or in the case of the voltage regulator: adjusting current flow to a certain value).

What if we wanted to control one or two DC motors for a little robot? Lots of fun stuff to do in that area, especially with wireless communication. To do this, we also need to be able to reverse the voltage placed on the motor, so we can make it turn forward or backward under software control. And if we want to make it a bit fancier, it would be nice if we could control the speed of the motor as well.

First things first. Reversing the direction of a motor can be done with a double-pole double-throw (DPDT) relay:

This low-tech solution will switch the +12V and the -12V poles to make the motor run clockwise or counter-clockwise. And if we were to use a transistor for the -12V (i.e. GND) side, we could also turn it on and off.

But that’s clunky! – let’s see if we can do differently. What we need is a way to place either a high or a low voltage on either side of the motor. Here’s a first (flawed!) attempt:

Look what happens when we put the proper voltages on A, B, C, and D:

  • with A high and B low, the left side of the motor is tied to “+”
  • with D low and C high, the right side of the motor is tied to “-”
  • it will start running

And now the other case:

  • with A low, B high, the left side of the motor is tied to “-”
  • with D high, C low, the right side of the motor is tied to “+”
  • it will start running in the opposite direction

And of course, when A = B = C = D = low, the motor will stop.

What the two transistors “on top” of each other do, is create sort of a push-pull circuit, since you can tie the central connection to either the “+” or the “-” voltage rail. This type of circuit is called an H bridge, due to it’s shape.

(note that I’ve left out 4 protection diodes, i.e. one across each C-E junction – they do need to be added in a real-world setup with DC motors)

There are several serious problems with this particular design, though:

  • to pull A or D high, we have to apply 12V, since 3.3V won’t be high enough to raise the base 0.7V above the emitter voltage level
  • if we pull A and B high, then we’ve got ourselves a short-circuit, with huge currents through both transistors on the left!
  • same for C and D…
  • and lastly, this thing needs a whopping 4 I/O pins

Let’s tackle that last point first: we can halve the I/O pin count by tying A and C together, and by tying B and D together. Now three out of the possible combinations will get us just what we want: stop, turn clockwise, turn counter-clockwise. But with both signals high, we still get a short circuit. Not good – we don’t want a software error to be able to start a fire…

The bigger problem though, electrically speaking, is that the input voltages involved are no longer suitable for an ATmega. This can be solved by adding an extra NPN transistor on both sides, for a total of 6 transistors. Instead of explaining the whole setup in detail, let me point you to some articles I found on the web:

  • this one describes the basic idea using relays
  • this page uses 6 transistors (lots more interesting pages on that site)

As you can see, it takes quite a few components to drive one small motor. Fortunately there are lots of H-bridge driver IC’s with various voltage- and current ratings. Some of these are quite small – such as the TC4424A I used on the DC motor plug, which is why I was able to actually put 2 of them on a single plug.

The second task we’d like to be able to do is control the motor speed.

This turns out to be fairly easy. The trick is to use pulse-width modulation (PWM). This is just a fancy term for a simple concept: we generate a set of pulses, and we control the on-time vs. off-time ratio of these pulses. As it turns out, DC motors are far too slow to follow these pulse trains if you generate them at 100 Hz or more. Instead, they will tend to average out the 0/1 values sent to them. And sure enough, a pulse train which is 100% off will cause the motor to stop, and a pulse train which is 100% on will cause the motor to run at full speed. Everything in between will lead to a motor running at intermediate speeds – simple!

For completeness’ sake, let me mention that the on-off power control circuits I’ve been describing in these last posts often use MOSFETs nowadays, instead of the traditional BJT transistors. For simple experiments and small DC motors, BJT’s are fine though.

Now if you think transistors are so great… wait ’till you see what MOSFETs can do!

I’ll go into those next week. Enough electronics for now.

Easy Electrons – Transistor circuits #2

In Hardware on Jan 23, 2011 at 00:01

Today, a second example of a transistor circuit. As announced yesterday, this one is about boosting the output current further…

With a transistor which amplifies current say 100 times, there are still limits to what you can control from an ATmega I/O pin: 10 mA x 100 = 1A. What if you want to drive a DC motor with a stall current well above that?

Quite simple, really: use two transistors “in series”. But how?

Note that this is not the way to do it:

Screen Shot 2011 01 22 at 23.13.37

On first sight, it looks exactly like what we need: after all, when the inout voltage rises above 2x 0.7V, both transistors will start to conduct, right? And since each of them can amplify their input current by 100, that means we could control a current which is a whopping 10,000x as large as the input current! So with the proper high-power transistors, this ought to work, right?

There is a sneaky problem, though. Keep in mind that the base voltage is always capped to at most 0.7V above the emitter, since the B-E junction is like a diode. So when the first transistor starts conducting, it’ll drive the second base up. Up to 0.7V, in fact. And that’s where things go wrong: the first transistor will drive 100x its base current into the second base. With 10 mA, that might well end up being around 1A. But most transistors can’t handle that: they expect small base currents to drive large collector currents. Another way to explain the problem, is that the C-E junction of the first transistor will always be 12 – 0.7 = 11.3V, so with a large current, it’s bound to overheat.

What we need, is a way to limit the current into the second transistor. Here are two ways to do it:

Screen Shot 2011 01 22 at 23.22.24

Both should work. The former is like a double amplification stage, whereas the latter uses the voltage follower approach described yesterday. I don’t really know which one would be better, because I’ve never tried either one.

That’s because there is also another circuit called the Darlington transistor, named after the person who invented it, Sydney Darlington:

150px Darlington Configuration.svg

The difference is subtle but important: the collector of the first transistor is no longer tied to the positive power supply rail, but to the collector, i.e. the lower side of the load.

The practical advantage of this combination, is that it’s still a 3-pin device, so you can use it wherever a transistor is being used, and that’s indeed it’s main raison d’être. Roughly speaking, a Darlington transistor acts like a transistor with a much higher current gain than a single transistor.

Its main drawback is that the saturation voltage, i.e. the voltage over the (combined) C-E junction, is higher than with a regular transistor – i.e. more like 1.1V than 0.4V. This is the voltage you get when driving the transistor all out – and it affects the amount of power absorbed by the transistor (P = E * I). So although a Darlington can switch higher currents from an I/O pin, it also generates roughly three times as much heat.

The reason I’m going into Darlingtons, is that they are very convenient and widely used. There is a 18-pin chip with 8 Darlingtons, tied into a tiny package, the ULN2803:

Uln 2803

This is what I used on the Output Plug, by the way. Not only does each pin drive 500 mA at up to 50V, you can actually tie them together to control larger currents. Each Darlington on this chip includes the necessary resistors, so it’s simply a matter of tying an I/O pin to its input, and it will “sink” up to 500 mA to ground.

An extra benefit of the ULN2803 is that it has a built-in reverse kickback protection diode, as needed when hooking up relays and motors. So that’s 8 more components saved, all by using this single chip.

Don’t get you’re hopes up too high, though. When driven from a 3.3V input, the output current of the ULN2803 might not go much higher than 300..350 mA on each pin. The components on the chip seem to have been designed for 5V. But it does work fine at 3.3V!

To summarize: the Darlington transistor pair is an easy way to get just a little bit more current (or more accurately: a higher gain) than from a single transistor.

So much for switching current on and off. Tomorrow, as last part of this mini-series, I’ll describe how to reverse the current as well, so we can also control the direction of a DC motor. And how we can control their speed. All with just a bunch of transistors.

Easy Electrons – Transistor circuits

In Hardware on Jan 22, 2011 at 00:01

With the basics and some real-world details out of the way, it’s time to start looking at some other circuits with transistors.

I’m going to describe three different types of circuits, to give you a feel for transistors – while noting that I’m just scratching the surface w.r.t. these amazing devices:

  • regulated power supply
  • more current with chained transistors
  • push-pull drivers

There’s way too much to say about this. Let’s get’s going!

Regulated power supply

In the post about diodes, I described a circuit based on a zener diode. One problem with that circuit was that it only worked for a few milliamps of current, the other was that this current was being drawn even under no load.

With a transistor, we can fix both problems at once:

Screen Shot 2011 01 21 at 23.48.09

Well, we’re not changing the fixed current draw really. But we can use a higher resistor value to draw less current, since only a little bit will will be needed to feed the transistor base.

So what’s going on here? Well, remember that the B-E junction is essentially a diode, connected in the forward direction. So from base to emitter, we have a 0.7 volt drop. Since the zener keeps the voltage fixed, the output voltage will be 0.7V below the zener breakdown voltage: i.e. 4 – 0.7 = 3.3V, tada!

The neat thing is that this is basically all there is to it!

The output voltage doesn’t really depend on the load current. With an amplification factor of 100, with a very light 1 mA load, the transistor will need to draw 10 µA on its base to generate that amount of current. It may seem like it does this as if by magic, “seeking” the proper settings all by itself. Let me try to describe what happens anyway. What we’re doing is keeping the base voltage at a fixed level. Here’s what happens when things start up, i.e. when the emitter is still at zero volts, right after turning on the power:

  • the base will then be at 0.7V, because it’s always 0.7V above the emitter level
  • this is much lower than the zener voltage
  • so all the current through R1 goes into the base
  • the transistor will amplify this and start conducting
  • that will “pull” the emitter voltage up, since the collector is tied to the input voltage
  • this in turn means that the load will be supplied with power
  • assuming the load is not a short circuit, the voltage on the emitter will rise
  • so will the base voltage – by 0.7V more, as always
  • at some point, the base reaches the zener voltage
  • that’s when current will start going into the zener
  • meaning: less current into the transistor base
  • where does it end? simple: when the emitter is precisely at 0.7V under the zener voltage
  • this adjustment process takes place continuously, so when the load current changes, the transistor will keep on adjusting its current to keep the base at the zener voltage
  • similarly, this will keep the emitter voltage at a fixed level even when the input voltage changes, since the voltage at the base remains the same

Voilá, a regulated power supply with a constant voltage output, a.k.a. a linear voltage regulator.

This voltage regulator will work fine for fairly large currents. After all, if we have a 10 mA current through R1, then a transistor with hFE 100 will be able to amplify this up to 1A.

But there is a catch: power consumption – again!

Note that the collector is held at the input voltage, and let’s assume this is fixed at 5V. And the emitter is held fixed too, at 3.3V in this example. So we have 1.7V on the C-E junction, with all the load current going through it. With a 1A current draw, that’s 1.7 watt of power. Not huge, but already well beyond what a little transistor can handle. This is why such circuits need to use power transistors and large heat sinks.

It gets worse with higher input voltage. Suppose we connect our setup to 9V instead of 5V. Now the C-E junction will have 5.7V over it, while still drawing 1A = that’s 5.7W of power, i.e. generated heat! So keep in mind, no matter how fancy your regulated supply is: if it works according to this “linear” principle, then it’ll turn all excess voltage into heat. See also an earlier post about this topic.

Our circuit also gives us a new way of looking at a transistor: while regulating, as shown above, it acts like a variable resistor, with the resistance being controlled by the amount of current flowing into the base.

So there you have it, the basic properties of a linear voltage regulator. I don’t want to stray too far from microcontrollers in this Easy Electrons series, but this really is a good example of how unusual transistors can be, compared to resistors and capacitors. Besides, voltage regulation is so common that it’s really useful to understand how it works and to be able to reason a bit about power consumption.

Tomorrow, we’ll go into “Darlingtons”! :)

Easy Electrons – Transistors #2

In Hardware on Jan 20, 2011 at 00:01

Yesterday’s post started off a little mini-series about transistors. Today, I’ll go a bit more into the practical side of things. And in case you’re curious: tomorrow I’ll describe some interesting circuits with’em.

Let’s look at that NPN transistor symbol again:


First thing I want to point out is that there’s essentially a diode between the base and the emitter. The most important property of that, is that when there is current flowing from base to emitter, then there will be an ≈ 0.7V voltage drop across this “B-E junction”.

So yesterday’s calculation was a bit inaccurate. When putting 3.3V on the IN pin, current will flow through the resistor into the base, and from there to the emitter and to ground. Since the base is 0.7V above the emitter, and the emitter is tied to ground, there will be 3.3 – 0.7 = 2.6V over the resistor. Which means that the current through the base will be 2.6 mA, not 3.3 ma as reported yesterday.

With 0V on the IN pin, there is no current, so the voltage between base and emitter is irrelevant (0V in fact).

There was another inaccuracy in yesterday’s post (thx Reinhard), in that the current into the base also comes out the emitter. So with 2.6 mA into the base, and 3.3V current going into the collector, the total current coming out of the emitter is 2.6 + 33 = 35.6 mA (not 33 mA).

We’re not out of the woods yet. Transistors are not perfect conductors. Even when driven all out, there is a small residual voltage from collector to emitter. Usually it’s around 0.4V – this means we can now make much a more accurate calculation:

  • with 3.3V on IN, and 0.7V on the base, there is 2.6 mA into the base
  • with a current amplification factor (hFE) of 100, the collector-to-emittter current might reach 260 mA
  • however, the R2 resistor will limit this
  • with one side of R2 at 3.3V and the other at 0.4V, current through R2 is (3.3 – 0.4) / 100 = 29 mA
  • currents will be: 2.6 mA into the base, 29 mA into the collector, and 2.6 + 29 = 31.6 mA out of the emitter

Now we’re ready for a calculation which is crucial: the amount of power dissipated in the transistor!

It’s really very simple (P = I * E): the base current corresponds to 2.6 mA x 0.7 V = 1.82 mW, and the collector current corresponds to 29 mA x 0.4 V = 11.6 mW, for a total of ≈ 13.4 mW.

How do we know this? Well, if there is a current flowing and a voltage drop, then that’s by definition a form of power consumption. And it can’t turn into anything but heat, really!

Fortunately, 13.4 mW is very little heat, so even the simplest small-signal transistor will be able to handle it. But with larger currents involved, this type of calculation can tell you whether the circuit will: 1) work, or 2) overheat and fail.

Here’s an example to illustrate the point of such calculations – suppose you want to turn a motor on or off, controlled from an ATmega I/O pin:

Screen Shot 2011 01 19 at 23.45.31

(I’ll explain the “kickback” protection diode some other time – it just blocks, mostly)

We know that an ATmega can’t supply more than a few milliamps. Let’s assume it can output 10 mA, and that when doing so the output pin voltage drops to 2.5V – what value do we need for the R1 resistor? And what type of transistor would we need?

Clearly it depends on the motor. Let’s assume it’s a fairly small motor driven from a 12V power supply. What we need to make sure is that the circuit won’t break down. The worst case is when the motor “stalls” and then starts drawing a large current – that’s when something prevents it from turning while power is being applied. Don’t be surprised to see stall currents of several amps, even for small motors which only draw a few hundred milliamps under light load conditions!

Ok, now let’s figure out how much of a motor current we could handle with the circuit shown above:

  • to get max current output, we’ll feed as much current into the base as we can, i.e. 10 mA
  • so we’re feeding 2.5V, and the base is 0.7V, meaning that R1 needs to be (2.5V – 0.7V) / 10 mA = 180 Ω
  • let’s assume we get a transistor with an amplification factor of 100
  • IOW, it can only produce 100 x 10 mA = 1 A current

If we have a motor with a stall current larger than 1 amp, then something nasty will happen: the voltage between collector and emitter will rise above the 0.4V saturation voltage that you get when driving a transistor all out.

So what’s the problem? Heat!

We’ve got 12V on the one side of the motor. Say it has a 2A stall current. The transistor only amplifies its base current to let 1A through. What happens, is that the collector voltage will rise – my hunch is that it will reach about 8V (4V over the motor and 8V over the transistor, matching the 2:1 current ratio).

Now we’re in big trouble. The transistor is conducting 1A with a 8V voltage drop. That’s eight watt of power consumption, i.e. heat. If you take a simple little transistor which isn’t designed for that sort of heat dissipation, then it’ll heat up and go up in smoke. Fireworks!

Note how the lack of output current is what caused this. If the transistor had been able to deliver those 2A, then it’s power consumption would be “only” 2A x 0.4V = 0.8 watt – one tenth of what happened here.

As you might expect, there are several solutions around this. I won’t go into them here, though – I just wanted to go through these calculations to show you that you can’t drive everything directly from an ATmega I/O pin.

Tomorrow, some real circuits!

Easy Electrons – Transistors

In Hardware on Jan 19, 2011 at 00:01

Another installment of the Easy Electrons series. This time I’m going to follow up on the diode post, and go into transistors.

Transistors. Phew. Biiig topic!

There are several types of transistors. The most common one is the BJT. There are two variants, which are schematically drawn like this (from that same Wikipedia page):

Screen Shot 2011 01 18 at 23.32.33

A transistor has three pins, called Base, Collector, and Emitter. Using the convention that current “flows” from “+” to “-”, it’s easy to remember which in an NPN transistor (the most common variant):

  • the collector, eh, “collects” current – IOW, this is where current flows into the transistor
  • the emitter is where the current flows out again, to ground at some point
  • the base is the main control which determines what the transistor does

So what does it do?

One way to look at it, is as a current amplifier: put 1 mA into the base, and the current from C to E will be a multiple of that – anywhere between 50 and 500 times depending on the particular model, i.e. 50 .. 500 mA!

Note that I’m not suggesting that a transistor generates current. Only that when a voltage is applied between C and E, then the current flowing will be a multiple of the “control current” fed into the base.

Things are not quite that simple, though. How do you “put a current” into a component? You can’t just put a voltage on all the pins… before you know it, the current might easily exceed some allowed maximum rating! Transistors have pretty rigid limitations. When you exceed them, they can easily overheat and get damaged.

We don’t really have an easy way to control current, but what we can do is turn ATmega I/O pins on and off, i.e. control the output voltage on those pins. It’s relatively easy to turn that into current though – Ohm’s law: use some resistors!

Here’s a simple circuit to let us explore this behavior:

Screen Shot 2011 01 19 at 00.21.58

The input pin can be fed a voltage, and the R1 resistor will make sure that the current flowing into the base of the transistor will be limited. Likewise, R2 makes sure that no matter how much current the transistor wants to pass from its collector to its emitter, there will be a limit.

How much are these limits? Depends on the voltages and resistor values, of course. Let’s assume the following:

  • the “+” voltage is 3.3V (and GND is 0V, as always)
  • the input pin can have voltages between 0 and 3.3V applied to it
  • resistor R1 is 1000 Ω
  • resistor R2 is 100 Ω

The maximum current flowing into the base will never be more than when IN = 3.3V, i.e. 3.3V over 1000 Ω = 3.3 mA (using “I = E / R”).

The maximum current flowing from collector to emitter is what you’d get if the transistor were a complete short circuit between C and E, i.e. 3.3V over 100 Ω = 33 mA.

Note how I’ve made all sorts of worst-case assumptions about the transistor. In fact, I’ve calculated these values as if B, C, and E were all shorted together, and hence tied to ground (since E is tied to ground).

A real transistor behaves somewhat differently. But no matter how it actually behaves, I know that no more than 3.3 mA will be flowing into the base, and not more than 33 mA will be flowing into the collector and out of the emitter. Just about any NPN transistor can handle that.

Here’s what happens when IN is 0V (i.e. GND):

  • no current will flow into the base
  • since the transistor amplifies the current, no current will flow from C to E
  • if no current flows from C to E, then it’s basically like an open (unconnected) circuit
  • if unconnected, there will be no current flowing through R2
  • with Ohm’s law, the voltage across R2 is (E = I x R) = 0 x 100 = 0
  • so the voltage on the OUT pin will be 3.3V, the same as on the other side of R2

Now, when IN is 3.3V, this is what happens:

  • current will flow through R1
  • lots of current will flow from C to E
  • that’s the same as saying that C and E are more or less shorted
  • that means the OUT pin will now be (close to) 0V

We’ve created a signal inverter: 0V in = 3.3V out and 3.3V in = 0V out!

As I said, big topic. I haven’t even touched on some important details of a “real” transistor.

Stay tuned…

Easy Electrons – Diodes

In Hardware on Jan 9, 2011 at 00:01

It’s time for some Easy Electrons again.

Semiconductors are at the heart of today’s electronics designs: diodes, transistors, and the huge advances made possible by Integrated Circuits (i.e. IC’s) is what makes all those electronic devices around us possible. And it all happened in the time scale of just a few decades…

I can’t possibly cover everything in this series, so I’ll cover the two most common ones for now: the diode today, and the “normal” (BJT) transistor in the next installment.

Very roughly speaking, a diode is a one-way conductor. This is also indicated by the schematic symbol used for diodes (image from Wikipedia):

800px Diode 3d and ckt

The arrow-like symbol points in the direction of the current flow, if you stick with the convention that current flows from “+” to “—”. If you keep forgetting which side is called the Anode and which the Cathode, this trick might help: in the alphabet, we (eh, I mean currents) go from A (to B) to C.

Diodes are useful to protect a circuit against connecting a power source the wrong way around (we’ve all been there, right?):

Screen Shot 2011 01 08 at 22.40.28

With this diode, the circuit is protected. Hooked up the wrong way, the diode will block, so no current will flow through the circuit.

But diodes aren’t perfect. There’s a voltage drop when conducting current, usually around 0.7V. So with the above circuit, if the power supply is 5.0V, then the circuit will only get about 4.3V. With low-voltage components, and especially battery-powered devices, this sort of voltage loss is awkward – and often unacceptable.

Which is why you won’t see this reverse voltage protection very often in circuits operating at 5V, 3.3V, or less. There is another type of protection, however:

Screen Shot 2011 01 08 at 22.40.40

This one is a bit nasty. It doesn’t really prevent the circuit from getting a reversed voltage at all. Instead, it will act (almost) like a short circuit when the voltage is applied the wrong way around. The idea being that this will cause the power supply to shut down (or the battery to drain very quickly). The RBBB uses this type of protection to overcome the voltage drop problem. The (cheap) diode will protect the (much more valuable) ATmega, as well as all other components hooked up to it.

This sort of protection is tricky. If you were to connect a LiPo battery, for example, then the short circuit can cause HUGE currents to flow, since many LiPo’s are able to supply them. Think many Amps… and now something else may happen: even if the diode can handle the current, the rest of the power lines might well become overloaded. Especially thin copper traces on a PCB are likely to act like a fuse and simply… evaporate!

There are other ways to deal with the voltage drop and still end up with diode protection. One of them is to minimize the voltage drop – this is where Schottky diodes can be useful. They usually have only half the voltage drop of normal diodes, i.e. around 0.3V. That might just be low enough for your particular setup.

Another option is to build an “ideal diode”. This might sound like an impossible task, given the properties of diodes, but there is actually a way to do this using a MOSFET. I won’t go into MOSFETs here, but basically they can switch current while having almost no resistance and (Ohm’s law!) therefore also almost no voltage drop. Trouble is: MOSFETs don’t know which way the current is flowing, so you need considerable extra circuitry to tell them when to turn on and off, based on comparing voltages on both ends. And although it is not a simple or cheap solution, this datasheet of the LTC4413 chip shows that it is indeed possible to beat the diode characteristics with some clever engineering. Electronics is often like that: people have come up with the most amazing tricks to overcome certain drawbacks, for all sorts of electronic circuit tasks. That’s why it’s so much fun just exploring and discovering it all, IMO :)

The graph of what a diode does is very characteristic: in reverse mode it blocks, and in forward mode (i.e. above around 0.7V) it conducts, albeit not perfectly. For some good example graphs see this page on Wikipedia (just skip the math formulas and look at the pretty pictures).

Now, assuming the voltage drop is no problem, because you’ve got some extra volts from the power supply anyway, then diodes can be extremely useful. The bridge rectifier for example, can be used to get a properly polarized voltage out, regardless of how the power supply is hooked up. This is particularly useful with alternating current, as present on the AC mains lines and on the coils of a transformer (a lot more Easy Electrons articles will be needed to present all this stuff!).

Another interesting diode is the Zener diode. It’s like a regular diode, but one which can’t support a very high reverse voltage. With Zeners, this voltage is called the “breakdown voltage”, and it ranges from about 2..200V. The value is fixed for any particular model.

Zener diodes make very simple (low-current) regulated power supplies:

Screen Shot 2011 01 08 at 23.03.19

Note how we’re putting the Zener in reverse mode, and counting on it to break down. As it does, current will start to flow. Until enough current is flowing across the resistor (Ohm’s law!) to take up all the “remaining” voltage.

So with a resistor of 100 Ω, and a Zener of 5.0V, we could power it with say 6..9V. At 6V, the current would be (6 – 5) / 100 = 10 mA. At 9V, the current would stabilize at (9 – 5) / 100 = 40 mA.

The reason this can be used as a regulated power supply, is that we can connect our circuit in parallel with the Zener, and it would always get 5V. The only drawback is that we can’t draw more than 10 mA from it:

  • at 6V, the resistor needs to “eat” 1V, so that the Zener ends up with 5V
  • if the circuit draws 10 mA, then 0 mA will go through the Zener
  • if the circuit draws 5 mA, then 5 mA will go through the Zener
  • if the circuit draws 0 mA, then 10 mA will go through the Zener
  • at 9V, the current will increase to 40 mA (to get 4V over the resistor)
  • in all cases, the circuit will see a 5V input voltage

Cool, so now we have built ourselves a simple regulated power supply!

As I mentioned, this circuit is not very powerful. If we draw more than 10 mA, then the voltage drop over the resistor may increase, leaving less than 5V for our circuit.

There is another drawback with the above regulated supply: it’s grossly inefficient. The reason is that it will always draw 10 mA, whether our circuit needs it or not. And that’s at 6V – at 9V it will always draw 40 mA!

I’ll show you how a transistor can easily increase the current and improve the regulating efficiency in a future installment. Exploring these simple electronic circuits can be great fun, and most of the time you can reason your way through without even having to build them!

Next time: transistors – incredibly useful devices, with tons of ways to use ‘em!

PS. Does anyone have tips on how to improve these diagrams? I really want to continue drawing them by hand, but the texts don’t come out very nice, no matter what I try!

LED discharge – measure or simulate

In Hardware on Jan 7, 2011 at 00:01

Yesterday’s post tried to create a new data point for measuring the forward drop voltage over a red LED at a slightly higher current. To summarize:

  • the voltage over the LED was read out as 2.229 V
  • the LED current was calculated to be 10.71 mA

But not so fast. What about component tolerances? What if the 100 Ω resistor isn’t exactly 100 Ω? And what if the supply voltage isn’t exactly 3.3 V?

It turns out that there’s quite a bit more going on here. Time to get the multimeter out and measure these values. If nothing else, this will be useful as cross-check against everything we did so far.

Here’s what I found (expected vs. actually measured):

  • 3.3V power supply = 3.298 V
  • “1″ on VIN = 3.036 V (!)
  • “0″ on VLOW = 0.213 V (!)
  • voltage over LED = 2.011 V
  • 100 Ω resistance = 99.7 Ω
  • current out of VIN = 7.85 mA
  • current into VLOW = 7.72 mA

Whoa – very different outcomes!

First off, this is a Voltcraft VC940 multimeter with 5-digit readout and a specified accuracy on DC voltage and current ranges (substantially) below 1%. For up to 4V, that means it shouldn’t be off by more than 20..30 mV, worst case.

First the good news: the power supply voltage on the 3.3V rail is very close to the desired voltage (3298 mV).

But check out those “1″ and “0″ digital I/O voltages: they are 3036 and 213 mV, respectively, i.e. around 10% off!

There’s a very simple explanation for that, and as it turns out, it’s in fact fully according to specs. Here is the output voltage you get when powering an ATmega at 3V, while drawing some current from one I/O pin:

As you can see, there’s just about a 0.3V drop at 25°C when drawing 10 mA. These I/O pins were not meant to be used as power supplies for other circuits, let alone as reference for analog circuitry.

Another way to put it, is that an I/O pin on an ATmega has an internal resistance of around 30 Ω. It’s easy to see that when we start drawing several milliamps through a 100 Ω resistor, then those “perfect” I/O signal lines are in fact a lot less like a real switched power supply.

The same holds for the “0″ pin voltage levels. Once you start dumping current into such an I/O line, it will start to look more and more like a resistor tied to ground, and not just a direct connection to ground.

So the first conclusion is that the LED isn’t being fed as much current as we had expected, because the voltage levels are not quite 3.3V and 0V.

Let’s recaclulate our results with this new insight:

  • VIN = 3.036 V
  • VHIGH = 2.229 V (same as before, via the ADC)
  • VLOW = 0.213 V
  • voltage over the LED = 2.229 – 0.213 = 2.016 V
  • 99.7 Ω resistor voltage = 3.036 – 2.229 = 0.807 V
  • current through resistor = 0.807 / 99.7 = 8.1 mA

Ah, that’s a lot better: 2.016 V calculated vs. 2.011 V measured, and 8.1 mA calculated vs. 7.85 mA measured (about 3% off, oh well).

One last puzzle: why is the current measured out of VIN not the same as the current into VLOW?

You’ll need to check the schematic again to see what’s going on. Since the VLOW voltage is not 0V as would be the case with a perfect I/O output, there is now also some current flowing from VLOW to GND, through that other 1 kΩ resistor.

How much? Well, Ohm’s law points to the answer, as always: 0.213 V over 1 kΩ means there is 0.21 mA flowing through that resistor. Since the only source of power is VIN, and since all current must flow either into VLOW or GND, this means we can add that 0.21 mA to 7.72 mA to get 7.93 mA total.

Ok, it’s not conclusive in that some unexplained differences still remain, but this is nevertheless a lot closer to the real values in the circuit than the original 2.2V @ 11 mA we arrived at earlier.

Note that we don’t really need a multimeter to be able to make these corrections. I could have tied VIN to another analog input, to be able to use the digital I/O as (imperfect) power supply for the circuit, while at the same time measuring the voltage drop due to the higher current. I’ll leave that as an exercise for the reader.

There’s a lot more to be said about this sort of design and measurement work. Electronics is a very large field, and all we did so far, was hook up 4 simple components!

One very interesting option, is to simulate the circuit instead of building it on a breadboard. There is a well-known application for that called SPICE which takes a circuit description and computes, time step by time step, how the circuit behaves when subjected to certain input signals and power conditions.

JGJ Veken (Joop on the forum & wiki) was very kind to help out with a simulation of the LED discharge circuit I’ve been describing in these weblog posts. Here’s what came out:

Spice led Discharge

The voltage levels are slightly different, because the LED charateristics are different, but you can clearly see more or less the same graph as shown in yesterday’s post. Just to drive tht point home: yesterday’s results were measured in a real circuit, whereas the graph above is a simulation performed 100% inside a computer.

To find out more about this exciting way to try out circuits and explore different parameter settings, see these excellent wiki pages by JGJ Veken: 5Spice and LTSpiceIV. These are two different systems (both with common ancestry), the former commercial but free for personal use, and the latter available from Linear Technology as freeware (I don’t think either of them is open source).

So there you have it. This concludes my mini-series about experimenting with simple components, and using JeeNodes and Arduino’s to investigate the circuit and create a simple test-jig setups for it. Combine that with the SPICE simulation options available out there, and you’ve got a very simple and low-cost way to exlore electronics for yourself. Transistors? Filters? Op-amps? Go for it – there’s a world out there to explore and tinker with!

LED discharge – more measurements

In Hardware on Jan 6, 2011 at 00:01

Following earlier posts about the LED discharge circuit (here, here, and here), let’s do a few more measurements. Here is the schematic again:

I’m going to apply a 1-second charge pulse and then disconnect for 5 seconds, as before. This time, I’m going to disable the pull-up during those 5 seconds, and improve the timing of the reporting so the time to send out characters over the serial port does not affect the whole measurement cycle:

Screen Shot 2011 01 05 at 13.09.50

The reason the timing is so much better in this version, is that it is now based on MilliTimer, which continues to count while the serial port deals with its outgoing data. Note that 20 chars @ 57600 baud takes a few milliseconds, which can quickly add up when reporting values 10x per second.

The values are sent out in a format which can be used directly in a spreadsheet – here are the first few lines of output:

Screen Shot 2011 01 05 at 13.10.55

The values are:

  • voltage measured over the capacitor, i.e. LED + 1 kΩ resistor (Volts)
  • voltage measured over the 1 kΩ resistor (Volts)
  • difference, i.e. voltage measured over the LED (Volts)

Here’s a graph of the resulting measurements:

Screen Shot 2011 01 05 at 12.42.29

Due to Ohm’s law (E = I x R, i.e. I = E / R), that yellow line is also the amount of current going through the resistor in milliamps. Since there is no other path for the current than through the LED, by deduction this is also the current through the LED.

What you can see (blue curve), is that the capacitor charges up within a fraction of a second, and then discharges to under 2V in the next 5 seconds.

What you can also see (yellow curve) is that the current through the LED is proportional to the voltage on the capacitor. As the capacitor charges up, the current increases, and from the shape of the curves is should be clear that the relationship is essentially linear.

This is not surprising, since linear voltage-vs-current curves are inherent to resistive loads, i.e. the 1 kΩ resistor in this case. What is special is the LED placed in series with that resistor. What it does is “eat up” a fixed voltage, i.e. 1.8..1.9 V of the voltage present on the capacitor “stays” in the LED. The rest is passed on to the resistor, which does its usual linear current-to-heat conversion thing (only milliwats of heat in this case – we’re dealing with very small currents and very low voltages here).

But LEDs are not perfect devices. If they were acting like a perfect diode, they would have a fixed voltage drop, regardless of how much current goes through them. You can see from the green line that there is a slight change in voltage drop.

Does that mean a LED has something like a “hidden resistor” inside it? Not really. Here’s a plot over that same data, as current versus voltage:

Screen Shot 2011 01 05 at 12.50.33

That’s not very linear. Remember that resistors just do what Ohm’s law tells them to (or was it the other way around?): twice as much voltage = twice as much current, etc. Which in a graph would show up as a straight line.

In this case, the graph appears to be tapering off. In other words, as more and more current goes through the LED, its forward voltage seems to stabilize around a certain value. Probably around 1.9V, but this will be different for each type of LED.

Note that I placed the current on the horizontal axis, because that’s the variable we can control. The LED “decides” what voltage drop it wants to add.

What seems to be happening in this circuit, is that between 1.75 and 1.80 V there is a small amount of leakage. This is consistent with the video, showing that the LED continues to light up very dimly as the charge leaks away, even though the current is less than 0.25 mA, i.e. 250 µA, at these voltage levels!

Ok. Can we find out more about this forward voltage behavior? Sure. Let’s put 3.3V on VIN and 0V on VLOW, and then measure the voltage on VHIGH:

Screen Shot 2011 01 05 at 13.45.46

(Isn’t it fun to do this stuff under computer control?)

Sample output:

Screen Shot 2011 01 05 at 13.47.05

Whoa, looks like I need to revise my conclusions a bit. The LED forward voltage does go up quite a bit when more current is applied!

Let’s try to figure out how much current is flowing:

  • the cap is fully charged after a few seconds, so we can ignore it
  • therefore the cap voltage will be 2.229 V, as measured by the ATmega
  • and the voltage over the 100 Ω resistor will be 3.3 – 2.229 = 1.071 V
  • the resistor is 100 Ω so with “I = E / R”, we get 1.071 / 100 = 10.7 mA

IOW, at roughly 11 mA, the foward voltage drop of this particular LED is about 2.23V, quite a bit more than the 1.87 V we measured at 1 mA. But still not anywhere near a linear relationship.

Tomorrow, I’ll examine these results a bit more closely … because they aren’t quite right!

Easy Electrons – Need more power

In Hardware on Jan 2, 2011 at 00:01

Welcome to another installment of the Easy Electrons series.

There have been a few posts about What is “power”?, but that was about the electrical concepts of power and energy, and how it relates to voltage and current.

In this post, I’d like to go into a different topic: how to control more powerful electrical devices. As you’ve seen in the LED discharge circuit post, the I/O pins of an ATmega can be used as weak power supply, sort of. This is because an output pin set to “1″ can be used as a 3.3V (5V on Arduino) power source, as long as you don’t draw more than a few milliamperes of current.

Here are the specifications of what a single pin can do, taken from the ATmega datasheet:

Source Datasheet

A few milliamps is not much. Barely enough to light a LED, and far too little to drive even the simplest electric motor. Let alone a light, a heater, or any AC mains appliance.

The first thing to note, is that there are a lot of different ways to control power – and each approach has fairly rigid limitations. You could use a power transistor to drive a bright 12V halogen lamp, but that same transistor would fail (spectacularly and dangerously so) if you tried to use it to control even the smallest AC mains lightbulb. Controlling power is a tricky business. As voltages and currents increase, so do the risks and potential effects of failure.

Let’s start simple, with an LED strip. These strips often need 12V to light up, and use about 300..900 mA per meter. There are several ways to control an LED strip of up to a few meters – using a relay, transistor, or MOSFET, respectively:

Screen Shot 2010 12 29 at 10.20.57

The relay is is the oldest type of power switch, and easiest to understand: an electromagnet closes a switch while powered up. It has been around for centuries. And although I included it as option, in practice even the smallest relays draw more current than what an ATmega I/O pin can supply (apart from very low power reed switches).

The transistor was invented only a few decades ago, and is at the heart of every electronic circuit these days. It’s usually depicted as follows in schematic diagrams (image from Wikipedia):

200px Transistor 2.svg

There’s a lot more to say about this fascinating invention. For now, let me just say that you can feed it a small current and it’ll control a much larger current (and voltage) on another pin.

And then there’s the MOSFET, which is even more recent than the standard bipolar-junction transistor. MOSFETs are pretty incredible: feed it a few microamps, and it can switch a huge amount of current (dozens of amps!). Perfect for direct hook-up to a microcontroller.

So how do we control an LED strip?

Easy – with a MOSFET, for example:

Screen Shot 2010 12 29 at 10.33.02

Note that the LED needs 12V at a fairly high current, whereas something like a JeeNode tolerates 12V – and needs only a few milliamps. In this case, we can get away with connecting both power supply inputs to the same 12V. The built-in voltage regulator will immediately reduce that 12V input to the 3.3V used in the rest of the circuit. So the voltage on the MOSFET “gate” will only be 0V or 3.3V – fortunately, that’s enough for many common MOSFETs these days.

It’s important to note that all these voltages and currents are fairly independent. The following would work just as well, using two separate power supplies:

Screen Shot 2010 12 29 at 10.33.14

I’ve drawn some extra arrows to indicate how the different current paths work. The crucial point is that current always needs to go through a closed loop. If the current “came from” the power supply on the left, then it will also always “return” to that same left-side supply. Think of it as “tagged electricity” if you like: what goes out of a battery on one en must come back on the other end of that same battery. It doesn’t really matter whether you think of electricity as “flowing” from + to –, or electrons flowing from – to +.

Note the connection between “–” on the left and “–” on the right. Without it nothing will work. The reason for this, is that voltages are always relative to some other part of the circuit. You can’t have a voltage (or a current, for that matter) over a single wire. You always need a return path. So in the case of the MOSFET, to drive it and put a voltage on it, you need to connect two wires – even if the current is small, as in this case. That’s why “–” is usually called ground, i.e. the reference against which we measure everything else.

Does this matter? You bet. If the power circuit uses a lot of current, then all its conductors must be able to carry that current: it needs thick wires! – but at the same time, the rest of the circuit can still get by with thin copper traces, as usual on boards like the JeeNode. This means that the ground connections (“–”) may need to be thick on one side, but not on the other – even though all ground connections have to be electrically tied together!

Current flow and proper design of all the wiring and connections is essential in power circuits. It’s a lot more involved than with purely digital circuits, or circuits which carry just milliamps.

How about controlling a lightbulb connected to 220V (or 110V)?

One way is with a relay (designed for such high voltages). But a relay can’t be driven directly from an output pin – so we add a transistor in between:

Screen Shot 2010 12 29 at 10.42.01

The extra resistor and diode are required (for reasons I won’t go into right now).

Note that there is no connection between this circuit and the switch shown at the top which is used to control the lightbulb. That relay does something which is crucial in the case of AC mains: it adds an isolation barrier between the low-voltage (safe!) side of the circuit and the AC mains (potentially lethal!) side of the circuit.

The second common way to control such a lightbulb is a Solid state relay, which uses a built-in opto-isolator to provide the isolation barrier. The advantage of an SSR is that it has no moving parts – hence no mechanical wear.

I’ve only touched briefly on how you can hook up stuff which needs more power than a feeble ATmega output pin can provide. Follow the links above if you want to find out more.

And marvel at the amount of knowledge and understanding Wikipedia brings us, freely available to anyone with an internet connection, anywhere in the world!

LED discharge – PWM and DAC

In Hardware on Dec 30, 2010 at 00:01

In yesterday’s post we saw how a digital signal gets turned into something a lot more gradual, i.e. analog.

The reason for this is what I described as capacitors “dampening change” in an earlier post. This is incredibly useful in the world of Physical Computing. We can do “gradual” things with nothing but 0/1 signals coming out of a microcontroller!

The reason this works, is that capacitors mess around with the time domain. Put a “1″ on them, and they will follow along eventually, i.e. a little while later. And likewise for a “0″ – to bring up a previous diagram again:

This is especially useful with the timer hardware built into an ATmega. You can set up some of the pins to toggle at the rate of a hardware-controlled counter. From the ATmega328 datasheet:

Screen Shot 2010 12 29 at 23.28.11

This is a pin which is set up to generate a pulse repeatedly, and the clever bit is that you can control not just the rate, but also the ratio between on and off times. This is amazingly useful:

  • if the ratio is all the way off, i.e. the pin is permanently “0″, the the voltage on the capacitor in the above circuit will be 0V

  • if the ratio is all the way on (100% on), then the voltage of the capacitor will stabilize to 3.3V if you wait a little while

  • anywhere in between, and the capacitor will be charged while high and discharged while low, and end up being some intermediate voltage between 0 and 3.3V on average

On average: that’s the key. The voltage will still go up and down, but if we choose a high-enough pulse rate, then that variation will be minimal.

This is one useful way of looking at Pulse Width Modulation (PWM): 0 = 0V, 255 (on an 8-bit counter) = 3.3V, and everything in between is N/255 * 3.3V – IOW, we’ve just created a digital-to-analog converter (DAC)!

There are more ways to generate such an adjustable output voltage – see the Bleep! weblog post, for example. But if you just want a slowly adjustable analog voltage, then all it takes is one resistor and one capacitor.

And all it needs on the microcontroller, is one pin which pulses up and down in a specified ratio. The faster it does, the smoother the output voltage. The more accurately the time-off vs time-on ratio is, the more accurately we can set that output voltage. An 8-bit timer will not be able to divide the 3.3V supply voltage into more accurate steps than 0.013V, i.e. 13 millivolt, for example.

It doesn’t really matter how the pulse is generated. There are six pins on an ATmega which can generate pulses with hardware support. This is why the very confusingly-named analogWrite() function in the Arduino library can only be used on 6 specific (digital!) output pins. And it’s not really analog at all, it just becomes analog if you attach a resistor and a capacitor.

The benefit of hardware PWM, as this is called, is that the timer pulses can be made to repeat very quickly (up to some 64,000 times per second). That means a smaller capacitor will often be sufficient, and you can get either a very smooth output voltage or one which can be adjusted rapidly (but never both at the same time).

With software PWM, the pin toggling is done with software loops or timer interrupts. In that case, any output pin can be used. But this incurs a lot more processor overhead, and the pulse rates are far more limited. A while back, I posted a software PWM example to drive some LED strips (the PWM being used for brightness control in this case, even though no caps are involved). That code was almost too slow to avoid visible flickering, although some software tricks can be used to improve the pulse rate a bit.

To be continued, probably about a week from now…

LED discharge – it’s analog!

In Hardware on Dec 29, 2010 at 00:01

The LED discharge circuit presented yesterday can be used for a number of experiments. Yesterday, I asked what this sketch does:

Screen Shot 2010 12 27 at 13.19.46

Here’s what happens:

(Not sure this video will work properly with all browsers – here are MP4 and MOV links)

It’s a little bit of a trick: pin 6 is set to a “1″ digital output (i.e. 3.3V) for one second, and then to an input for 5 seconds. Being an input means it no longer supplies power (or rather: a negligible trickle through the pull-up). So running the sketch is like periodically connecting a 3.3V power supply for one second and then disconnecting it for the next 5 seconds:

Screen Shot 2010 12 27 at 16.25.41

If you look at the circuit schematic again, you can see that pin 6 (i.e. DIO3) is connected to VIN. When it it at 3.3V, it will charge capacitor C1 through resistor R1.

The JP3, JP4, and JP5 pins are not used yet (analog 1 and 2 are inputs). The LED and resistor R2 are powered by the same voltage as what is currently present on the capacitor C1:

  • when pin 6 is high, C1 charges, and the voltage over C1 increases
  • the LED draws some current, and lights up
  • when pin 6 “floats”, C1 discharges, and the voltage over C1 decreases
  • the LED still lights up, but it gets dimmer as the voltage over C1 drops

Here’s a graph of the LED brightness over time, which matches what is shown in the above video:

Screen Shot 2010 12 27 at 16.31.01

There’s a lot of hand-waving in there: can’t actually know excatly what’s going on until we measure it, right?

Let’s start by measuring the voltage over the capacitor C1. Note that the bottom is tied to ground, i.e. it’s 0V by definition. The top side of the capacitor is tied to VHIGH, i.e. analog 2 (AIO3). So all we need to do is measure while waiting for time to pass:

Screen Shot 2010 12 27 at 16.55.46

Sample output:

Screen Shot 2010 12 27 at 16.53.43

Oh, wait. That’s not terribly useful. The analog converter reports values from 0..1023, corresponding to voltages 0..3.3V – so why not convert it to millivolts first? (I prefer to use ints, floating point isn’t very convenient on small 8-bit microcontrollers). This is the improved version:

Screen Shot 2010 12 27 at 17.03.29

And here’s some new output over a longer period of time, rearranged for brevity:

Screen Shot 2010 12 27 at 17.05.39

A quick copy of these values into a spreadsheet produces this graph:

Screen Shot 2010 12 27 at 17.11.14

As you can see, the measurements follow a very clear and regular pattern. But what’s going on? Why are these lines curved? Why doesn’t the voltage go all the way up to 3.3V? Why doesn’t it drop to zero? How does this graph explain the LED’s brightness changes? How can we get a constant brightness?

Questions, questions. Welcome to the real world, which – in case you hadn’t noticed – is mostly analog!

The neat bit about all this is that not only can we just play around and hook up components in all sorts of funky ways, we can in fact even explain exactly what is going on. Those graph shapes, for example, are fully predictable exponential curves, and there’s a very simple reason why they are this way.

I’ll go into that in a future post, but first let’s find out how to create an arbitrary voltage using nothing but one digital output pin. C’ya tomorrow!

LED discharge circuit

In Hardware on Dec 28, 2010 at 00:01

Yesterday’s post ended with the suggestion to play with some electronics bij hooking up some components to a JeeNode (or Arduino). This is really very useful (and oodles of fun, what a bargain), since it brings together so many aspects of physical computing:

So let’s do it!

Here’s the initial plan, let’s see how it pans out:

  • set up a simple yet interesting circuit
  • hook it up to a JeeNode (an Arduino wold work just as well, but using 5V)
  • write a little test sketch to drive the circuit
  • use two analog input pins as a pair of DIY multimeters
  • report the results graphically
  • interpret the results and try out some variations

The circuit I’m going to use, looks as follows:

Dsc 2405

If you’re not familiar with solderless breadboards, note that those central holes in the picture are vertically interconnected in groups of five. I.e. the brown wire is connected to one side of a brown-black-red resistor on the right, as well as to one of the two wires coming out of that large black capacitor on the left. And so on.

One LED, one capacitor, two resistors, a few wires, and a JeeNode. That’s all. But as you will see, it’s enough to explore PWM and digital-to-analog conversion, and it illustrates how you can create your very own electronics workbench to explore “RC filters”, charge curves, discharge curves, pulse generators, timers, and even create a very simple oscilloscope to understand what’s going on in a dynamic electronic circuit.

The first thing I need to do is clear things up a bit. While that above picture is a fully functioning circuit, it’s pretty awkward to see exactly what is hooked up to what. Some of these components are polarized, so there’s in fact more to it than “which wire goes where”.

Here’s the same circuit, is schematic form:

Screen Shot 2010 12 27 at 12.24.48

See if you can match everything in the schematic up to that picture above.

First thing to notice, is that there’s a lot more info here, and it’s a lot more precise. The components use a standard notation, and their values are also indicated.

Now, although it was a fun exercise for me to draw this by hand and scan it in, it’s a bit tedious if I make mistakes while drawing or when things change. Fortunately, there are computer-aided design (CAD) software packages which make it simple to draw and edit such schematics on-screen. Here’s the same schematic using EAGLE:

Screen Shot 2010 12 27 at 12.37.42

It has the same layout as the hand-drawn version, but now all the components also have names: R1, R2, C1, LED1, etc. I’ll refer to these names from now on.

Ok, all nice and well, but what does the circuit DO ???

Well, first of all, since there is no energy source in there: nothing at all until you feed it from an external power source. Doh.

But this is where the fun starts. We could just hook up a battery to it (+ to VIN and – to GND), and there would in fact be some interesting behavior. But we can do a lot better than that: we can put the entire circuit under computer control! The digital output pins on an ATmega are terrific controllable power sources, as long as we only need a few milliamps at 3.3V or 5V. And if we need more… well, that’s where transistors come in (to be described in a future post).

The other great property of an ATmega (many MPUs, for that matter), is that they also have analog and digital inputs, so they can be used to measure various aspects of the circuit under test at the same time.

This is why the above circuit is hooked up to DIO3, AIO2, and AIO3 (digital 6, analog 1, and analog 2 on the Arduino, respectively).

I still haven’t told you what the circuit does. But if you’ve played around a bit with this stuff before, you should be able to predict what this little sketch does:

Screen Shot 2010 12 27 at 13.19.46

Stay tuned…

Easy Electrons – Electric charge

In Hardware on Dec 27, 2010 at 00:01

Welcome to another installment of the Easy Electrons series.

The previous article was about capacitance. And specifically about the dynamic properties of capacitors. Complex stuff (literally so, in fact).

This time, I will focus on the charge and energy aspects of capacitors (and similar components).

First a small diversion into the land of electrical units: a farad can be interpreted as the amount of charge you need to create a voltage potential of 1 volt. Charge is described in terms of coulombs (named after Charles-Augustin de Coulomb). One coulomb is equivalent to 1 amp current during 1 second.

Once you start diving into this, you will be thankful for the International System of Units which created a set of units of measurement that are very easy to use and to remember. Being able to write that previous paragraph about what a farad is, without a single conversion factor or physical constant is a great help, also intuitively. I can clearly picture an amount of water (coulomb), being lifted a certain height (volt), and flowing at a certain rate (ampere). And even though the water analogy is quite limited, it’s a great help to visualize what’s “happening” inside an electrical circuit.

The farad unit is awkward, though.

It’s far too big a unit for most capacitors. You will often see caps described in terms of µF (microfarad, 10^-6), nF (nanofarad, 10^-9), or even pF (picofarad, 10^-12). Capacitors in the mF (millifarad) range are less common.

There’s another very widespread type of electricity containers: batteries. A battery is a bit like a huge capacitor, even though its “charge” is not held as electrical energy but as chemical energy. For batteries, the farad unit is also awkward, because it’s in fact too small. Let’s find out how many farad a standard 1.5V 2500 mAh AA battery would be, if it were a capacitor:

  • 2500 mAh means it can supply 2500 mA during one hour
  • that’s 2.5 x 3600 = 9000 “ampere-second”
  • an ampere is defined as 1 coulomb per second
  • so the AA battery holds 9000 coulomb of charge
  • in our battery, that charge is “held” at 1.5V
  • so we’d need 9000/1.5 = 6000 coulomb to reach 1V
  • than means one AA battery is essentially a 6000 farad capacitor, charged to 1.5V

As you can imagine, it’s easy to make mistakes with farads because you may encounter values in normal use which vary over some fifteen orders of magnitude. Always check your zeros carefully!

Somewhere between the basic capacitor and the battery, lies the Supercap:

This is still a capacitor, but with a phenomenally high capacitance, compared to normal caps. The one shown here is 0.47 farad. No milli, micro, nano, or pico. These small devices are relatively new, and usually only work up to 2.7 or 5.5V, max.

If anything, supercaps look a lot like little batteries. They only hold their charge for a few hours though, due to a certain amount of internal leakage. Think of it as a resistor tied permanently to its output pins, draining the charge, slowly but incessantly.

One important use for capacitors (of all sizes) is as what I’d like to call “charge buffers”. This is the case whenever you see a capacitor with one side tied to negative, i.e. ground level:

Screen Shot 2010 12 12 at 21.17.17

What these do could be summarized as: resist change. If + in the left-hand image is tied to +3.3V, then the capacitor will charge up to 3.3V and then … it’ll essentially stop doing anything. But whenever there is a distubance in that 3.3V level, the capacitor will either draw current (if the voltage went up), or supply current (if the voltage went down).

It’s not that different from a rechargeable battery. Attach a voltage higher than the current battery and the battery starts charging. Attach a lower voltage, including any circuit consuming power, and the battery starts discharging.

The circuit on the right is slightly more involved, due to the extra resistor. The same happens as before, but now, as the capacitor draws or supplies current, the current has to pass through the resistor. As a consequence, the resistor will create a voltage drop (E = I x R, again!). The effect is similar to the LED circuit with a series resistor: the resistor will reduce the current flowing in or out, thus “dampening” the effect. So what you get, is that OUT lags IN, if IN changes, but eventually it’ll follow it to whatever voltage IN is.

The right-hand side is also called a low-pass RC filter. It tracks slow-moving changes fairly accurately, but rapid changes are evened out a bit.

The left-hand circuit is used all over digital circuits, to remove “noise” (i.e. very fast but random changes) in the power supply line. The noise comes from the fact that digital circuits switch connections all the time, changing electricity flow and power draw. Often a 0.1µF capacitor is used. This is usually called a “decoupling” capacitor. It rips high frequencies out of a supply line which you’d like to remain stable.

The right-hand circuit is also useful to even out variations, but in a more gradual and controlled manner. It’s used as last step in a power supply, and to even out pulse trains. One nice use of this, is to turn an PWM signal into an analog voltage:

  • a PWM signal which is always on will produce an output of that same voltage
  • a PWM signal which is always off will produce a zero volt output
  • everything in between will produce and averaged value in between the two extremes

There are some simple calculations to determine how fast things happen. Look for the term “RC time constant” on the web. And if you run into articles such as this one, don’t let the math discourage you. As I said in the previous post, the intricate details of capacitors involve complex calculations. Just skip them. There’s plenty you can do with caps without diving in.

Supercaps are also a lot of fun to play with. You get all the properties described above – after all, it is a capacitor like any other. The difference is that things happen a lot slower, due to the larger amounts of charge involved. Supercaps have enough energy to power an LED, for example (don’t forget the series resistor!). And when it does, you’ll see how it eventually fades and dies out, as the charge drops.

A simple experiment would be to measure the voltage over time with such a supercap driving an LED + resistor circuit. With Ohm’s law, you can then calculate the amount of current drawn. Which in turn gives you an idea how brightness in LEDs is related to the current through them. If you think that’s boring, how about measuring the voltage with a JeeNode, and then sending the results to your PC and plotting the values in real time? You may not realize it, but a lot of lab experiments related to electricity can be done with an ATmega, i.e. a JeeNode or an Arduino. Who needs a multimeter? Make one!

Easy Electrons!

Easy Electrons – Capacitance

In Hardware on Dec 26, 2010 at 00:01

This is the third installment of the Easy Electrons series.

Let’s talk about capacitance. Or more accurately: capacitors. What are they and what are they for?

My mental image of a capacitor uses the water analogy: a capacitor is like a bucket of water:

Screen Shot 2010 12 12 at 16.26.53

It’s a container, and in the case of a capacitor, it holds electrical energy. How much energy depends on how much water (electrical charge) and how high up (voltage potential) it is.

If you were to take a bucket of water to the top of the Eifel tower, you’d make a pretty hefty splash on the ground when emptying it!

Screen Shot 2010 12 12 at 16.26.43

Thinking in terms of electricity, a capacitor is a little bit like an isolator, because, when left alone, it prevents the water from going anywhere.

Capacity is measured in terms of farads, the name was chose in honor of Michael Faraday. I’ll talk more about that in a future post.

Ok, so what is a capacitor, eh?

Capacitors are funny little beasts. When you feed them with voltage or current changes, they sort of absorb them. It’s easy to visualize with the bucket of water analogy: if you hold one end of a hose submerged into the bucket and raise/lower the other end to model voltage change, you can imagine water flowing into or out of the bucket through the hose to rapidly adapt to the position (height) of the other end.

Once the current flows, capacitors immediately adapt and start to match the input voltage. Once they do, current stops. You can’t keep a constant current flowing through a capacitor. It’s not simply a conductor.

Another way to describe this, is that capacitors only affect a circuit while the voltage changes. Once it is constant, the capacitor stops playing along and will start to look more and more like a complete isolator.

This behavior is hard to grasp. You can’t just look at one state and reason from there, you have to look at the state over time and think in terms of change. Capacitance (and induction, for that matter) is substantially more complicated as concept than resistance.

But even though it’s hard, I think I can give you a feel for why it’s so tricky, using a little analogy.

When doing calculations with capacitance, dynamic systems, changes over time, and such, you’ll quickly run into something called complex numbers, a mathematical concept with immense implications in the field of electronics and other domains of physics.

Complex numbers are… w e i r d – well perhaps not as mind-bending as quantum physics, but still: complex numbers are an extension of normal numbers, in that every value consists of a real and an imaginary part. Want an example of how weird that is? How about: you can’t take the square root of a negative number such as -1, right? Because there is no value in the world which will produce -1 when multiplied by itself. Right? Wrong. With complex numbers, there is such a value (it’s called “i”, the unit of imaginary numbers).

But not to worry. I won’t expand further on complex numbers. And luckily there’s no need!

Suppose you were looking at a child sitting on a swing, swinging happily along – image on the left:

Screen Shot 2010 12 12 at 17.48.52

As you watch, you can see two things going on: a sideways motion and an up-down motion. Always mesmerizing, because there is this intriguing relationship between vertical and horizontal position and things like velocity. You’re looking at the fascinating world of complex numbers, using the analogy of a pendulum.

Now imagine yourself looking at that same child swinging, but from the back, swinging away and towards you. It’s the same situation, but you’re only seeing part of the picture – image above, on the right.

What you see, is a swing moving up and down in some smooth repeating cycle. There’s much less to reason about now. You can no longer contemplate the periodic alternation of angular velocity and potential energy (i.e. height). There’s a hidden dimension which you can’t observe. IOW, you’re no longer seeing the big picture, but only half the essential information, i.e. only the real part, not the imaginary part.

That’s what makes it so hard to build up an intuition about what capacitors do. They require a richer conceptual model. Most of us are not trained to think in complex numbers, we just see quantities as a simple numerical value.

Fortunately, this need not prevent us from dealing with capacitors. We just have to work a bit more from memorized rules and water analogies, instead of innate intuition.

This is why I think of a bucket of water, and how it “dampens” all changes it is subjected to:

Screen Shot 2010 12 12 at 17.20.41

That’s also known as a “low-pass filter”. Very useful to turn a PWM signal into an analog voltage level, for example.

And why for me, capacitors “pass electrical changes” and then “become isolators”:

Screen Shot 2010 12 12 at 18.26.30

That’s a high pass filter, by the way. It doesn’t let the flat portions of the input signal through, just the edges.

Next time: a bit more about farads, charge, and really really big caps.

Easy Electrons – LEDs

In Hardware on Dec 19, 2010 at 00:01

This is the second installment of the Easy Electrons series. This isn’t a “course” in electronics. Just a grab bag of topics, and an attempt to convey my somewhat intuitive grasp of them. That’s also why I’m not going to systematically cover all the usual types of components, not in the traditional order anyway.

Today’s topic is low-power signaling LEDs, or Light Emitting Diodes.

Heres a very nice exposed diagram of a standard low-power red LED, from HowStuffWorks:

Led Diagram

Schematically, a LED is shown as an arrow (same as a diode), with light coming out. Here’s the Blink Plug, with two LEDs and two switches:

Screen Shot 2010 12 12 at 14.42.29

Here is the way you hook up a single LED:

Screen Shot 2010 12 12 at 14.47.06

The arrow has to point from + to – for the LED to work. It’s a diode, meaning that in the other direction it just “blocks” (no current, nothing happens). Also note that, since this is a series circuit with LED and resistor connected one after the other, it doesn’t really matter in which order you hook them up. This circuit will work just as well if the resistor comes first. As long as + “flows” to – through the LED.

So what’s that resistor doing in there?

Well, LEDs (like any diode) are very peculiar in terms of voltage and current. They behave in a specific way:

  • below a certain voltage, nothing happens, i.e. no current flows
  • when no current flows, the resistor makes no difference at all (E = I x R, i.e. 0 x anything is still 0!)
  • above a certain threshold, the LED starts conducting and letting all current through
  • the LED only emits light above that threshold
  • the brightness of a LED is determined by the amount of current through it
  • LEDs only support a certain amount of current, any more will damage them

To use the water analogy, an LED is like a dam which will not let water through before a certain level has been reached. Once that happens, everything more spills over:

Screen Shot 2010 12 12 at 15.09.35

The threshold depends on LED type: with red LEDs, it’s usually around 1.7V, with blue LEDs, it’s more like 3V.

You can’t just connect an LED directy to a power source. Think about it. LED behavior can be graphed as follows:

Screen Shot 2010 12 12 at 14.47.16

In other words: if the voltage is too low, nothing will happen. And if it’s too high, the current through the diode will be immense (and destroy the LED). We could try to regulate the voltage just right, but it varies slightly per LED and also depends on temperature, for example. There’s no way we can adjust our power supply once and get just the right level, day in day out. Besides, often we can’t even adjust the voltage at all, such as with a battery.

So how do we solve this?

Well, that’s where the resistor comes in. This is an example of another major use of resistors: current limiting.

Again, go back to Ohm’s law, i.e. E = I x R (memorize it, please!). The more current flows through a resistor, the higher the voltage over it. Or equivalently, the higher the voltage placed on it, the more current will flow.

In the above LED circuit, the resistor will always have the input voltage minus the LEDs threshold voltage over it (once the input is higher than the threshold). The effect on the voltage and current in this circuit changes in an important way due to the extra resistor:

Screen Shot 2010 12 12 at 15.09.44

The vertical “knee” in the original LED graph has turned into a more gradual slope, due to the added resistor. As more surplus voltage is handed over to the resistor, it starts to gradually use more current. This effect is completely linear, btw. An LED with a 1.7V threshold will be twice as bright with a 4.9V power supply as with a 3.3V supply.

Ok, well, so much for the pictures. What this tells us is that we can now calculate exactly what resistor we need.

For example, say we want to light a LED using a 3.3V power supply and let 10 mA (0.01A) current flow through it, which is a good value for standard LEDs. What resistor do we need?

  • the LED “takes” a fixed 1.7V
  • that leaves 1.6V for the resistor when the supply is 3.3V
  • we want to get 10 mA flowing through the LED
  • since the resistor is in series, it’ll get those same 10 mA
  • E = I x R can also be written as R = E / I (same law, different usage)
  • so R needs to be 1.6 V / 0.010 A = 160 Ω

Take a LED, add a 160 Ω in series, and the LED will work great on a 3.3V power supply. A more easily available 150 Ω resistor will work fine too, BTW. Almost the same currrent.

What if you don’t have a 150 Ω resistor, but only a 1 kΩ one? No problem, the current through the LED then becomes: (I = E / R), i.e. 1.6 V / 1000 Ω = 1.6 mA – usally still enough to turn the LED on, but not as bright.

Easy Electrons!

Voltage: 3.3 vs 5

In AVR, Hardware on Dec 16, 2010 at 00:01

One of the decisions made early on for the JeeNode, was to make it run at 3.3V, instead of the 5V used by the standard Arduino.

The main reason for this was the RFM12B wireless module, which can only be used with supply voltages up to 3.8V, according to the specs. Running them at 5V seems to give varying results: I’ve never damaged one, but there have been reports of such failures. Given that the older RFM12 (no B) worked up to 5V, my hunch is that something in the design was found to give problems at the higher voltage. It’s just a guess on my part, though.

So what’s the deal with 3.3V vs 5V?

Well, the first thing to note, is that the ATmega328 used in a 3.3V JeeNode runs at the same 16 MHz frequency as a 5V Arduino does. This overclocking is “out of spec”:

You’re not supposed to do this, but in my experience the good folks at Atmel (the designers and manufacturers of ATmega’s and other goodies) have drawn up specifications which are clearly on the conservative side. So much so, that not a single case has been reported where this has caused problems in any of the several thousand JeeNodes produced so far. As I pointed out in a previous post, that doesn’t necessarily mean everything is 100% perfect over the entire temperature range. But again: no known problems to date. None.

This is good news for low-power uses, BTW. It means you can get the same amount of work done using less power, since power = voltage x current. Even more so because both voltage and current are lower at 3.3V than when running at 5V.

A second reason for running at 3.3V, is that you can use 3 AA batteries instead of 4 (either alkaline or rechargeable). And that you can also power 3.3V circuits with LiPo packs, which have this hugely convenient 3.5..4.2V range.

The third important reason to run JeeNodes at 3.3V, is that more and more neat sensor chips are only available for use in the 2.7 .. 3.6V range or so. By having the entire setup operate at 3.3V, all these sensors can be used without any tedious level converters.

Occasionally I’ve been bitten by the fact that I used a chip which doesn’t work as low as 3.3V, as in the first RTC Plug trial. But more often than not, it’s simply a matter of looking for alternative chip brands. One recent example was the 555 oscillator used on the Infrared Plug: the original NE555 needs at least 4.5V, but there’s an ICM7555 using CMOS technology which works down to 3V, making it a non-issue.

Mixing 3.3V and 5V devices

The trouble with these voltage differences, is not just that the power supply needs to be different. That’s the easy bit, since you can always generate 3.3V from a 5V supply with a simple voltage regulator and 2 little capacitors.

The real problem comes from the I/O interface. Placing a 5V signal on a chip running at 3.3V will cause problems, in the worst case even permanently damaging the chip. So each I/O pin connected is also affected by this.

Fortunately, there’s often a very simple workaround, using just an extra resistor of 1 kΩ or so in series. To see how this works, here’s the way many chips have their input signals hooked up, internally:

Screen Shot 2010 12 14 at 23.35.16

There’s a pair of diodes inside the chip, for each pin (not just the inputs), used for ESD protection, i.e. to protect the chip against static electricity when you pick it up.

These diodes “deflect” voltage levels which are above the VCC of the device or below GND level. They do nothing else in normal use, but if you were to place 5V on in a pin of such a device powered by 3.3V, then that would lead to a (potentially large) current through the upper diode.

With electronics (as with humans, btw), it’s usually not the voltage itself which causes damage, but the current flow it leads to, and – in the case of sensitve electronics components – the heat produced from it.

By placing a 1 kΩ resistor in series, we limit the flow through the diode to under 2 mA, which most devices will handle without any problems:

Screen Shot 2010 12 14 at 23.42.27

Ok, so now we can hook up signals to a JeeNode, even if they swing in the 0..5V range. This works best with “slow” signals, BTW. The extra resistor has a bad effect on rise and fall times of the signal, so don’t expect this to work with signals which are in the 1 MHz range or higher. Then again, it’s unlikely you’ll need to tie such fast signals directly to an ATmega anyway…

How about the other direction?

What if you have a chip running at 5V which needs to receive signals from a chip running at 3.3V, i.e. signals going in the other direction?

Well, it turns out that this may or may not work by simply tying the two lines together. The 3.3V output signal will definitely not damage a chip running at 5V. The worst that can happen, is that the 5V side doesn’t consider the signal valid.

We need to look into logic levels to figure this one out, as specified in the datasheet of the chip. The easy part is logic “0″, i.e. a low level. Most chips consider anything between 0 and 0.8V a logic “low”. There will hardly ever be an issue when tying a 3.3V chip to a 5V chip.

The tricky part is logic “1″, i.e. a signal which is intended to represent a high level. Now it all depends on what the 3.3V chip sends out, and what the 5V chip requires.

Most CMOS chips, including the ATmega, send out nearly the full power line voltage to represent a logic “1″ (when the load current is low), so you can expect output signals to be just about 3.3V on a JeeNode.

On the input side, there are two common cases. Some chips consider everything above 1.6V or so to be a logic one. These chips will be perfectly happy with the JeeNode signal.

The only case when things may or may not work reliably, is with chips which specify the minimum logic “1″ voltage to be “0.7 x VCC” or something like that. On a 5V chip, that translates to a minimum value of 3.5V …

Note that datasheets usually contain conservative specs, meant to indicate limit values under all temperatures, load conditions, supply voltages, etc.

In practice, I find that even with “0.7 x VCC”, I can usually drive a 5V chip just fine from a JeeNode. The only exception being higher power chips, such as stepper motor drivers and such, which operate mostly at much higher voltage levels anyway. For these, you may have to use special “level translator” chips, or perhaps something like the I2C-based Output Plug, which can be powered with voltages up to 50V or so.

This post only addresses digital I/O signals. With analog I/O, i.e. varying voltage levels, you will need to carefully review what voltage ranges are generated and expected, and perhaps insert either a voltage divider or an op-amp to amplify voltages. That’s a bit more involved.

But all in all, living mostly in a 3.3V world is often more flexible than living mostly in a 5V world, nowadays.

Which is the fourth reason why I decided to run JeeNodes at 3.3V, BTW.

Easy Electrons – Resistors

In Hardware on Dec 12, 2010 at 00:01

A few days ago, I was completely overwhelmed by the positive response to a couple of posts about electronics principles such as power and circuit diagrams. Since I love to share what I’ve learned (and still learn) about this world full of discoveries, inventions, and creative engineering, I’ve been thinking about how to fold such a topic into this daily weblog.

The result is Easy Electrons – a series which will cover various aspects of electronics from the viewpoint of a technology enthusiast with a non-electronics background.

I’ve got some ideas about the frequency and topics for these posts, but I’m not commiting to a schedule or specific subjects just yet. Let’s see how it goes, and let me know what you think of these posts. Your comments will help guide me.

With that out of the way – let’s have some fun with electronics, eh?

But ya’ can’t run before you walk. This kick-off post has to go into some basic stuff. You may well know all this, but if in doubt, make sure you “get it”. Without these preliminaries, you will not be able to make sense of everything else in the upcoming posts of this series.

Resistance is not futile!

IMO, there is no concept more important in electrical circuits than resistance. One reason is that it’s everywhere, even the thickest copper wire has some resistance, however small. And an insulator, i.e. the stuff that prevents electricity from flowing all over the place, has essentially infinite resistance.

Take a voltage (or, using the water analogy: lift some water up). Once you let it “go”, it’ll want to flow. It does this using the path of least resistance. Thick solid copper pipe: huge current, massive power surge. Very thin wire: tiny current, squeezing its way through and heating up the wire. If the squeeze is strong enough (enough voltage) the wire will heat up to the point where Thomas Alva Edison made an incandescent light!

Voltage wants to flow. And when it does, it creates a current. It flows quickly when the resistance is low, it flows more slowly when the resistance is high, and it fails to flow when the resistance is infinite. That’s also why electricity will always pick a copper wire over plain air.

It’s time to introduce Ohm’s law:

    E = I x R

In words: voltage = current times resistance.

Voltage is described in volts (thanks to Alessandro Volta), current is described in amps (courtesy André-Marie Ampère), and resistance is described in ohm (due to Georg Simon Ohm).

I’ll simplify the world by saying: in simple cicuits with no effects from electric and magnetic fields, Ohm’s law is all you need to know. If you know any two of the quantities, you can calculate the third.

I won’t go into them now, but if you also learn the two Kirchoff’s circuit laws, then you’ll have some incredibly powerful tools to explain what’s going on, even in circuits with dozens of components, connected in all sorts of funky ways.

Physicists and chemists will be used to this, but if you come from the world of software, then note that these laws are really quite amazing: they let you predict what will happen when you hook up a circuit. Laws such as this were not “created” to terrorize kids in school, they are really extremely useful!

Let’s try it:

Screen Shot 2010 12 05 at 15.16.27

What’s the voltage on the right side? (assuming no load current)

I’m going to skip several details, but here’s how I would reason about it:

  • we want to know the voltage over the lower resistor
  • we know its resistance, so if we knew how much current is flowing, we could calculate it
  • the current flows through both resistors
  • the current IN is the same as the current OUT
  • so the same current flows through both resistors
  • we know the voltage over the total
  • if we knew the total resistance, we could derive the current through both
  • once we do, we know the current through the lower resistor
  • and from there, we can calculate the voltage, as requested

Question: what is the resistance of two resistors placed in series, one after the other?

Answer: this is one of those facts you’ll just have to memorize – resistance of R1 and R2 in series = R1 + R2.

  • so we have 9 volts over 3 kilo-ohm, i.e. 3000 ohm
  • the current is 9 / 3000 = 0.003 amps, i.e. 3 milliamps
  • voltage over 1 kΩ is 1000 x 0.003 = 3 volt

So the final answer is 3 volts.

But don’t stop there, please:

  • What if we use a 3V battery? Answer: (3/3000)*1000 = 1V.
  • How about a 12V power supply? Answer: (12/3000)*1000 = 4V.
  • See the pattern?

The two resistors act as a voltage divider. They don’t really “care” about the input voltage, they will simply divide it by 3. Because the ratio of the total to the lower resistance is (2+1)/1 = 3. This is also the reason why I drew that schematic in this particular way: it illustrates the voltage “drop”.

Hold on to that insight. Electric circuits usually have lots of voltage dividers. Whenever I see resistors in series, I try to determine what voltage is placed over them. And sure enough, most of the time, that’s what the resistors are used for. It works for any voltage. It also works for varying voltages: if you have an audio signal in the form a a rapidly varying voltage, then the voltage divider will simply pass the signal through, at a reduced voltage level.

Not every resistor is used as voltage divider. But more often than not, that’s all they do when used in series.

Easy Electrons!

P.S. Would you believe that I found out about this tutorial after writing the above? Heh… synchronicity :)

What is “power” – part 2

In Musings on Dec 4, 2010 at 00:01

To continue yesterday’s post, let’s go into that last puzzle:

Why does the 1x AA Power Board run out of juice 3 times as fast as a 3x AA battery pack?

The superficial answer would be: it’s one battery instead of three, so obviously it’ll last 1/3rd as long.

But that’s not quite the whole story…

The AA Power Board contains a switching regulator called a boost converter. Switching regulators are a lot more efficient than ordinary “linear” voltage regulators. They play games with energy conversion into electrical and magnetic fields. And by doing so, they mess with the rule that current is always the same everywhere.

But let me first explain what a linear regulator does:

Screen Shot 2010 12 02 at 22.12.51

Don’t laugh – that’s the essence of a linear voltage regulator: a variable resistor!

Well, it’s far more complex than that in reality. But the machinery inside a linear voltage regulator is all about wasting energy. The goal is to waste just the right amount to get the desired 3.3V on the output pin, regardless of changes in input voltage and current draw. Functionally, all the regulator does is continuously adjust its internal resistance to get the right output.

If you think about it, there’s in fact little else you can do with resistors. They exist to drop voltage, and by doing so, they generate heat, even if the amount is minimal and usually irrelevant.

The other type of regulator is the switching regulator. Huge topic, way beyond the scope of this post (and way over my head, in fact). I’m bringing it up because the AA Power Board uses a switching regulator to “boost” the voltage from say 1.5V to 3.3V.

So how does one boost voltage?

The hydraulic analogy would be to pump water from one level to a higher level using only water power (height and flow). There’s an ingenious pump called a hydraulic ram which can do that. The one I’ve seen in action works by letting water flow and then quickly interrupting that flow. All of a sudden, the water has nowhere to go and pressure builds up. All you need is an outlet pointing up, and the water will go there as only option.

The flow will quickly stop, so the trick is to repeat this cycle, and then – in a pulsating fashion – you actually can get water to climb up. Voilá, a higher voltage!

That’s also how the AA Power Board works. It contains an efficient switch, which pulses the current flow, and (in most cases) an inductor which transforms current changes into a magnetic field, and vice versa. The inductive “kick” is what makes it possible to play games with current vs. voltage without turning it all into heat.

But you don’t get anything for free. Apart from circuit losses, you lose the conversion factor w.r.t. power – drawing 10 mA @ 3.3V will require 30 mA @ 1.1V – with circuit losses increasing that slightly further. You can’t ever get more watts out of this than you put in!

So, roughly speaking, to get 3.3V from a 1.2V AA NiMH battery, you need to draw about 3 times as much current from the battery as what will go into the target circuit.

Which is why a 2000 mA single AA battery behaves roughly like a 650 mAh battery delivering 3.3V via the boost converter. With our circuit drawing 10 mA, that will last 650 mAh / 10 mA = 65 hours.

That’s roughly a third as long as the 3x AA battery pack. QED.

There are some losses and inefficiences. Even with a switching regulator, you should expect no more than 90..95% efficiency under good conditions. But this is nowhere near the inefficiency of a linear regulator with a high input voltage. On a 9V battery, the on-board regulator of a JeeNode will be less than 40% efficient.

Note that there are also down-converting switching regulators (called buck converters), and these do have much higher efficency levels. Even the AA Power Board is able to handle over 5V on its input, and still deliver a 3.3V output, by going into a buck conversion mode. In which case the input current will be less than 10 mA to deliver 10 mA @ 3.3V on its output – something a linear regulator simply cannot do.

Conclusion: if you want very power-efficient solutions, look carefully at what voltages to use for supplying your circuits, and use switching regulators when the voltage differential is substantial. Linear regulators can only drop voltage, and can only do so by wasting energy.

There is another benefit to using a boost converter: it lets you suck the last breath out of batteries. The AA Power Board can be used with batteries with only 0.85V or so left in them, and if kept connected and running, it’ll work all the way down to 0.6V or so. You can be assured that by the time an AA Power Board gives up, its battery will have been completely drained!

One last note about the AA Power Board: maximum efficiency is achieved with an input voltage between 2.4V and 3.0V, so if you want to optimize, consider using either 2 AA (or AAA) cells, or a 3V battery such as the CR123A, which is half the size of an AA and a great source of energy with about 900 mAh of oomph…

But just to put all this into perspective: if all you want is a good solid source of power for a JeeNode and everything attached to it, use a 3x (or 4x if you have to) AA battery pack. Or use power from USB.

Me, I’ll stick to single rebranded Eneloops @ 1.2 .. 1.3V.

What is “power”?

In Musings on Dec 3, 2010 at 00:01

Here’s something which may be totally obvious to some, yet clear as a mud to others…

Voltage, current, power – what are they? Here are some puzzles I’ll go into:

  • Why does a 4x AA battery pack run out almost as fast as a 3x AA battery pack?
  • Why does a 9V battery last about 1/4th as long as a 3x AA pack?
  • Why does the 1x AA Power Board run out of juice 3 times as fast as a 3x AA battery pack?

Let’s take it one step at a time. An often-used analogy for electricity is water (see hydraulic analogy). To simplify, let’s say that electricity flows from a high voltage to a low voltage, such as ground. Likewise, water flows from a high location to a lower location. So let’s make the analogy that high voltage equals water high above the ground.

This is what happens in a circuit where a 3.6V battery powers a JeeNode:

Screen Shot 2010 12 02 at 19.56.58

While in the battery, the voltage is “at” 3.6V. When it goes through the on-board voltage regulator, it is made to drop to 3.3V, and then that electricity flows through the ATmega, RFM12B, etc, to ground.

Let’s assume the circuit draws 10 mA. The thing about current is that it’s doesn’t change across a circuit, like voltage does. Using the water analogy: current is the amount of water flowing. And no matter where it flows, the amount at the top is the same as the amount lower down. It might trickle down in different ways, but the amount into the whole circuit is the same as the amount coming out:

Screen Shot 2010 12 02 at 20.13.33

So what we have is a battery, where the electricty “starts out”, and then it traverses first the voltage regulator, then the ATmega, etc, and then it flow back into the battery at 0V, which in effect “pumps” it back up to 3.6V. And the the cycle repeats.

I’m taking many liberties here. Electricity doesn’t really flow from + to -, and there’s no pumping involved either. But as a mental model, this actually works pretty well.

So what’s “power” then, eh?

Well, power is defined as “voltage times current”. I’ve added the calculations in that second diagram. As you can see, with a 10 mA current consumption, the battery generates 36 mW, of which the voltage regulator consumes (i.e. wastes) 3 mW, and the ATmega, etc, get the remaining 33 mW.

What you may not realize, is that “consuming power” is basically equivalent to “turning electricity into heat” – because that’s what happens, essentially. Think about it: the JeeNode is really just a mini electric heating. It isn’t very much heat, and it happens over a long stretch of time. But in the end, when the battery is dead, you’ve done nothing but heat up the surroundings a teeny bit…

Well, almost: a small amount will have been emitted as radio energy when the RFM12B is transmitting.

Ok, so now let’s try to answer the above three questions.

Why does a 4x AA battery pack run out almost as fast as a 3x AA battery pack?

This is due to the voltage regulator. If you feed it say 4.8V, instead of 3.6V, it will simply waste that extra energy: the voltage drop over the regulator will be 1.5V instead of 0.3V, so that the output of he regulator stays at 3.3V. That’s the whole purpose of the regulator after all: to deliver a constant voltage, regardless of the voltage placed on its input pin.

Here’s what would happen if you put 9V on the voltage regulator:

Screen Shot 2010 12 02 at 20.32.10

And here’s how that works out in terms of power consumption:

Screen Shot 2010 12 02 at 20.33.05

(correction: the 5.3V – bottom middle – should have been 5.7V)

In other words: you can raise the voltage all you like, it won’t have any effect on the amount of power needed or used by the ATmega, etc. They will always get 3.3V, and will continue to draw 10 mA as before.

The only thing that happens, is that the voltage regulator works a little harder, and wastes a bit more power by turning it into more heat!

Conclusion: if your circuit doesn’t need the higher voltage to work properly, power it at the lowest practical voltage. Keep in mind that the “low-drop” voltage regulator on the JeeNode likes to have at least 0.1..0.2V to do its job properly. Both 3x AA packs and LiPo batteries are just about perfect for JeeNodes.

Another very important lesson from this is that if you’re trying out stuff, and you notice that the voltage regulator is getting very hot because some part of your circuit draws a lot of current, then you should try to reduce (!) the voltage you’re feeding into it: you’ll help the regulator, by giving it less power to eat up and waste.

Why does a 9V battery last about 1/4th as long as a 3x AA pack?

Now with the above explanation, it should be clear that the 9 volts won’t give you a longer-running JeeNode. But why is it so much shorter?

The reason is that not all batteries contain the same amount of energy. The capacity of a battery is specified in terms of milli-Ampere-Hour: an AA battery often has over 2000 mAh. This means it can supply 2000 mA for one hour. Or 1000 mA for 2 hours, 500 mA for 4, etc. And then it’s empty.

Energy is defined as Voltage x Current x Time (or equivalently: Power x Time). The unit is watt hour.

So the amount of power you get when draining an AA battery in one hour (voltage x current) is: 1.5V x 2000mA = 3.0 watt. Consquently, the amount of energy in a a 3x AA pack is 9.0 watt hour.

For a standard 9V battery, the figure is around 500 mAh. This is 9V x 500 mAh = 4.5 watt hour of energy.

Great, so a 9V battery has half as much energy as a 3x AA battery pack, and should last about half as long, right?

Wrong! – go back to that first discussion about feeding the voltage regulator with 9V instead of 3.6V: it just turns that extra voltage into heat.

The way to estimate lifetimes, is to use the current draw as starting point. We assumed in all these examples that the circuit is drawing a constant 10 mA.

On a 3x AA pack (or 4x AA, for that matter), this means we get 2000 mAh / 10 mA = 200 hours of run time.

But on a 9V battery, we’ll only get 500 mAh / 10 mA = 50 hours of run time!

Conclusion: don’t use 9V battery packs for JeeNode projects. They are an expensive way to waste energy, and you’ll keep running to the shop to get new ones.

Why does the 1x AA Power Board run out of juice 3 times as fast as a 3x AA battery pack?

Before even going into that, the first puzzling fact about running a JeeNode off a single AA is really: how can a 3.3V circuit run off a 1.5V power source in the first place? Think about it. As you know, most electrical circuits don’t work at all when the supply voltage is too low.

It’s equivalent to asking: how can you get water which flows at a certain level to lift itself to a higher level?

Hint: there exists an ingenious type of water pump which can do this!

To be continued in tomorrow’s post…