Computing stuff tied to the physical world

Archive for April 2012

Tiny Lithium discharge

In Hardware on Apr 30, 2012 at 00:01

The tiny rechargeable Lithium batteries I mentioned recently are another way to try and retain some charge overnight, just like the supercap mentioned last week.

First thing to do was to charge it up for a day, using a 1 kΩ resistor and a 3.0V supply:

Screen Shot 2012 04 22 at 17 14 55

I adjusted the radioBlip sketch, to switch back to 8 MHz (because the ATmega will be running well below 3.3V):

Screen Shot 2012 04 22 at 18 12 35

And I used these fuse settings:

  • efuse 0x06 = BOD 1.8V
  • hfuse 0xDE = OptiBoot (512b)
  • lfuse 0xCE = fast 16 MHz resonator startup

This should allow a JeeNode to work all the way down to 1.8V (the RFM12B radio only officially supports down to 2.2V but usually still works a bit below that). I also used a JeeNode with no regulator, and added a 100 µF cap to handle the peak currents during packet transmission (100 µF is a bit excessive – less probably also works fine):

DSC 3071

And sure enough, even with 2.75 V left in the battery, it starts up fine and starts sending out packets.

Unfortunately, I accidentally shorted out the battery while fiddling with the cables – so the charging process needs to be repeated for duration tests :(


In Hardware on Apr 29, 2012 at 00:01

Elektro:Camp is a convention on Smart Metering, Smart Home, Smart Grid and Smart Ideas, in a BarCamp style.

October 2011, I attended this really interesting get-together about smart metering, monitoring, home automation, and more. Very heavy on technology. It’s basically a few rooms filled with lots of human ingenuity for two days :)

The Elektro:Camp event is scheduled twice a year in various locations, and is coming up again very soon:

Elektro camp 2012 05 final web

You can find out more and sign up on this website.

Lots of people signed up already, from all over Europe.

Due to a silly scheduling mistake, I can’t make it this time, unfortunately. But if you like the stuff on this weblog, then you’ll most likely also be delighted with everything being presented and discussed at Elektro:Camp!

Tiny solar cell – part 2

In Hardware on Apr 28, 2012 at 00:01

The tiny solar cell chip presented a couple of days ago has been doing some indoor sun-bathing:

DSC 3073

I’ve left it alone for some 3 days, just to give it a chance to charge up the 0.47 F supercap as far as possible. The voltage after all that time (partly sunny on most days) is now only just over 2.78 V, so this isn’t really going to work indoor, I’m afraid. Nor outside during the winter, probably – it’s just too weak.

The other solar cell I tried is also a very small one, rated at about 5V but only 1 or 2 mA, IIRC:

DSC 3083

It’s currently in the shadow, but during these same 3 days it has had its share of sunlight (still indoor, and again behind double-glazing). Much better: about 4.75V on the second day, and unchanged since then.

This might actually do the trick. I’ll wait for another experiment to finish and will then hook up the JeeNode running my radioBlip sketch to see how it goes.

Component Tester revisited

In Hardware on Apr 27, 2012 at 00:01

In January, I described the concept of a Component Tester, and how it can help understand what various types of components are doing.

In theory, you can just hook up a small transformer to generate the signal needed for the CT, i.e. a 50 Hz ±10V sine wave. Here is the circuit again, which is delightfully simple as you can see:

That secondary voltage is a bit high, though. Here’s what I get with two 6.3 VAC in series, i.e. 12.6 VAC:


Half that would be fine. But it’s not really a sine wave, as you can see from the many harmonics in an FFT:


And it shows – here’s what you get when placing a 1 µF electrolytic capacitor under test:


Yikes, what a mess! With a (clean) sine wave, that would have been a (clean) oval!

I don’t think it makes sense to build a CT this way. Not with this particular small transformer anyway…

TK – Semiconductor Analyzer

In Hardware on Apr 26, 2012 at 00:01

Welcome to the Thursday Toolkit series, about tools for building Physical Computing projects.

Today’s episode is about a little gadget called the DCA55 Semiconductor Analyzer from Peak Electronics:

DSC 3053

It’s a nifty little self-contained unit, which identifies a range of 2- and 3-pin semiconductors, their pinouts, and some useful characteristics:

  • NPN and PNP Bipolar Junction Transistors and Darlingtons
  • Various types of MOSFETs and Junction FETs
  • Low-power thryristors and triacs
  • Diode and diode networks, as well as LEDs

The convenient bit is that you just hook up all the pins, press ON, and this gadget will figure it out, all by itself.

Here’s a BC549C transistor, i.e. a very common high-gain NPN transistor:

DSC 3051

And here’s an example from the datasheet, showing all the info you get:

Screen Shot 2012 04 17 at 18 10 49

I wouldn’t call this unit indispensable – most of this can also be derived with a battery, a few resistors, and a multimeter – but it’s darn convenient, if you regularly re-use stuff from your spare parts bin, as I often do.

Tiny solar cell

In Hardware on Apr 25, 2012 at 00:01

Got a tip from Lennart Herlaar a long time ago about a tiny CPC1824 solar cell from Clare with 4V output:

CPC1832N sml

It’s packaged as a SOIC-16 chip, so clearly the light collecting capabilities of this thing will be limited. But with all this ultra-low power stuff going on here at JeeLabs, I thought I’d give it a whirl anyway. It’s trivial to hook up:

Screen Shot 2012 04 22 at 15 27 51

In bright sunlight, you get over 4V with a 100 µA short-circuit current according to the datasheet.

I added a BAT34 Schottky diode in series (which has a low voltage drop) and placed it all on a little breadboard together with a 0.47 F supercap – the solar chip is mounted on a little SOIC breakout board:

DSC 3069

The initial voltage was under half a volt, but rising (very) slowly and steadily while exposed to light.

Let’s just leave this thing exposed to light near a south-facing window for a week or so, eh?

TD – Solar light

In Hardware on Apr 24, 2012 at 00:01

Welcome to the Tuesday Teardown series, about looking inside the technology around us.

The other day, Ard Jonker pointed me to this item available at the Dutch Lidl stores for €12.95:

DSC 3066

A solar LED light you put in the floor outside, which automatically lights up when it gets dark.

It’s about 14 cm in diameter, and 6 cm deep – let’s have a look inside:

DSC 3067

A solar cell, with two white LEDs, held in place by two screws yearning to be removed:

DSC 3075

The red leads connect to an on/off switch which can be accessed from outside. The batteries are 800 mAh, according to the specs, and look like standard replaceable AAA cells. The PCB has a chip on the other side:

DSC 3076

Hey – not bad, two NiCad NiMH’s and a little chip to drive the LEDs. This could easily accommodate a JNµ!

The DIP-8 chip in there seems to have logic for turning the LEDs on only when it’s dark (weak solar cell voltage, I assume). It does a bit more though, as this scope trace of one of the LED shows:


Probably some sort of charge-pumping, to drive the LEDs beyond the 2.5V supplied by the batteries. The power consumption is about 9.5 mA, so these lights should last through the night if there is enough sunlight during the day to fully recharge the batteries.

Neat. This could make an excellent power source plus enclosure for a JeeNode Micro, but note that the big metal ring is essential – it presses the glass and rubber seal tight against the rest of the enclosure “cups”.

Supercap discharge – part 2

In Hardware on Apr 23, 2012 at 00:01

Yesterday, I charged a 0.47F 5.5V supercap to 5.1V and kept charging it for 24 hours to reduce the leakage current.

Actually, I lowered it to 5.01V in the last hour – there’s a slight memory effect, so right after lowering the voltage actually rises when power is disconnected.

Next step is to measure the supercap’s self-discharge time from 5.00V to 1.84V (i.e. 36.8% of 5V) – that’ll give the time constant of the RC circuit (the real capacitance, in parallel with an imaginary internal current leakage resistor). Note that this is not the same as the ESR of a cap, which is about charge & discharge current losses.

Ok, let’s disconnect the power supply and track the voltage readings in high-impedance mode. It is 10:17 here, and the voltage has just dropped to 5.00V – with the power supply removed.

Time passes. Unfortunately, waiting for the voltage to drop to 1.84V (i.e. 36.8% of 5V) would take a bit long, so let’s throw some math at this and come up with a quicker way to measure leakage current:

  • for T = R x C, we need to measure a drop to 36.8% (i.e. a factor 0.368) of the original voltage
  • since the charge decay curve is exponential, we can estimate when 0.5 T will happen
  • this turns out to be the square root of 0.368, i.e. a factor of 0.607
  • so with a drop to 0.607 x 5V = 3.033V, we know 0.5 x T
  • let’s repeat that trick one more time, to get at 0.25 x T
  • my trusty on-screen calculator tells me that the square root of 0.607 is 0.779
  • so if we wait for a drop to 0.779 x 5V = 3.894V, we’ll know 0.25 x T
  • four times that duration, and we have T, the RC time constant we’re after

Good. That means I only need to wait for the supercap charge to drop by roughly 1V i.s.o. over 3V.

More time passes. It’s now 0:26 after midnight, and the voltage has dropped to 3.98V – i.e. not yet the 3.894V we need to reach, but hey, let’s call it a day anyway.

That’s over 14 hours total, i.e. over 50,000 seconds = 0.25 x T, so the calculation now becomes:

  • 200000s = R x 0.47F
  • R = 200000 / 0.47 ≈ 425 kΩ
  • so at 5V, the internal discharge current is 5V / 425kΩ ≈ 12 µA

Hmmm…. that amount of leakage is three orders of magnitude higher than with a 47 µF electrolytic cap, but it might still be usable as power source for a JeeNode or JeeNode Micro. Here’s my reasoning:

  • suppose the JN/JNµ draws 12 µA on average – a tough target, but it should be feasible
  • then we’re effectively draining the supercap twice as fast as its self-discharge
  • it looks like the supercap can hold a charge down to 1.8V for 56 hours on its own
  • note that 1.8V is too low for RFM12B use, but the microcontroller would still work
  • with the added load from the JN/JNµ, this halves to 28 hours, i.e. slightly over a day
  • so the challenge will be to fully recharge the supercap to 5V at least once a day

A solar cell might just do it – assuming it’s large enough to overcome a dark and cloudy winter day. And the good news is that supercaps can charge up very fast, so a short period of bright light could be enough.

UpdateThere’s a lot more to supercaps than this…

As suggested by @jpc in a comment yesterday, I had a look at some documentation from Panasonic, in particular Part 2. And sure enough, they show that a supercap can be modeled as a whole set of capacitors in parallel, each with their own – often substantial – series resistance. It takes a while to “reach them” with charge, so to speak. Which explains why a long charge time increases the charge and voltage:

Screen Shot 2012 04 22 at 14 09 04

And which also explains why the supercap tends to drop quickly at first:

Screen Shot 2012 04 22 at 14 06 39

Having seen the discharge tail off much more than expected (i.e. flatten out and retain voltage), I can confirm that a supercap behaves considerably differently from a plain electrolytic capacitor.

The good news, is that for our intended purpose, this might actually work out quite well: a solar cell, keeping the supercap charged up fairly well most of the time, with just night-time JeeNode activity to drain the charge a bit, and occasional dark days, expecially in wintertime.

Update #2 – Three days have passed, and the voltage is still 3.23V, so T will be over 6 days, and the corresponding discharge rate even lower than estimated above. Bit of a puzzle – the discharge tails off considerably, apparently. Which is good news in fact, because that leaves more charge for a JeeNode to use. I’m ending this experiment for now: real-world testing with a JeeNode sending packets will be more useful.

To be continued…

Supercap discharge

In Hardware on Apr 22, 2012 at 00:01

Now that I have this super-high-impedance multimeter, it’s time to revisit the venerable supercap:

DSC 3057

That’s a whopping 0.47 Farad, the size of a little coin cell, and as you can see, this unit is rated 5.5V (most supercaps are 2.7V, I suspect that this is actually made of two 1F 2.7V units placed in series).

The beauty of a supercap is that it’s like a little battery, but with fewer limitations – you can’t really overcharge it, for one, because it doesn’t turn electric energy into chemical energy. There is no conversion: put 5V on it, and it’ll draw current and gobble up electrons until it reaches 5V, then it’ll stop.

So for example for solar-powered ultra-low power nodes, this could be a pretty nice solution. Solar cell -> diode -> supercap -> JeeNode. Max charge rate while the sun shines, and then it simply stops once the supercap is full. Only thing is to not exceed that 5.5V maximum, for which supercaps are very sensitive.

But there’s a problem. Supercaps can have a substantial self-discharge rate. When I connected 5.3V to it, the voltage immediately jumped to 5.3V, but when I disconnected that cable, it also dropped back to around 4.7V in just a few seconds – a normal capacitor sure isn’t supposed to work that way!

As it turns out, supercaps tend to “learn” to keep charge better over time. The longer you expose them to a voltage, the lower their self-discharge rate becomes. The isolation barrier needs time to build up, apparently (I’ve had this supercap on the shelf for over a year). Which is great, because presumably these cells would be kept charged most of the time, with the node only depleting them slightly when sending out a packet. So ideally, all we really need is for the supercap to retain enough energy overnight.

It’s time to put these unique components to the test!

The first encouraging fact is that indeed, when fed 5.1V for a couple of minutes, the discharge no longer jumps as radically when disconnected. It now drops to 5.03V in a few seconds, but tends to hold its value after that. So it does indeed look like these supercaps can be “taught” to better retain their charge.

This test is going to take some time. First thing I’m going to do is to just keep the supercap charged to 5.1V (note that the power supply voltage calibration is pretty good – slightly less so for the low mA’s):

DSC 3058

Let’s just leave it there to stabilize for about 24 hours. Stay tuned…

What does a BJT do?

In Hardware on Apr 21, 2012 at 00:01

And while we’re at it, let’s compare a regular transistor (a.k.a. BJT) to yesterday’s MOSFET.

Again a smal test setup, but this time it also needs a 10 kΩ resistor between input signal and base:

Screen Shot 2012 04 10 at 13 14 35

The reason for that extra resistor, is that the base of an NPN BJT is essentially connected to ground via what looks like a forward-biased diode. So the voltage on the base doesn’t normally rise above 0.7V. Without current limiting resistor, the transistor would get damaged (and perhaps also the source circuit into it).

Compare this to yesterday’s screen shot and you’ll see that a BJT behaves like a MOSFET, sort of:


The main difference is that the switching point is much lower, around 0.7V – which happens to be just about the point where the base-to-emitter junction starts to conduct.

Here’s the same as X-Y graph (with again the X axis adjusted to 500 mV/div for full scale):


Compared to the MOSFET, the switch-over is steeper, i.e. more like a digital on-off switch. Note also that although the base-to-emitter voltage will be at 0.7V, the collector-to-emitter voltage is in fact below that, almost zero!

What might not be immediately apparent from the above plot, is that a transistor has a much more linear behavior (even if steeper, i.e. with more amplification). In that small range between about 0.65V and 0.75V, it’s in fact a great linear amplifier – which is what transistors were initially used for, and on a huge scale.

A simple way to describe them is that BJTs are current-driven, whereas MOSFETs are voltage-driven.

For a nice article about how to use BJT’s for signal amplification, see this page on the PCBheaven website.

The BJT was at the start of the semiconductor revolution, decades ago. The MOSFET added a new and very different component, perfect for switching enormous loads with amazingly little power loss.

For the dual-voltage supply of a few days ago, either a MOSFET or BJT will probably work. With the BJT, there will be a higher residual voltage – so a check is needed to make sure it switches properly with a feedback pin voltage of only 0.41V. The MOSFET has no such issues, it’s essentially a controllable resistor: no bipolar junctions or diode-like behavior in sight.

What does a MOSFET do?

In Hardware on Apr 20, 2012 at 00:01

In a previous post, I mentioned using a MOSFET to short out a resistor. So how does that work?

Well, a MOSFET is like a voltage-controlled switch. To be more precise, an N-channel enhancement type MOSFET is like an infinite resistance when the gate-to-source voltage is zero, and turns into a very low resistance when the gate-to-source voltage is a few volts positive.

To examine this in more detail, I created a test setup like this:

Screen Shot 2012 04 10 at 03 22 50

By applying a linear ramp voltage on the gate, we can see what it does with varying voltages. When open, the output should be 5V, and when conducting, it should drop to almost 0V. Let’s examine this in real life:


The blue line is the input voltage on the gate (by definition a sloped straight line), and the yellow line is the voltage on the output (i.e. between drain and resistor). Let’s try and read this:

  • the gate voltage takes 10 divisions to reach 3V, so that’s 0.3 V/div
  • the MOSFET starts conducting at around 1.8V and is fully on at ≈ 2.4V
  • at slightly over 2.1V, the drain-to-source resistance is about 1 kΩ

The red trace is the derivative of the output, so the output change is maximal at just over 2.2V.

There’s no linear behavior, in terms of gate-to-source voltage (the derivative is never constant, except in the fully-open and fully-closed regions), but what you can see is that the MOSFET will switch just fine with a logic signal (anything switching between under 1.8V and over 2.4V will work perfectly).

There are more ways to look at this. Here’s an X-Y plot, with the linear ramp on the horizontal axis:


Note that – if you think about it – in X-Y mode, it doesn’t really matter what sort of signal is placed on the gate as long as it has the same voltage range. Here’s a sine wave to illustrate this perhaps somewhat surprising property:


It’s a good exercise to try and understand exactly why the two above screenshots are the same.

Lastly, here is a zoomed-in measurement, to get more precise data using the scope’s cursor features:


As you can see, a 0.33V change on the gate is all it takes between the “almost-OFF” and “almost-ON” states.

I’ll leave it as exercise for the reader to plot the resistance of this particular MOSFET at different gate voltages. With a bit more setup, the scope’s math functions should in fact be able to display that plot on-screen.

So there you have it: a MOSFET switches on voltage, and a scope + function generator makes it easy to see that behavior. Note that even without these instruments, with nothing more than a potentiometer and a multimeter, you could in fact derive exactly the same information. It would merely be a bit more work.

TK – Resolution vs accuracy

In Hardware on Apr 19, 2012 at 00:01

Welcome to the Thursday Toolkit series, about tools for building Physical Computing projects.

This episode is not about an instrument you will normally need, but about using a high-end unit.

Once you get into measuring instruments, there’s a trap – the kick of going after models which have more and more resolution and accuracy. First, let me explain the difference – i.e. roughly speaking:

  • resolution is the number of digits you can measure
  • accuracy is how close that value is to the real value

So you could have a 3-digit multimeter which is spot-on, and in most scenarios it’d probably be much more useful than a 5-digit multimeter which delivers meaningless results because it’s not properly calibrated.

The trouble with this search for perfection is that it can be addictive – see the time-nuts site for one example of keeping track of the EXACT time. Over the top for most mortals, but hey, I can relate to this sort of craziness :)

And recently I fell into the same trap. I’ve got quite a few hand-held multimeters, but when someone pointed out some eBay offers of a 6.5 digit HP/Agilent bench-top multimeter, I simply couldn’t resist and bought one:

DSC 3050

An amazing instrument – above it’s measuring between 1.8 and 2.0 µV with the probes shorted out. It’s a second-hand unit, probably from the 90’s, so it’ll be out of calibration by now. I could send it to a calibration lab, where they tweak the thing until it’s back to its sub-ppm accuracy, but that might well cost as much as what I paid for it. So for now I’ll just assume its accuracy is decent, perhaps in the 5-digit range. More than good enough for the experiments at JeeLabs anyway. This is all for fun, after all.

One of the interesting specs of this multimeter is a selectable input resistance of over 10,000 MΩ on DC ranges up to 10V. This extremely high value is great for measuring the leakage of a capacitor. Let’s try it:

  • first, a 47 µF 25V cap is charged to slightly over 5V for a few minutes
  • then, the power supply is disconnected and it starts discharging
  • finally, we measure the time it takes to discharge from 5V to 3.16V
  • this was determined to be well over six hours (I stopped waiting!)

I picked this voltage range because 3.16V is 63.2% of 5V, so the measured time corresponds to the time constant of the T = R x C formula for capacitor discharge. In other words:

  • 20000 s = R x 47 µF
  • therefore, the internal leakage resistance R = 20000 / 47 ≈ 425 MΩ
  • this translates to an internal leakage current of under 5 V / 425 MΩ ≈ 12 nA

So without even having an instrument which can measure such extremely low currents, we can arrive at an estimate of the leakage of this particular 47 µF 25V electrolytic capacitor, and under 12 nA is not bad!

Update – see the comments below, the leakage is even lower because the discharge should be measured to 1.84V iso 3.16V – so it’s well under 10 nA for this capacitor, in fact!

Two voltages

In Hardware on Apr 18, 2012 at 00:01

For a sensor I’ve been fooling around with, I needed a supply which can switch between 5V and 1.4V, supplying up to about 200 mA.

There are several ways to do this, but I decided to use the MCP1825 adjustable voltage regulator:

Screen Shot 2012 04 07 at 13 05 57

The trick is to create an adjustable voltage divider, using a MOSFET to short out one of the resistors:

Screen Shot 2012 04 07 at 13 12 03

When off, the MOSFET does nothing, with R2 and R3 in series. When on, R3 is essentially shorted out.

The regulator varies its output voltage (top of R1) such that the level between R1 and R2 always stays at 0.41V:

Screen Shot 2012 04 07 at 13 16 18

So the task is to come up with suitable values for R1, R2, and R3. Let’s start with the 5V output and R1 = 10 kΩ:

  • 5V = 0.41V x (10 kΩ + R2) / R2
  • then 5 x R2 = 0.41 x (10,000 + R2) = 4,100 + 0.41 x R2
  • and 5 x R2 – 0.41 x R2 = 4,100, i.o.w. 4.59 x R2 = 4,100
  • that would make R2 = 4,100 / 4.59 = 893 Ω

Now for the 1.4V output level (where R2′ is R2 in series with R3):

  • 1.4V = 0.41V x (10 kΩ + R2′) / R2′
  • then 1.4 x R2′ = 0.41 x (10,000 + R2′) = 4,100 + 0.41 x R2′
  • and 1.4 x R2′ – 0.41 x R2′ = 4,100, i.o.w. 0.99 x R2′ = 4,100
  • that would make R2′ = 4,100 / 0.99 = 4141 Ω

But that’s not quite right, because R2 and R2′ have to be in the range 10 .. 200 kΩ. This is easy to fix by making R1 = 220 kΩ. Then the above values all increase by a factor 22 as well – bringing both R2 and R2′ nicely in range:

  • for 5V: R2 = 19.6 kΩ
  • for 1.4V: R2′ = 91.1 kΩ

IOW, two resistors of 19.6 kΩ and 71.5 kΩ in series would work, whereby the 71.5 kΩ resistor can be shorted out with the MOSFET to take it out of the loop.

These are not very convenient values, for resistors in the E12 series – let’s try and improve on that. After all, we can choose these values any way we like, as long as their relative values stays the same. With 15 kΩ and 54.7 kΩ, R1 would have to be 168 kΩ. That’s not so bad, we could use 15 kΩ, 56 kΩ, and 68 kΩ in series with 100 kΩ, resp.

Or, better still, perhaps: 19.6 kΩ ≈ 10 + 10 kΩ, and 71.5 kΩ ≈ 33 kΩ + 39 kΩ. With R1 kept at 220 kΩ. This needs 5 resistors in total to get the desired results. Now let’s try it out for real, eh?

DSC 3037

Yippie – it works! Voltages with 200 mA load are 1.38 V and 4.89 V, respectively – close enough.

With 5 V input, the output is still 4.86 V @ 200 mA, proving that the MCP1825 is indeed a low-dropout regulator. The switching edges look clean on the oscilloscope, with rise and fall times of ≈ 30 µs (1 µF cap charge/discharge).


Weblog post 1000 !

In News, Musings on Apr 17, 2012 at 00:01

Today is a huge milestone for JeeLabs. This is weblog post number:

Screen Shot 2012 04 16 at 17 15 32


It all started on October 25th in 2008, with a weblog post about – quite appropriately – the Arduino.

Then it took a few more months to evolve into a daily habit, and yet another few months to set up a shop, but apart from that it has all remained more or less the same ever since.

You might have been following this from the start, and you might even have been going through the long list of daily posts later, but there you have it – a personal account of my adventures in the world of Physical Computing. If anything, these years have been the source of immense inspiration and delight. I’ve been able to re-connect to my inner geek, or rather: my inner ever-curious and joyful child. And to so many like-minded souls – thank you.

“Standing on the shoulder of giants” is a bit over-used as a phrase, but it really does apply when it comes to technology and engineering. What we can do today is only possible because many generations of tinkerers, inventors, and researchers before us have created the foundations and the tools on which we can build today. It feels silly even to try and list them – such a list would be virtually endless.

I’m not a technocrat. I think our IT world has done its share to rob people of numerous meaningful and competence-building jobs, and to introduce new mind-numbing and RSI-inducing repetitive tasks. Our (Western) societies have become de-humanized as more and more screens take over in the most unexpected workplaces, and our car trips and train rides are turning us into very selectively-social beings, reserving our emotions but even our respect and courtesy for our families and the people we choose as our friends. Technology’s impact on daily life is a pretty horrible mess, if you ask me.

But what drives me, are the passion and the creativity and the excitement in the field of technology. Not for the sake of technology, but because that’s one of the major domains where cognition and rationality have free reign. You can learn (and reason) all about history, medicine, psychology, or you can invent (and reason about) things which do new things, be it electrical, mechanical, biological, informational, or otherwise. Technology as a source of boundless evolution and innovation is breath-taking, we “merely” have to tap it and put it to good use.

And what thrills me most is not what I can do in that direction, but what others have done in the past and are still doing every day. Learning about all that existing technology around us is like looking into the minds of the persons who came up with all that stuff, feeling their struggles, their puzzles, and ultimately the solutions they came up with. I’m in awe of all the cleverness that has emerged before us, and even more in awe of the thought that this will no doubt go on forever.

It’s really all about nurturing curiosity, asking questions, and solving the puzzles they bring to the surface:

I have no special talents. I am only passionately curious. — Albert Einstein

Here’s the good news: we all have that ability. We all came into the world the same way. We can all be explorers.

If you start doing this early on in life and hold onto it, you’ll never be hungry and you’ll never get bored. And if you didn’t have that opportunity back then: nothing of substance prevents you from starting today!

We live in amazing times. Ubiquitous internet and access to knowledge. Open source Physical Computing. Online communities with a common language. This weblog is simply my way of reciprocating all these incredible gifts.

Lithium theatrics

In Hardware on Apr 16, 2012 at 00:01

As an alternative to supercaps, I recently ordered a Lithium rechargeable battery from Digikey:

ML614 TZ21

It’s not quite what you might think, though: its size is only 6.8 x 1.4 mm, with a tiny 3.4 mAh capacity :)

Got ten of them, as part of a larger order, and they came packaged as follows:

DSC 3039

So far so good, but now the crazy part. These batteries were sent out in a separate 23x23x5 cm box:

DSC 3040

With a warning label …

DSC 3041

… and another warning label:

DSC 3042

The max discharge current of these things is 1.5 mA according to the specs. I doubt they’ll even go up to 15 mA when shorted! By the way, does that dented corner qualify as “damaged” ? … I want my money back! :)

Get real – or better still, read Bruce Schneier‘s works!

PS. Please don’t get me wrong: fire risks are very real – it’s just that the above cells have virtually no energy…

Learning to program

In News, Software on Apr 15, 2012 at 00:01

As it so happens, someone very recently brought to my attention a site called, which announces itself as simple and as clearly as can be:

Free online university classes for everyone.

It’s a phenominally exciting initiative, second only to the Khan Academy, if you ask me:

Screen Shot 2012 04 14 at 21 23 47

The idea: great video lectures plus exercises to let anyone with (good) internet access learn some major topic really well. You have to be fluent in English, evidently, but apart from that the courses seem to be designed to give the broadest possible group of people access to this new form of – literally! – world-class education.

These guys are serious. With a pool of well-known researchers and teachers and set up to scale massively (the class on Artificial Intelligence which led to all this had over 160,000 people signed up).

For some background info about this project, see these Hack Education and Reuters articles.

The format is slightly different from the Khan Academy in that the courses start on a fixed date and have a fixed duration. So you really have to “sign up” for class if you want to benefit from what they have to offer.

As it so happens, these classes start tomorrow, Monday, April 16th and they will last for 7 weeks.

It looks like there will be a bunch of videos each week, plus some homework assignments, which you can then follow whenever you have time that week. You can enroll in multiple courses, but I’m sure they will be repeated at a later date, so it’s probably best to just pick what feels like a good match right now.

What can I say? IMO, this is a unique chance to learn about modern software programming on many levels. Whether you’ve never built any software or whether you are curious about how some really sophisticated problems can be solved, these six courses cover a breathtaking range of topics.

I don’t know how these courses will turn out, but I do know about some of the names involved, and frankly, I’d have loved to have this sort of access when starting out in programming.

FWIW, out of curiosity, I’ve signed up for CS101. What a nice birthday present.

There has never been a better time to learn than now. This world will never be the same again.

Reading out DHTxx sensors

In Software on Apr 14, 2012 at 00:01

The DHT11 and DHT22 sensors measure temperature and humidity, and are easy to interface because they only require a single I/O pin. They differ in their measurement accuracy, but are in fact fully interchangeable.

There is code for these sensors floating around on the web, but it all seems more complicated than necessary, and I really didn’t want to have to use floating point. So I added a new “DHTxx” class to JeeLib which reads them out and reports temperature in tenths of a degree and humidity in tenths of a percent.

Along with a new demo sketch called dht_demo:

Screen Shot 2012 04 02 at 03 40 38

That’s about as simple as it gets, and it compiles to less than 4 KB.

Sample output, in this case a DHT11 which only reports whole degrees and percentages:

Screen Shot 2012 04 02 at 03 26 05

Humidity is gradually shooting up as I breathe next to it (there’s a slight lag).


Analog Plug readout

In Software on Apr 13, 2012 at 00:01

The analog plug contains an MCP3424 4-channel ADC which has up to 18 bits of resolution and a programmable gain up to 8x. This can measure microvolts, and it works in the range of ± 2.048 V (or ± 0.256 V for 8x gain).

However, the analog_demo example sketch was a bit limited, reading out just a single fixed channel, so I’ve added a new AnalogPlug class to JeeLib to simplify using the Analog Plug hardware. An example:

Screen Shot 2012 04 01 at 21 10 25

This interfaces to an Analog Plug on port 1, and uses 0x69 as default I2C device address. There are a number of ways to use this, but if you want to read out multiple channels, you have to select the proper channel and then wait for at least one conversion to complete. Since conversions take time, especially at 18-bit resolution, a delay() is needed to get proper results.

Sample output:

Screen Shot 2012 04 01 at 21 18 18

I tied a 1.5V battery to channel 1 and left the rest of the pins unconnected. Touching both battery pins lowers the voltage briefly, as you can see.

These results are in microvolts, due to this expression in the code:

    long uvolts = ((adc.reading() >> 8) * 1000) / 64;

Here’s the reasoning behind this formula:

  • the reading() call returns 32 bits of I2C data, but we only need the first 24 bits
  • of these 24 bits, the first 6 will simply be a sign-extended copy of bit 18
  • the top of the measurement range is 2.047 Volts, i.e. 2047 millivolts
  • but we want to report in terms of microvolts, so we multiply by 1000
  • only 11 bits are needed to represent 0 .. 2047 mV, the remaining 6 bits are fractional
  • so we shift right by 6 bits (i.e. divide by 64) to get the actual result

It’s a bit convoluted, but as you can see, the measured value comes out as about 1.477 Volts, with a few more digits of resolution. If you do the math, you’ll see that the actual “step” size of these measurements is 1000 / 64 = 15.625 µV – and it drops to under 2 µV when used with 8x gain!

With this sort of precision, electrical noise can easily creep in. But it’s pretty neat: 5 digits of precision for 4 channels, with nothing more than one teeny little I2C chip.

TK – Resistors

In Hardware on Apr 12, 2012 at 00:01

Welcome to the Thursday Toolkit series, about tools for building Physical Computing projects.

Yet another useful package from Conrad (NL #418714) – a set of 390 resistors from 10 Ω through 1 MΩ:

DSC 3048

Resistors come in specific values and are based on a logarithmic range, i.e. you’ll see them organized as “E6”, “E12”, or “E24”, meaning that they are split up into 6, 12, or 24 values per decade, respectively.

Here’s some info about what’s in that above box:

Screen Shot 2012 03 29 at 13 11 35

This is actually mostly a subset of the E6 range (which is 10, 15, 22, 33, 47, 68) – see this Wikipedia article about preferred numbers for how and why things are organized that way.

The point is that you can never have enough resistors, which can probably be considered to be the most elementary components in electronics. Whether for limiting the current through a LED or creating a voltage divider, these things just tend to get used all over the place.

But what if you need a different value? Well, that’s often trivial: by using two resistors, either in series or in parallel, it’s often possible to get real close to the value you’re after.

The formula for two resistors in series is simply the sum of their values:

    Rseries = R1 + R2

The formula for two resistors in parallel is slightly more complicated:

    Rparallel = (R1 x R2) / (R1 + R2)

(this can easily be explained using Ohm’s law, I’ll be happy to write a post about this if you’re interested)

Here’s an online calculator which will find the proper values – although I recommend doing the math yourself, at least initially, because it will help you get a good grasp of how resistors work together.

EtherCard improvements

In Software on Apr 11, 2012 at 00:01

This has been an often-requested feature, so I’ve added a way to get an Ethernet reply back after you call tcpSend() in the EtherCard library:

Screen Shot 2012 04 01 at 15 08 44

The one thing to watch out for, is that – over time – packets going out and coming back are going to interleave in unforeseen ways, so it is important to keep track of which incoming reply is associated to which outgoing request. Fortunately, the EtherCard library already has some crude support for this:

  • Each new tcpSend() call increases an internal session ID, which consist of a small integer in the range 0..7 (it wraps after 8 calls).
  • You have to store the last ID to be able to look for its associated reply later, hence the “session” variable, which should be global (or at least static).
  • There’s a new tclReply() call which takes that session ID as argument, and returns a pointer to the received data if there is any, or a null pointer otherwise. Each new reply is only returned once.

A simple version of this had been hacked in there in a Nanode-derived version of EtherCard, so I thought I might as well bring this into the EtherCard library in a more official way.

This code – the whole EtherCard library in fact – is fairly crude and not robust enough to handle all the edge cases. One reason for this is that everything is going through a single packet buffer, since RAM space is so tight. So that buffer gets constantly re-used, for both outgoing and incoming data.

Every time I go through the EtherCard code, my fingers start itching to re-factor it. I already did quite a few sweeps of the code a while back as a matter of fact, but some of the cruft still remains (such as callback functions setting up nested callbacks). It has to be said though, that the code does work pretty well, with all its warts and limitations, and it’s non-trivial, so I’d rather stick to hopping from one working state to the next, instead of starting from scratch, working out all the cases, and tracking out all the new bugs that would introduce.

The biggest recent change was the addition of a “Stash” mechanism, which is a way to temporarily use the RAM inside the ENC28J60 Ethernet controller as scratchpad for all sorts of data. Its already useful in its current state because it lets you “print” data to it in the Arduino way to construct a request or a reply for an Ethernet session.

There are a few more steps planned, with as goal to avoid the need to have a full packet buffer in the ATmega’s RAM. Once that goal is reached, it should also become possible to track more than one session at the same time, so that more frequent requests (in and out) should be possible. There is no reason IMO, why an ENC28J60-based Ethernet board should be much less capable than a Wiznet-based one (apart from needing a bit more flash memory for the library code, and not supporting multi-packet TCP sessions).

The remaining steps to get away from the current high demands on RAM space are:

  • generate the final outgoing packet directly from one or more stashes, without going through our RAM-based buffer
  • collect the incoming request into a stash as well, again to avoid the RAM buffer, and to quickly release the receiver buffer again
  • reduce the RAM buffer to only store all the headers and the first few bytes of data, this should not affect all too much of the current code
  • add logic to easily “read” incoming data from a stash as an Arduino stream (just as “writing” to a stash is already implemented)

Not there yet, but thinking this through in detail is really the first step…

TD – Infrared Remote

In Hardware on Apr 10, 2012 at 00:01

Welcome to the Tuesday Teardown series, about looking inside the technology around us.

Steve (@tankslappa) recently sent me two spare IR remotes he had lying around. Very joyfully and gratefully accepting his generous gift, I decided to tear one down to see what makes these things tick:

DSC 3043

Frightfully little, I’m afraid. Just a single SOIC-20 type IC! Marked “DUSUN021” and “1003” (3rd week 2010):

DSC 3044

The switches are custom-designed, using a silicone mat with buttons, each of them holding some sort of little carbon-lined conducting pad. When pressed, they connect two traces on the PCB and that’s it!

Oh, wait, the other side has two more components and some simple battery clips:

DSC 3045

The electrolytic cap just helps the battery supply power for IR LED, I presume, while the other component is a cap 3.45 MHz resonator, and part of the frequency-generating circuit.

Here is a scope trace of the emitted IR light when pressing a single button:


This was picked up with an AMS302 light sensor, BTW. You can see the two pulse trains, i.e. the button press gets repeated twice. Perhaps not as easy to see, is the fact that “ON” is not represented by a simple IR pulse, but by a pulse train. This allows the receiver to filter out noise and random pulses, by filtering and detecting pulses only when modulated in this way.

As you can see in the zoomed-in section, the pulse train consist of turning the IR LED on and off at a 36 KHz rate.

This is within the detection range of the TSOP34838 IR receiver, as used on the Infrared Plug, even though that receiver is optimized for 38 KHz modulation. Don’t be put off by the term “modulation” in this context, BTW – it simply means that the 38 KHz frequency used to drive the IR LED is turned on and off in a certain pattern.

Each key has its own pattern. This remote appears to use the RC5 protocol. Here’s a snapshot of one keypress using the TSOP34838 chip, which detects, demodulates, and then outputs a clean logic signal:


I’ve enabled the tabular pulse search listing, which gives us information about the encoding used by this remote:

  • 829 µs for a short “OFF”
  • 953 µs for a short “ON”
  • 1738 µs for a long “OFF”
  • 1752 µs for a long “ON”

Decoding such a pulse train is fairly easy, and as you can see, the component count for such IR transmissions is extremely low and hence very low-cost. Which also explains the popularity of this system!

PS. I’ve switched to light oscilloscope screen shots as a trial. The colors are not as pronounced, but it seems to be a little easier on the eyes. Here’s the same info, in the dark version as it shows on-screen:


Do I need an oscilloscope?

In Hardware on Apr 9, 2012 at 00:01

As I’ve mentioned before, an oscilloscope is a pretty nifty piece of test equipment. It can also be very expensive.

The following comment in my series on oscilloscopes is still a good summary of what it’s all about, IMO:

Oscilloscopes are the “printf” of the electronics world. Without a “scope” you can only predict and deduce what’s happening in a circuit, not actually verify (let alone “see”) it. Here’s what an oscilloscope does: on the vertical axis, you see what happens, on the horizontal axis you see when it happens. It’s a voltmeter plus time-machine.

That doesn’t mean you can’t get anything done in Physical Computing without one. A simple multimeter is a lot cheaper and will get you a long way in figuring out the electrical behavior of a circuit – not to mention finding shorts and connection mistakes. So the first thing to get is a multimeter, not a scope. Always.

The trouble is that ATmega’s are so friggin’ darn fast. We can’t observe events on their time scale, and more importantly: many problems will zoom past us and get lost before we have a chance to see anything!

So I’m going to revise my advice about oscilloscopes somewhat: if you solder together kits and basic components, then yeah, a multimeter is plenty. But if you hook up non-trivial chips and need to debug the combination of hardware and software, then you really need all the help you can get. Be it a logic analyzer for digital signals, buses, and pulse-trains, or a scope to investigate the electric behavior of a fast circuit.

Note that a logic analyzer can be a lot cheaper than a scope. The reason being that they are electrically much simpler – they just need to collect a bunch of digital logic levels (rapidly), whereas a scope needs to collect much richer signals (ranging from millivolts to hundreds of volts, and with all sorts of signal processing to make sure you’re seeing the real thing and not some artifact of the instrument itself).

If you’ve been following this weblog a bit, you’ll have seen quite a few scope screen shots in some of the posts. One of the most important uses for my scope here at JeeLabs is to figure out power consumption while trying to optimize a JeeNode’s ultra-low power mode. Power consumption is an analog thing, so that’s where a scope comes in. And when you look at the amount of detail a modern scope can show, it’s clear that this level of insight really comes from such an instrument. See the recent Watchdog tweaking and Room Node analysis for some examples.

Does that mean you have to shell out a few thousand dollars to do something similar? Not at all.

First of all, visualization isn’t everything. A couple of years ago, I used one JeeNode to measure the power consumption of another JeeNode, see the Power consumption tracker post, and the software for it. Less insight perhaps, and no geeky screen shots, but plenty of info to try and optimize the power consumption by trial-and-error. Just tweak your sketch and measure, over and over again.

Second point I’d like to make, is that such power measurements are fairly slow, so any scope will do. Even a 10 MHz model will be able to accurately display changes from one microsecond to the next.

There are a couple of ways to get such a “low-end” scope (don’t let that term fool you, any oscilloscope can be extremely useful as long as things don’t change too fast):

  • Look for a second-hand unit, lots of them can often be found on eBay.
  • Consider getting a USB-connected scope such as the DSO-2090.
  • For PC’s there is software to create a basic scope using the sound card.
  • Check out the ultra-tiny Xmegalab, its under $50 (plus shipping).

These last two options are lower cost, but more limited since they don’t really include a full “front-end” to handle a wide range of input voltages. For circuits with only a few volts, they may still be sufficient.

Normal “sweeping” analog scopes are ok, but storage scopes (analog or digital) are considerably better because you can “capture” an event and keep it on the screen to investigate. Such a feature will cost more though.

Here’s an example of how a €100 second-hand Tek 475 (analog & non-storage) scope can be used to measure that same power consumption as in the Watchdog tweaking post – it’s the same waveform:

DSC 3023

Two essential tricks were used: 1) the watchdog is firing at ≈ 60 Hz, so the scope trace fires constantly, and 2) it triggers on one pulse but displays the next one, using x10 horizontal magnification.

The above screen shows 2 mA and 200 µs per division. The vertical scale could have been zoomed in further, but for the horizontal scale I’m sort of at the limit unless I start using delayed sweeps. Here’s the whole unit:

DSC 3014

No storage, no screen capture, no USB, so this was done by darkening the room and holding a camera in front of the scope. It took a couple of tries, but hey – it is possible to estimate power consumption this way!

What I’m trying to say is that you too can do this sort of work with an investment of €100 to €150.

If you intend to do more with electronics (and let me assure you: this sort of fooling around is geek heaven, and addictive!) – then consider holding off just a bit longer if need be, and save up for a Rigol or Owon scope. These “DSO’s” are mature, have tons of useful features, and they can store lots of detail (that’s the “S” in DSO).

Is this a case of “if you have a hammer then everything starts looking like a nail”? All I know is that my insight in ultra-low power consumption and optimization has increased significantly since getting an oscilloscope.

Electricity consumption

In Hardware on Apr 8, 2012 at 00:01

Came across this graphic a while ago – US energy cost and consumption over the years:

Screen Shot 2012 03 27 at 18 44 08

For comparison, in 2012, electricity here costs ≈ €0.21 (i.e. $0.28) per kWh, including taxes.

Our usage (i.e. Liesbeth’s and mine) was about 3000 kWh in 2011. That includes electric cooking, but note that heating and warm water is provided through natural gas.

That puts us in the late 1950’s w.r.t. US electricity consumption levels – yo, Elvis! :)

I’ve started to get involved in a local initiative (see this Dutch website if you’re interested – “duurzaamheid” is all the rage these days, it seems), with all sorts of simple and not-so-simple ways planned 1) to consume less, 2) to switch to renewable sources, and 3) to fall back to natural resources for the rest. It’s not an all or nothing game, more a way to plot a practical trajectory for improving things over the next couple of years.

Here’s the JeeLabs neighborhood:


Lots of space to catch some sunlight on all those rooftops – but careful with that chimney’s shadow!

Now that solar energy has become so cheap (Wp prices including inverter have dropped below €1.70), we’re finally getting together with a couple of neighbors here to actually make it happen. This year, and hopefully before the summer is gone again!

The aim is to try and get 4000 to 5000 Wp onto our roof (16..21 panels of 100×160 cm), which would cover for our entire yearly electricity needs, even without pushing for further savings. For the 52°N latitude of the Netherlands, panel + inverter efficiencies are estimated in the 80..85% range, nowadays.

That’s just half the story, gas consumption is the other biggie – but hey, ya gotta’ start somewhere, eh?

Trying to measure capacitor leakage

In Hardware on Apr 7, 2012 at 00:01

Capacitors have a “leakage current”, i.e. when you charge them up fully, the leakage current will cause them to slowly lose that charge. I was wondering about this in the context of an ultra-low power JeeNode, which has a 10 µF buffer cap right after the voltage regulator. Does its leakage affect battery lifetimes?

Time to do a quick test – I used the 47 µF 25V cap included with JeeNode kits these days:

DSC 2981

So how do you measure leakage currents, which are bound to be very small at 3.3V? Well, you could charge up the cap and then insert a multimeter in series in its most sensitive range. This multimeter goes down to 0.1 µA resolution, although its accuracy is specified as 1.6 % + 5 digits, so the really low values aren’t very precise.

A simpler way is to use the RC time constant as a basis. The idea is that a real-world cap can be treated like a perfect cap (which would keep its charge forever) plus a resistor in parallel. That resistor merely “happens” to be situated inside the cap.

What I did was charge the cap from a 3x AA battery pack which was just about 4.0V, then disconnect the battery and watch the discharge on the oscilloscope:


As you can see, it took 500 seconds for the charge in the capacitor to drop by some 2.5V – note the exponential decay, which matches the assumption that the leakage comes from a fixed resistance.

Can we derive the leakage from this? Sure we can!

The formula for RC discharge is:

    T = R x C

Where T (in seconds) is the time for the cap to discharge by 63.2 percent, R is the discharge resistor (in ohms), and C is the capacitor size (in farads).

Above, it took 500 seconds to drop from 3.98 V to 1.48 V, which by pure accident is almost exactly 63.2 %, so T = 500 and C = 0.000,047 – giving us all the info needed to calculate R = 500 / 0.000,046 = 10638298 ≈ 10.6 MΩ.

Using ohm’s law (E = I x R), that means the leakage current at the start is 4 V / 10.6 MΩ = 0.376 µA.

The good news is that such a result would not be of any concern with ultra-low power JeeNodes – the regulator + ATmega + RFM12B use an order of magnitude more than that, even when powered down.

But the bad news is that this result is in fact completely bogus: to measure the charge, I placed the oscilloscope probe over the cap, and it happens to have 10 MΩ internal resistance itself. So basically the entire discharge behavior shown above was caused by the probe i.s.o. the capacitor’s own leakage!

So it looks like I’ll need a different setup to measure real leakage, which is probably in the nanoamp range…

Hameg scope update

In Hardware on Apr 6, 2012 at 00:01

The Hameg HMO2024 scope just got a firmware upgrade – wow, it just keeps getting better and better.

Support for up to 6 calculated values (was 2), based on any of the input channels – now with optional statistics:


And one of the things I really missed dearly – the ability to see all decoded serial data in tabular form:


The top two traces show the SCL and SDA data in analog form, the next group is the color-coded serial data, and at the bottom is the list of packets. As you scroll through the table, the traces adjust to show the related information. Still shown at the bottom are the 6 auto-measured items I configured in the first screen.

Last big new feature is the capability to search through stored traces, again with a table to help navigation:


It’s all firmware, evidently, but I hadn’t expected the development to keep on moving the capabilities of this oscilloscope forward to such an extent. And these aren’t just gimmicks, such features can be extremely useful!

TK – Burden voltage

In Hardware on Apr 5, 2012 at 00:01

Welcome to the Thursday Toolkit series, about tools for building Physical Computing projects.

Two weeks ago, I extolled the virtues of the multimeter for measuring various electrical units.

With voltages, things are very simple: you’ve got two probes, and you can stick them anywhere in your circuit to measure the voltage potential difference between two points. The input impedance of any modern multimeter is usually 10 MΩ or more, which means the load caused by measuring is neglegible in just about all cases.

Let’s apply Ohm’s law: 10 MΩ over 1V is just 0.1 µA current, and over 230V it’s still just 23 µA current.

But with current measurements, things change: a multimeter in current measurement mode is essentially a short. You place the probe pins between the supplier and consumer of current to measure the Amps, milliamps, or microamps. That also means you can’t just go probing around at random: sticking the probes between + and – of a power supply, or even just a battery, basically creates a short. The result is a huge current, which will blow the internal fuse of the multimeter. Very often, the fuse is a 500 mA type (to protect a 400 mA range).

That’s why the VC170 (left) is better than the VC160 (right) – voltage and current are on different jacks:

DSC 2979

But there’s another aspect of current measurement with multimeters to be aware of: burden voltage.

When measuring current, multimeters insert a small resistance in series with the load, i.e. between the two probe pins, and then work by measuring the voltage drop across them (Ohm’s law, again!).

So placing multimeter between current supplier and consumer actually introduces a small voltage drop. How much? Well, that depends both on the multimeter and on the selected range.

Here’s the VC170 with a 1 mA current through it – in its 400 mA range:

DSC 2977

I used the VC160 multimeter to measure the voltage over the VC170 multimeter, which is in current measurement mode. This is one example why having several multimeters can come in handy at times.

Not bad – roughly 1 mV to measure 1 mA, so the burden resistor in this unit for the 400 mA range is somewhere around 1.3 Ω. Note also that with 400 mA, the voltage drop will rise to over 500 mV!

Let’s repeat this with the VC170 in µA range, i.e. measuring up to 4000 µA:

DSC 2978

Hmmm… the voltage drop with 1 mA is now 100 mV, i.e a 100 Ω burden resistor. Not stellar.

Why is this a problem? Let’s take an example from the JeeNode world: say you want to measure the current consumed by the JeeNode once it has started up and entered some sort of low-power state in your sketch. You expect to see a few µA, so you place the multimeter in µA mode.

The JeeNode starts up, powered from say a 3.6V 3x AA battery pack with EneLoops. It starts up in full power mode, briefly drawing perhaps 10 mA. You’ve got the multimeter in series, which in µA mode means that you’ve got a 100 Ω resistor in series with the battery.

The problem: at 10 mA, a 100 Ω resistor will cause a 1V drop (BTW, make sure you can dream these cases of Ohm’s law, it’s an extremely useful skill). That comes out as 100 V/A burden voltage.

So the battery gives out 3.6V, but only 2.6V reaches the JeeNode. Supposing its ATmega is set to the default fuse settings, then the brown-out detector will force a reset at 2.7V – whoops! You’re about to witness a JeeNode constantly getting reset – just by measuring its current consumption!

In the 400 mA range, the voltage drop at 10 mA will be 13 mV and affect the circuit less (1.3 V/A burden voltage).

The good news is that the multimeter still does auto-ranging. As you can see in the above example, 1 mA is shown with 2 significant decimals, so it’s still possible to read out ± 10 µA in this mode (don’t assume it’ll be accurate beyond perhaps ± 30 µA, though).

Can this problem be avoided? Sure. Several ways:

  • stick to the higher current ranges, even if that means you can’t see low values very precisely
  • add a Schottky diode in forward mode over the multimeter – this will limit the voltage drop to about 0.3V, even during that brief 10 mA startup peak
  • get a better instrument – this is easier said than done, most multimeters have a 1..100 V/A burden voltage (!)
  • look at Dave Jones’ µCurrent adapter, which converts low currents to a decent ± 1V range with only 0.07 V/A burden voltage

One caveat with Dave’s solution is that it is never in stock. I’ve been trying to get one for years without luck. He occasionally gets new ones made, but they tend to sell out within nanoseconds, AFAICT!

PortI2C – C++ syntax

In Software on Apr 4, 2012 at 00:01

To finish last week’s discussion about C++ classes for I2C buses and devices – here’s the nasty bit… syntax!

The PortI2C class is defined as follows in Ports.h (I’ve omitted some of the internal details):

    class PortI2C : public Port {
        enum { KHZMAX = 1, KHZ400 = 2, KHZ100 = 9 };

        PortI2C (uint8_t num, uint8_t rate =KHZMAX);

        uint8_t start(uint8_t addr) const;
        void stop() const;
        uint8_t write(uint8_t data) const;
        uint8_t read(uint8_t last) const;

Couple of things to note:

  • PortI2C is a subclass of Port (defined here), which handles raw I/O for one port (1..4 or 0)
  • there’s an “enum” which defines some constants, specifically for PortI2C use
  • there’s a “constructor” which takes two arguments (the second one is optional)
  • there are four member functions available to any instance of class PortI2C

But that’s not all. Since PortI2C is a subclass of public Port, all the members of the Port class are also available to PortI2C instances. So even when using a PortI2C instance as I2C bus, you could still control the IRQ pin on it (mode3(), digiWrite3(), etc). An I2C port is a regular port with I2C extensions.

Note this line:

    PortI2C (uint8_t num, uint8_t rate =KHZMAX);

This is the constructor of the PortI2C class, since it has the same name as the class. You never call it directly, it gets called automatically whenever a new instance of PortI2C is declared.

This constructor takes one or two arguments: the last argument can be omitted, in which case it will get a default value of KHZMAX, which is the constant 1, as defined in the preceding enum.

Note that the first argument is required. The following instance declaration will generate a compile error:

    PortI2C myPort; // compile-time error!

There’s no way to create an instance of a port without specifying its port number (an int from 1 to 4, or 0). Instead, you have to use either one of the following lines:

    PortI2C myPort (3);                  // this defaults to KHZMAX ...
    PortI2C myPort (3, PortI2C::KHZ400); // ... or you can specify the rate

And this is where things get nasty: PortI2C is a subclass of Port, which also has a constructor requiring a port number. So the PortI2C constructor somehow has to pass this information to the Port constructor. To see how this is done, look at the PortI2C constructor function, defined in Ports.cpp:

    PortI2C::PortI2C (uint8_t num, uint8_t rate)
        : Port (num), uswait (rate)

This is the PortI2C constructor, and welcome to the murkier side of C++:

  • “PortI2C::PortI2C” is the way to refer to PortI2C’s constructor function
  • “blah::blah (…) : Port (…) { … }” is how the Port subclass constructor gets called
  • “blah::blah (…) : uswait (…) { … }” is used to initialize the “uswait” member variable
  • note that the “=KHZMAX” optional value for the 2nd arg is not repeated in this code

To summarize: the above code is called when you create a instance (such as “PortI2C myPort (3);”), and what it’ll do (in that order), is:

  • initialize the included Port instance it is based on, passing it the 1st arg
  • set the uswait member variable (which is part of the PortI2C instance) to the 2nd arg
  • call sdaOut(), mode2(), and sclHi(), all defined in the Port and PortI2C classes

It gets worse. Let’s have a look at the definition of class DeviceI2C:

    class DeviceI2C {
        const PortI2C& port;
        uint8_t addr;

        DeviceI2C(const PortI2C& p, uint8_t me)
          : port (p), addr (me << 1) {}

        bool isPresent() const;
        uint8_t send() const { ... }
        uint8_t receive() const { ... }
        void stop() const { ... }
        uint8_t write(uint8_t data) const { ... }
        uint8_t read(uint8_t last) const { ... }
        uint8_t setAddress(uint8_t me) { ... }

DeviceI2C is not a subclass, but it does need to refer to the PortI2C instance specified as 1st argument and remember the bus address. The way this is done is through member variables “port” and “addr”. These are defined at the top of the class, and initialized in the DeviceI2C constructor.

The reason we can’t use subclassing here, is that a device is not a port, it’s merely associated with a port and I2C bus, since multiple devices can coexist on the bus. The “&” notation is a bit like the “*” pointer notation in C, I’ll refer you to C++ language documentation for an explanation of the difference. It’s not essential here.

Not being a subclass of PortI2C, means we can’t simply send I2C packets via send(), write(), etc. Instead, we have to go through the “port” variable. Here’s the above write() member function in more detail:

        uint8_t write(uint8_t data) const { return port.write(data); }

In other words, instead of simply calling “write()”, we have to call “port.write()”. No big deal.

So much for the intricacies of C++ – I hope this’ll allow you to better read the source code inside JeeLib.

TD – PC Power Supply

In Hardware on Apr 3, 2012 at 00:01

Welcome to the Tuesday Teardown series, about looking inside the technology around us.

Well, not a very “deep” teardown, just opening it up and looking inside a conventional 400W PC power supply:

DSC 3003

When turned on, but not powered up, the power cunsumption is a substantial 2.8 W. IOW, that’s your computer when turned off. But the nasty surprise was that even with the mechanical switch in the off position, it still draws 0.04 W? Oh well, the sticker says “2006”, so let’s assume things have improved since then.

Here’s the top view inside:

DSC 3004

Two large heatsinks with two fans blowing air across, the bottom fan is on the outside of the case.

These caps scare me, I had it powered up briefly, so I’d probably get a jolt if I were to touch them now:

DSC 3005

Two small transformers in there, on the right. And here are three more:

DSC 3006

One last toroidial one in where the main circuitry appears to be – note the one-sided PCB with jumpers:

DSC 3007

And that board at the right is filled with varicaps, etc – noise and surge suppression, no doubt:

DSC 3008

Found a schematic of a 200 W supply on this website:


Go to the website for the full-size view. Looking at the number of transformers, this supply is probably similar. The basic idea is simple: generate a high-frequency AC signal, and feed it through some transformers for galvanic isolation and to produce the much lower voltages at much higher currents. A high frequency is used i.s.o. 50 Hz because transformers are more efficient that way. There’s a feedback mechanism to regulate the output voltages.

The TL494 chip (which is not necessarily the same as used in this particular supply) is the heart of a PWM Power Control Circuit, which seems to drive it all. It generates pulses, and varies the ON-time as a way to regulate the generated output voltages. I think.

What I never understood is how you can regulate multiple voltages with what looks like only one feedback loop. In the schematic, the +12 and +5 V outputs are brought together as a single regulating signal through 2 resistors. What if the power draw from those 12V and 5V sections differ widely over time?

Anyway, go to that website mentioned earlier to read more about how it all works. I’m sure it does since there must be hundreds of millions of these on the planet by now…

Update – This particular unit will turn on without adding 10 Ω resistors, as sometimes suggested for lab use of such PSU’s. Voltage unloaded is 3.39V, 5.18V, and 11.99V, so close enough – with a little extra to compensate for wire losses. Big downside for lab use of such a “raw” PSU, is the nearly unlimited current that will flow with a short-circuit – guaranteed to vaporize lots of things! One solution would be to add basic current sensing and MOSFETs to switch off when pre-set values are being exceeded. With proper dimensioning, the added current drop need not be more than perhaps 100 mV, so the generated voltages would still be “in spec”. The + and – 12V would make a nice ±10V supply for analog experiments with dual-supply op-amps, for example.

Meet the Heading Board replacement

In Hardware on Apr 2, 2012 at 00:01

The Heading Board has been sold out for some time now. I’ve not been reordering it because it’s a bit quirky (needing the IRQ pin as well) and probably also not really all that sensitive.

To continue to offer a solution, I’ve decided to switch to the Modern Device 3-axis Compass Board instead:

DSC 2982

As you can see, it has a port-compatible header footprint on one side. The other side is for use with a 5V system, such as an RBBB or Arduino. Which is why there is also a 3.3V regulator on there.

The board is slightly smaller than a standard JeePlug and does not have port headers on both sides to support daisy chaining, but apart from that it’s totally JeeNode-/port-compatible. You can simply put it on the end of the chain if you want to mechanically stack this along with other I2C-enabled plugs.

Be careful about the orientation: it not the same as other plugs and there’s no “dot” next to the “P” pin.

I’ve added a very basic implementation in JeeLib to access the HMC5883 chip on this board, with demo:

Screen Shot 2012 03 29 at 15 47 17

Sample output:

Screen Shot 2012 03 29 at 15 45 34

This new board has now been added to the JeeLabs shop.

Watchdog tweaking

In AVR, Software on Apr 1, 2012 at 00:01

The other day, I mentioned a way to keep approximate track of time via the watchdog timer, by running it as often as possible, i.e. in a 16 ms cycle.

This brought out some loose ends which I’d like to clean up here.

First of all, the loseSomeTime() code now runs 60 times per second, so optimizing it might be useful. I ended up moving some logic out of the loop, to keep the time between power-down states as short as possible:

Screen Shot 2012 03 27 at 11 00 51

The result is this power consumption profile, every ≈ 16 ms:


That’s still about 22 µs @ 6.5 mA. But is it, really?

The above current measurement was done between the battery and the power supply of a JeeNode SMD. Let’s redo this without regulator, i.e. using a “modded” JeeNode with the regulator replaced by a jumper:


Couple of observations:

  • different ATmega, different watchdog accuracy: 17.2 vs 16.3 ms
  • the rise and fall times of the pulse is sharper, i.e. not dampened by a 10 µF buffer cap
  • new behavior: there’s now a 0.4 mA current during 80 µs (probably the clock starting up?)
  • that startup phase adds another 75 nC to the total charge consumed
  • note that there is a negative current flow, causing the charge integral to decrease

The worrying bit is that these two ways of measuring the current pulses differ so much – I can’t quite explain it. One thing is clear though: an adjusted fuse setting with faster clock startup should also make a substantial difference, since this now needs to happen 60 times per second.

A second improvement is to assume that when a watchdog cycle gets interrupts, half the time has passed – on average that’ll be as best as we can guess, assuming the interrupt source is independent:

Screen Shot 2012 03 27 at 13 17 55

The last issue I wanted to bring up here, is that small code optimizations can sometimes make a noticeable difference. When running the test sketch (same as in this post) with a 8192 millisecond argument to loseSomeTime(), the above code produces the following profile:


The reason the pulse is twice as wide is that the “while” in there now loops a few times, making the run time almost 50 µs between power-down phases. As Jörg Becker pointed out in a comment, the ATmega has no “barrel shifter” hardware, meaning that “shift-by-N” is not a hardware instruction which can run in one machine cycle. Instead, the C runtime library needs to emulate this with repeated shift-by-1 steps.

By changing the while loop from this:

Screen Shot 2012 03 27 at 12 18 20

… to this:

Screen Shot 2012 03 27 at 13 06 49

… we get this new power consumption profile (the horizontal scale is now 20 µs/div):


IOW, this takes 20 µs less time. Does it matter? Well, that might depend on who you ask:

  • Marketing guy: “50 µs is 67% more than 30 µs – wow, that means your sketch might last 5 years i.s.o. 3 years on the same battery!”

  • Realist: “50 µs i.s.o. 30 µs every 8 seconds – nah, those extra 120 nC or so will merely add 15 nA to the average current consumption.”

The moral of this story: 1) careful how you measure things, and 2) optimize where it matters.

Anyway, I’ve added all three changes to JeeLib. It won’t hurt, and besides: it leads to smaller code.