Computing stuff tied to the physical world

Archive for the ‘Hardware’ Category

Wrapping up

In AVR, Hardware, Musings, News, Software on Oct 6, 2013 at 00:01

I’m writing this post while one of the test JeeNode Micro’s here at JeeLabs is nearing its eighth month of operation on a single coin cell:

DSC_4507

It’s running the radioBlip2 sketch, sending out packets with an incrementing long integer packet count, roughly once every minute:

Screen Shot 2013-10-04 at 15.44.58

The battery voltage is also tracked, using a nice little trick which lets the ATtiny measure its own supply voltage. As you can see, the battery is getting weaker, dropping in voltage after each 25 mA transmission pulse, but still recovering very nicely before the next transmission:

Screen Shot 2013-10-04 at 15.45.45

Fascinating stuff. A bit like my energy levels, I think :)

But this post is not just about reporting ultra low-power consumption. It’s also my way of announcing that I’ve decided to wrap up this daily weblog and call it quits. There will be no new posts after this one. But this weblog will remain online, and so will the forum & shop.

I know from the many emails I’ve received over the years that many of you have been enjoying this weblog – some of you even from the very beginning, almost 5 years ago. Thank you. Unfortunately, I really need to find a new way to push myself forward.

This is post # 1400, with over 6000 comments to date. Your encouragement, thank-you’s, insightful comments, corrections and additions – I’m deeply grateful for each one of them. I hope that the passion which has always driven me to explore this computing stuff tied to the physical world technology and to write about these adventures, have helped you appreciate the creativity that comes with engineering and invention, and have maybe even tempted you to take steps to explore and learn beyond the things you already knew.

In fact, I sincerely hope that these pages will continue to encourage and inspire new visitors who stumble upon this weblog in the future. For those visitors, here’s a quick summary of the recent flashback posts, to help you find your way around on this weblog:

Please don’t ever stop exploring and pushing the boundaries of imagination and creativity – be it your own or that of others. There is infinite potential in each of us, and I’m certain that if we can tap even just a tiny fraction of it, the world will be a better place.

I’d like to think that I’ve played my part in this and wish you a lot of happy tinkering.

Take care,
Jean-Claude Wippler

PS. For a glimpse of of what I’m considering doing next, see this page. I can assure you that my interests and passions have not changed, and that I’ll remain as active as ever w.r.t. research and product development. The whole point of this change is to allow me to invest more focus and time, and to take the JeeLabs projects and products further, in fact.

PPS. Following the advice of some friends I highly respect, I’m making this last weblog post open-ended: it’ll be the last post for now. Maybe the new plans don’t work out as expected after all, or maybe I’ll want to reconsider after a while, knowing how much joy and energy this weblog has given me over the years. So let’s just call this a break, until further notice :)

Update Dec 2013 – Check out the forum at jeelabs.net for the latest news about JeeLabs.

Flashback – Anatomy of a transmission

In Hardware on Oct 5, 2013 at 00:01

One of the really fun things I always like to work on, is to push the envelope on power savings in the JeeNode.

It all started long ago, but over the years, I did refine the measurement process as my insight and instruments both got better. Here’s the most primitive approach, inserting a multimeter in series with the power supply to measure the static current consumption:

dsc_2597

The big problem with this is that a multimeter is far too slow to really see what’s going on. Only static idle current can be measured this way.

Another approach was to use a second JeeNode as power consumption tracker with some extra circuitry, to measure the voltage drop repeatedly:

Screen-shot-2009-12-19-at-16.27.09

This design can capture spikes by performing lots of repeated measurements, and in this particular case it even had a fairly large measurement range of 1 µA to 60 mA. This was done by using two separate sensing circuits and switching between them as needed.

But the real breakthrough came mid 2010, when Jörg Binkele sent me an oscilloscope snapshot of the voltage over a small series resistor. Here is one of the last ones, after lots of power saving techniques had already been applied:

detail_power_use1

As you can see from the annotations, there is an incredible amount of information one can glean from such oscilloscope traces.

This was one of the main reasons for me to learn more about oscilloscopes and eventually to buy a modern one myself – as described in a couple of posts, such as this one.

The capabilities of a modern digital storage oscilloscope (DSO) are truly phenomenal – and much of it is not even that much affected by the actual price range, although their cost does tend to keep them out of reach for occasional hobby use.

After many days of tinkering, it became possible to produce a very detailed map of the current consumption of a sensor acquisition + packet transmission cycle, as seen here:

annotated-room-packet1

The “haircomb” is the power consumption while sending individual bytes over SPI to the RFM12B module (and the received ACK after that), whereby the ATmega is even going to sleep between those bytes. For reference: the entire trace on this last screen is similar to the little blip marked “RFM12B transmission” on the previous screen. It’s not only considerably more detailed, but actually calibrated in 5-mA steps on the vertical axis.

Fascinating stuff, and no doubt a major reason why JeeNodes can perform so well nowadays in terms of ultra-low power consumption. If you had asked me this in 2008, I honestly would never have thought such a level of insight and performance to be attainable by anyone without access to a big research lab!

Flashback – Dive Into JeeNodes

In AVR, Hardware, Linux, Software on Oct 4, 2013 at 00:01

Dive Into JeeNodes (DIJN) is a twelve-part series, describing how to turn one or more remote JeeNodes, a central JeeLink, and a Raspberry Pi into a complete home monitoring setup. Well, ok, not quite: only a first remote setup is described with an LDR as light sensor, but all the steps to make the pieces work together are described.

More visually, DIJN describes how to get from here:

dijn01-essence.png   dijn01-diagram

.. to here:

Screen-Shot-2013-02-09-at-12.22.13

This covers a huge range of technologies, from embedded Arduino stuff on an ATmega-based JeeNode, to setting up Node.js and the HouseMon software on a Raspberry Pi embedded Linux board. The total cost of a complete but minimal setup should be around €100. Less than an Xbox and far, far more educational and entertaining, if you ask me!

It’s all about two things really: 1) describing the whole range of technologies and getting things working, and 2) setting up a context which you can explore, learn, and hack on tinker with in numerous ways.

If you’re an experienced Linux developer but want to learn about embedded hardware, wireless sensors, physical computing and such, then this offers a way to hook up all sorts of things on the JeeNode / Arduino side of things.

If you’re familiar with hardware development or have some experience with the Arduino world, then this same setup lets you get familiar with setting up a self-contained low-power Linux server and try out the command line, and many shell commands and programming languages available on Linux.

If you’ve set up a home automation system for yourself in the past, with PHP as web server and MySQL as back end, then this same setup will give you an opportunity to try out rich client-side internet application development based on AngularJS and Node.js – or perhaps simply hook things together so you can take advantage of both approaches.

With the Dive Into JeeNode series, I wanted to single out a specific range of technologies as an example of what can be accomplished today with open source hardware and software, while still covering a huge range of the technology spectrum – from C/C++ running on a chip to fairly advanced client / server programming using JavaScript, HTML, and CSS (or actually: dialects of these, called CoffeeScript, Jade, and Stylus, respectively).

Note that this is all meant to be altered and ripped apart – it’s only a starting point!

Flashback – Easy Electrons

In Hardware on Oct 3, 2013 at 00:01

The Easy Electrons series is a set of weblog posts which were published end of 2010 and beginning 2011 to try and bring across a bit of intuition w.r.t. electronics.

Many many times, people not trained in electronics struggle with the concepts of voltage vs. current, wonder why some component suddenly overheats, what a capacitor does, why you need a resistor in a certain circuit, or how large that resistor should be.

Unlike software, hardware and electronics are bound by the laws of physics. Painfully so, in fact – you can damage stuff when hooking things up incorrectly, and you can even get hurt if the voltages or currents involved are high enough. And it’s not just AC mains that can hurt you: even a car battery can be dangerous if you don’t know what you’re doing.

Knowing why things happen is extremely important in electronics. And learning the basics is really just a matter of reading up on it and investing a bit of effort. There’s no magic – in fact, there is so much knowledge about electronics nowadays, that you really can predict and explain stuff, even before hooking things up.

Since I loved tinkering with electronics as a teenager, I was lucky to gain a good deal of very intuitive knowledge about electronics early on. So much so, that basic DC electricity knowledge became second nature to me. Ohm’s law is not some technical rule, it’s obvious – the linear relation between voltage and current, and the fact that resistance is simply the slope of that relationship, is so ingrained by now, that I don’t even think of Ohm’s law as something distinct from the essence of electricity. Same for Kirchhoff’s laws – and the water analogy which works so well in so many cases to match intuition to the real world.

So the Easy Electrons series was born – no math, no theory, just a set of posts which tackle a number of electronics concepts in what I hope can bring across some of that intuition. My drawing tools at the time were based on paper and a scanner, so the drawings were a bit crude and hard to read – here’s an example where I’m trying to explain how to drive LED strips which draw more power than the weak I/O pins of an ATmega can provide:

screen_shot_2010_12_29_at_103314

There are posts about voltage and current, about power and heat, about resistors and capacitors, about LEDS and diodes, and about transistors and MOSFETs, to name a few.

Don’t take my word for it, heck… don’t even read my posts if you don’t want to – all I can say is: if you ever hook up electronics circuits of your own imagination and invention: get to grips with the basics, so you’ll understand why hooking up a bunch of LEDs in parallel is usually not such a good idea, why using a power supply with a higher voltage is likely to lead to overheating and damage, and why hooking up relays and motors often requires extra protective circuitry.

It’s not hard, it’s not magic, it requires no math of any sophistication (and there’s always the brilliant Khan Academy if you want to brush up on it anyway). It can be exhilarating to be able to design and predict what a circuit will do before hooking anything together.

Electronics is a truly wonderful field to explore (and it’s huge!). You don’t need much to experiment with, and you will learn a lot – if only to become quite respectful of the laws of physics, which are merciless (still: most mishaps are harmless and nothing gets damaged).

You’ll run into everything from “nothing happens” to “it’s smoking”, and it’s terrific fun!

Flashback – The first JeeNode PCB

In AVR, Hardware on Oct 1, 2013 at 00:01

The first JeeNode circuit board was very exciting to make, back in January 2009:

pd-d1

Initially, I just wanted to get the connections right and didn’t care for silkscreen labelling, so there was none. It was created with CadSoft’s EAGLE, a commercial package with a freeware version for small boards. The “JeeNode” name came a month later, by the way.

The learning curve of the EAGLE package is steep, but then again, drawing this sort of stuff is going to be complicated whatever you do, because it’s not about drawing a nice picture where only aesthetics matter, but a meticulously designed diagram of which all the paths and connections have to follow certain rules, such as wires not crossing (doh!) and wires all having a minimum width and separation.

Here’s the JeeNode v6 PCB in comparison, of which many thousands have been produced:

DSC_4499

It’s still surprisingly similar in design to the first iteration, although the production details and fabrication process have greatly improved over the years. One aesthetic detail I’ve always been pleased with is the blue-with-gold color choice. The gold plating is easier to solder than the HASL process I used initially, and is much more resistant to corrosion. Don’t think too much of this gold layer, by the way: it’s chemically deposited (fairly nasty stuff, from what I understand) and only a few atoms thick. Still… enough to do its work, and visually attractive (all in the eye of the beholder, evidently).

The purpose of a PCB is three-fold: a physically strong base for all the components, a reliable interconnect between all the pins to implement the actual circuit design, and silkscreen labelling to ease assembly and use afterwards.

The result: a tangible product. Quite an exciting change for a software developer used to work with bits and bytes, and who could never before point to the “real” result of it all!

Flashback – Batteries came later

In AVR, Hardware, Software on Sep 30, 2013 at 00:01

During all this early experimentation in 2008 and 2009, I quickly zoomed in on the little ATmega + RFM12B combo as a way to collect data around the house. But I completely ignored the power issue…

The necessity to run on battery power was something I had completely missed in the beginning. Everyone was running Arduino’s off either a 5V USB adapter or – occasionally – off a battery pack, and never much more than a few days. Being “untethered” in many projects at that time, meant being able to do something for a few hours or a day, and swapping or recharging batteries at night was easy, right?

It took me a full year to realise that a wireless “node” tied to a wire to run for an extended period of time made no sense. Untethered operation also implies being self-powered:

DSC_0496

Evidently, having lots of nodes around the house would not work if batteries had to be swapped every few weeks. So far, I just worked off the premise that these nodes needed to be plugged into a power adapter – but there are plenty of cases where that is extremely cumbersome. Not only do you need a power outlet nearby, you need fat power adapters, and you have to claim all those power outlets for permanent use. It really didn’t add up, in terms of cost, and especially since the data was already being exchanged wirelessly!

Thus started the long and fascinating journey of trying to run a JeeNode on as little power as possible – something most people probably know this weblog best for. Over the years, it led to some new (for me) insights, such as: transmission draws a “huge” 25 mA, but it’s still negligible because the duration is only a few milliseconds. By far the most important parameter to optimise for is sleep-mode power consumption of the entire circuit.

In September 2010, i.e. one year after starting on this low-power journey, the Sleepy class was added to JeeLib, as a way to make it easy to enter low-power mode:

class Sleepy {
public:
    /// start the watchdog timer (or disable it if mode < 0)
    /// @param mode Enable watchdog trigger after "16 << mode" milliseconds 
    ///             (mode 0..9), or disable it (mode < 0).
    static void watchdogInterrupts (char mode);
    
    /// enter low-power mode, wake up with watchdog, INT0/1, or pin-change
    static void powerDown ();
    
    /// Spend some time in low-power mode, the timing is only approximate.
    /// @param msecs Number of milliseconds to sleep, in range 0..65535.
    /// @returns 1 if all went normally, or 0 if some other interrupt occurred
    static byte loseSomeTime (word msecs);

    /// This must be called from your watchdog interrupt code.
    static void watchdogEvent();
};

The main call was named loseSomeTime() to reflect the fact that the watchdog timer is not very accurate. Calling Sleepy::loseSomeTime(60000) gives you approximately one minute of ultra low-power sleep time, but it could be a few seconds more or less. To wait longer, you can call this code a few times, since 65,535 ms is the maximum value supported by the Sleepy class.

As a result of this little class, you can do things like put the RFM12B into sleep mode (and any other power-hungry peripherals you might have connected), go to sleep for a bit, and restore all the peripherals to their normal state. The effects can be quite dramatic, with a few orders of magnitude less power consumption. This extends a node’s battery lifetime from a few days to a few years – although you have to get all the details right to get there.

One important design decision in the JeeNode was to use a voltage regulator with a very low idle current (the MCP1700 draws 2 µA idle). As a result, when a JeeNode goes to sleep, it can be made to draw well under 10 µA.

Most nodes here at JeeLabs now keep on running for well over a year on a single battery charge. Everything has become more-or-less install and forget – very convenient!

Flashback – RFM12B wireless

In AVR, Hardware, Software on Sep 29, 2013 at 00:01

After the ATmega µC, the second fascinating discovery in 2008 was the availability of very low-cost wireless modules, powerful enough to get some information across the house:

wireless-modules

It would take another few months until I settled on the RFM12B wireless module by HopeRF, but the uses were quickly falling into place – I had always wanted to track the energy consumption in the house, to try and identify the main energy consumers. That knowledge might then help reduce our yearly energy consumption – either by making changes to the house, or – as it turned out – by simply adjusting our behaviour a bit.

Here is the mouse trap which collected energy metering data at JeeLabs for several years:

mousetrap

This is also when I found Modern Devices’s Real Bare Bone Board Arduino clone by Paul Badger – all the good stuff of an Arduino, without the per-board FTDI interface, and with a much smaller form factor.

Yet another month would pass to get a decent interrupt-driven driver working, and some more tweaks to make transmission interrupt-based as well. The advantage of such as design is that you get the benefits of a multi-tasking setup without all the overhead: the RF12 driver does all its time-critical work in the background, while the main loop() can continue to use delay() calls and blocking I/O (including serial port transmission).

In February 2009, I started installing the RF12demo code on each ATmega, as a quick way to test and try out wireless. As it turned out, that sketch has become quite useful as central receiving node, even “in production” – and I still use it as interface for HouseMon.

In April 2009, a small but important change was made to the packet format, allowing more robust use of multiple netgroups. Without this change, a bit error in the netgroup byte will alter the packet in a way which is not caught by the CRC checksum, making it a valid packet in another netgroup. This is no big deal if you only use a single netgroup, but will make a difference when multiple netgroups are in use in the same area.

Apart from this change, the RF12 driver and the RFM12B modules have been remarkably reliable, with many nodes here communicating for years on end without a single hick-up.

I still find it pretty amazing that simple low-power wireless networking is available at such a low cost, with very limited software involvement, and suitable for so many low-speed data collection and signalling uses in and around the house. To me, wireless continues to feel like magic after all these years: things happening instantly and invisibly across a distance, using physical properties which we cannot sense or detect…

Flashback – Discovering the Arduino

In AVR, Hardware on Sep 28, 2013 at 00:01

It’s now just about 5 years ago when I started with JeeLabs, so I thought it might be a good idea to bring back some notes from the past. Get ready for a couple of flashback posts…

One of the first posts on this weblog was about the Arduino, or rather Atmel’s AVR ATmega chip I had just discovered (it was the ATmega168 back then):

atmega328p

It was the Arduino IDE which made it trivial to play with this chip, an open source multi-platform software package combining an editor, the avr-gcc compiler, and the avrdude uploader. And despite the use of very Arduino-ish names such as “sketches” (firmware) and “shields” (add-on hardware), it was all nearly-standard C and C++, with a couple of convenient libraries to easily access I/O pins, the ADC, the serial port, timers, and more.

Five years ago, a fascinating brand new world opened up for me. I knew all about C and C++ as well as digital I/O and boot loaders, but a lot of really interesting and powerful new technologies were new to me: I2C, SPI, embedded timer hardware, and above all: sleep mode. These chips were not only able to run at an amazing 16 MHz clock rate, they could actually go to sleep and use a watchdog timer to wake up again later, saving 3 orders of magnitude on energy consumption.

A small universe, controlled by standard software and able to interface to the real world.

Physical Computing. Low cost. Accessible to anyone.

Wow.

Small Gravity Plug update

In Hardware on Sep 25, 2013 at 00:01

The Gravity Plug contains a BMA020 3-axis accelerometer from Bosch Sensortec, which is being replaced by a newer BMA150 chip. Luckily, it’s fully compatible in both hardware and software, so the GravityPlug implementation in JeeLib will continue to work just fine with either one.

But the new chip does have more features: you can override its calibration parameters and defaults, by changing values in a new EEPROM area added to the chip. That in itself is probably not too useful for simple setups, but the new chip also offers access to its built-in temperature sensor, so I’ve added some extra code and expanded the gravity_demo sketch to take advantage of that:

#include <JeeLib.h>

PortI2C myBus (1);
GravityPlug sensor (myBus);
MilliTimer measureTimer;

struct {
  int axes[3];
  int temp;
} payload;

void setup () {
    Serial.begin(57600);
    Serial.println("\n[gravity_demo]");

    if (sensor.isPresent()) {
      Serial.print("sensor version ");
      sensor.send();
      sensor.write(0x01);
      sensor.receive();
      Serial.println(sensor.read(1), HEX);
      sensor.stop();
    }

    rf12_initialize(7, RF12_868MHZ, 42);
    sensor.begin();
}

void loop () {
    if (measureTimer.poll(1000)) {
        memcpy(payload.axes, sensor.getAxes(), sizeof payload.axes);
        payload.temp = sensor.temperature();

        rf12_sendNow(0, &payload, sizeof payload);

        Serial.print("GRAV ");
        Serial.print(payload.axes[0]);
        Serial.print(' ');
        Serial.print(payload.axes[1]);
        Serial.print(' ');
        Serial.print(payload.axes[2]);
        Serial.print(' ');
        Serial.println(payload.temp);
    }
}

Here is some sample output:

GRAV 2 -10 130 41
GRAV 0 -9 133 41
GRAV 4 -14 127 41
GRAV 0 -12 134 41
GRAV 4 -15 130 41
GRAV 4 -13 129 42
GRAV 3 -8 128 41

The reported temperature is in units of 0.5°C, so the above is reporting 20.5 .. 21.0 °C.

Unfortunately, the old chip isn’t reporting anything consistent as temperature:

GRAV 51 -31 -225 2
GRAV 50 -29 -225 0
GRAV 51 -30 -224 1
GRAV 52 -30 -227 1
GRAV 51 -30 -229 1
GRAV 52 -31 -223 2
GRAV 51 -31 -225 1

I have not found a way to distinguish these two chips at runtime – both report 0x02 in register 0 and 0x12 in register 1. Makes you wonder what the point is of having a chip “ID” register in the first place…

Anyway – in the near future, the Gravity Plug will be shipped with the new BMA150 chips. It should have no impact on your projects if you use these accelerometers, but at least you’ll be able to “sort of” tell which is which from the temperature readout. Note that the boards will probably still be marked as “BMA020″ on the silkscreen for a while – there’s little point in replacing them, given that the change is so totally compatible either way…

My development setup – hardware

In Hardware on Sep 11, 2013 at 00:01

After yesterday’s notes about my development software, some comments about hardware.

As you may have noticed, I use Apple’s hardware with Mac OS/X. Have gone from big (clunky!) setups to the svelte 1 kg 11″ MacBook Air, and now I’m back on a 15″ model. It’s unlikely that I’ll ever go back to a desktop-only setup, and even the 1920 x 1200 pixel 24″ screen on my desk has been sitting idle for many months now (apart from its use in the FanBot project). One reason is that screen switching with multiple physical screens has not been convenient so far (the next OS revision this fall promises to fix that), but even as is, I find the constant switching between different pixel sizes disruptive. Nowadays, I’m often in house-nomad mode: switching places several times a day around the house – from the desk, to the couch, to a big comfy rotating chair, and back. Heck, even outside, at times!

So one setup it is for me. And these days, that’s a 15″ Retina MacBook Pro (“RMBP15″):

Screen Shot 2013-09-04 at 14.48.48

There’s a lot to say about this, but the essence boils down to: 1920 x 1200 with VM’s.

To me it’s not essential which operating runs on the host: pick one which you feel really at home with, and go for a laptop size and build quality that suits you and your budget.

Now the crazy thing about the MBPR15 is that its screen is not 1920 x 1200, but 2880 x 1800 pixels. And out of the box, the machine comes set to a 1440 x 900 “logical” screen size, i.e. doubling up all the pixels. Which, in my view, is too small as main development environment – at least by today’s measures (hey, we’ve all been there – but it really is worth stepping up whenever you can).

So there’s this curious 1.5x magnification setting on this Mac laptop – does this mean that a 1-pixel thick line will end up getting drawn as “one pixel and a half”?

Obviously not. It’ll all be anti-aliased, as you can see in this close-up:

Screen Shot 2013-09-04 at 15.04.40

If you click on the image above, you’ll see a larger version. There is some interesting stuff going on behind the scenes when using a RMBP15 in 1920 x 1200 “interpolated” mode:

  • to the applications, the screen is reported as being 1920 x 1200
  • so that’s the way apps deal with for screen area and placement
  • for lines, the Mac OSX graphics engine will do its anti-aliasing thing
  • for text, the graphics engine will draw the fonts at their optimal resolution

That last one does the trick: when drawing a 12-point text, the graphics engine will actually draw an 18-point version, using the full screen resolution. As a result, text comes out as sharp as the LCD display will allow, without the application having to do a thing.

I tend to go for the smallest font sizes in editors and command-line shells which my glass-assisted (no, not that one) eyes can still read well (Menlo 10, for monospaced fonts). This gives me a 100 line window height in MacVim, which is perfect. But on a real 1920 x 1200 display, that would actually be pushing it. However, due to the rendering going on inside a Retina Mac, what you actually get to see is text drawn in a 15-point font on a display with over 200 dpi resolution. The result is excellent.

These choices for screen, window, and font sizes are really hitting the sweet spot for me. An 100 x 80 character editing window with splits and tabs as needed, a decent area to see the browser’s console log (and command line), and a main HMTL display area which is still almost exactly the 1366 x 768 size of a common small laptop screen. I rarely use the Mac’s multiple-desktop feature (called “spaces” in OSX), because I don’t have the patience to wait through its sweep-left-and-right animations. And because there’s no need: one “mode” with carefully-positioned windows, and other windows which can be moved to the front and back – a bit disruptively, but that’s because IMO that’s exactly what they are!

The second part of my laptop story is that since everything is running on an Intel 64-bit chip, virtualisation comes easy. This means both Windows and Linux can be run at the same time on the same machine (assuming you have enough RAM). I regularly fire up a Linux VM, and then ssh into it from the command line. For editing, I don’t even have to leave MacVim: just opening a file as scp://debianvm/housemon/ will open a directory window in MacVim and let me navigate from there. With the entire editor environment intact for fast file selection, tags, folding, etc. With Windows, it’s a matter of “mounting” my home directory on Windows, and all the local command line tools can be used for editing, git, diff, and so on (there’s a lot more possible, but I don’t use Windows much).

I’ll finish off tomorrow with some other handy software utilities I’ve come to rely on.

PS. No, this wasn’t intentionally made to coincide with Apple’s latest publicity blitz :)

3 years on one set of batteries

In AVR, Hardware on Sep 8, 2013 at 00:01

Ok, so maybe it’s getting a bit boring to report these results, but one of the JeeNodes I installed long ago has just reached a milestone:

Screen Shot 2013-09-06 at 23.30.55

That “buro JC” node has been running on a single battery charge for 3 years now:

And it’s not even close to empty: this is a JeeNode USB with a 1300 mAh LiPo battery tied to its back, and (as I just measured) it’s still running at 3.74 V, go figure.

Let’s do the math on what’s going on here:

  • the battery is specified as 1300 mAh, i.e. 1300 mA for one hour and then it’s empty
  • in this case, it has been running for some 1096 x 24 = 26,304 hours total
  • so the average current consumption must have been under 1300 / 26304 = 50 µA
  • well… in that case, the battery should be empty by now, but it isn’t
  • in fact, I suspect that the average power consumption is more like 10..25 µA

Two things to note: 1) LiPo batteries pack a lot of energy, and 2) they have a really low self-discharge rate, so they are able to store that energy for a long time.

The other statistic worth working out, is the amount of energy consumed by a single packet transmission. Again, first assuming that the battery would be dead by now, and that the microcontroller and the rest of the circuit are not drawing any current:

  • 1,479,643 packets have been sent out, i.e. ≈ 1300 / 1500000 = under 1 µAh per packet
  • since 60 packets are sent out per hour: about 60 µAh per hour, i.e. 60 µA continuous
  • energy can also be expressed in coulombs, i.e. 60 µC gets used per packet transmission (3,600 seconds to the hour, but there were 60 packets sent out during that period)
  • so despite the fact that the RFM12B draws a substantial 25 mA of current during transmission, it does it so briefly that overall it’s still extremely low-power (a few ms every 1s, so that’s a truly minute duty cycle)

The conclusion here is: for these types of uses, with occasional brief wireless sensor data transmissions, the power consumption of the wireless module is not the main issue. It’s far more important to keep the idle (i.e. sleep mode) of the entire circuit under control.

The 2nd result is also a record, a JeeNode Micro, running over 6 months on a coin cell:

This one is running the newer radioBlip2 sketch, which also measures and reports the battery voltage before and after packet transmission. As you can see, the coin cell is struggling a bit, but its voltage level is still fine: it drops to 2.74 V right after sending out a packet (drawing 25 mA), and then recovers the rest of the time to a fairly high 2.94 V. This battery sure isn’t empty yet. Let’s see how many more months it can keep this up.

The 3rd result (penlight test), is this setup, based on the latest JNµ v3:

The timing values are way off though: it has also been running for over 6 months, but I accidentally caused it to reset when moving things around earlier this summer. This one is running with a switching boost regulator. The Eneloop battery started out at 1.3 V and has now dropped slightly to 1.28 V – it should be fine for quite some time, as these batteries tend to run down gradually to 1.2V before they start getting depleted. This is a rechargeable battery, but Eneloop is known to hold on to its charge for a surprisingly long time (losing 20% over 2 years due to self-discharge, if I remember correctly).

You can see the boost regulator doing its thing, as the output voltage sent to the ATtiny is the same 3.04 V as it was on startup. That’s the whole idea: it regulates to a fixed level, while sucking the battery dry along the way…

Note that all these nodes are not sensing anything. They’re just bleeping once a minute.

Anyway… so much for the progress report on a pretty long-running experiment :)

Electricity usage patterns

In Hardware, Software on Sep 3, 2013 at 00:01

Given that electricity usage here is monitored with a smart meter which periodically phones home to the electricity company over GPRS, this is the sort of information they get to see:

Screen Shot 2013-09-02 at 11.20.38

Consumption in blue, production in green. Since these are the final meter readings, those two data series will never overlap – ya can’t consume and produce at the same time!

I’m reading out the P1 data and transmitting it wirelessly to my HouseMon monitoring setup (be sure to check the develop branch, which is where all new code is getting added).

There’s a lot of information to be gleaned from that. The recurring 2000+ W peaks are from a 7-liter kitchen boiler (3 min every 2..3 hours). Went out for dinner on Aug 31st, so no (inductive) home cooking, and yours truly burning lots of midnight oil into Sep 1st. Also, some heavy-duty cooking on the evening of the 1st (oven dish + stove).

During the day, it’s hard to tell if anyone is at home, but evenings and nights are fairly obvious (if only by looking at the lights lit in the house!). Here’s Sep 2nd in more detail:

Screen Shot 2013-09-02 at 11.23.50

This one may look a bit odd, but that double high-power blip is the dish washer with its characteristic two heating cycles (whoops, colours reversed: consumption is green now).

Note that whenever there is more sun, there would be fewer consumption cycles, and hence less information to glean from this single graph. But by matching this up with other households nearby, you’d still get the same sort of information out, i.e. from known solar power vs. returned power from this household. Cloudy patterns will still match up across a small area (you can even determine the direction of the clouds!).

I don’t think there’s a concern for (what little) privacy (we have left), but it’s quite intriguing how much can be deduced from this.

Here’s yet more detail, now including the true house usage and solar production values, as obtained from some pulse counters, this hardware and the homePower driver:

Screen Shot 2013-09-02 at 11.52.21

There is a slight lag in smart meter reporting (a value on the P1 port every 10s). This is not an issue of the smart meter though: the DyGraphs package is only able to plot step lines with values at the start of the step, even though these values pertain to the past 10 seconds.

Speaking of which – there was a problem with the way data got stored in Redis. This is no longer an issue in this latest version of HouseMon, because I’m switching over to LevelDB, a fascinating time- and space-efficient database engine.

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:

pwm

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:

CRLowPass1

That image came from an excellent article by Scott Daniels about this same topic on the ProvideYourOwn.com 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:

SCR79

(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:

SCR80

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);
    delay(10);
  }
}

The result is this:

SCR81

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:

SCR84

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!

Status of the RFM12B

In Hardware on Jun 28, 2013 at 00:01

The RFM12B wireless radio module has been around for quite some time. When I found out about it at the time, I really liked the mix of features it provided – far more capable than the morse-code like OOK modules in cheap sensors, very low power, and available at a considerably lower cost than the XBee and other ZigBee solutions out there:

rfm12b

There was little software for it at the time, and writing an interrupt-driven driver for it was quite a challenge when this all started, but nowadays that’s no longer an issue – the RF12 driver which is now part of JeeLib has turned out to work quite well.

There have been some rumours recently, and understandably also some worries, that the RFM12B might be phased out, but if I may paraphrase Mark Twain on this: the reports of the RFM12B’s death have been greatly exaggerated…

After some email exchanges between HopeRF and Martyn Judd, I’m now happy to report that we have received a formal statement from HopeRF to clarify the issue:

“The popular RFM12B S1/S2 modules remain in production with a large volume of long standing and long term orders. There is NO plan to discontinue the series and NO plan to end production in the foreseeable future. It is correct that we no longer recommend this series to customers developing new projects, since we have developed more recent designs, for example the RFM6X series. These incorporate functionality improvements that can provide a better price/performance for specific applications.”

– Derek Zhu, Marketing Manager, HopeRF

As I see it, this means that the RFM12B will be around for quite some time and that we don’t have to worry about supplies for keeping all current networks based on these modules working. I definitely intend to keep using RFM12B’s at JeeLabs and in products designed and produced by JeeLabs.

Having said that, I’m also evaluating alternatives and looking for a convenient option to act as next step forward. My focus is on low-power consumption and good range for use within the house, both of which I hope to take even further. I’d also like to make sure that over-the-air flashing with JeeBoot will work well with the current as well as future choices.

In my opinion the RFM12B continues to be a simple & excellent low-cost and low-power foundation, so I’m taking my time to very carefully review any new options out there.

Meet the FanBot

In Hardware, Musings on Jun 27, 2013 at 00:01

The FanBot is a very simple robot based on a small PCB with microcontroller by Peter Brier, some LEDs as eyes and mouth, and a servo to allow the robot to wave its arms:

DSC_4497

Over a thousand boards have been produced, along with accessories to let children create a little cardboard robot with their own name and a little program to store a personalised sequence of LED blinks and servo movements. The µC is an ARM LPC11U24 chip, donated by NXP – which has plenty of power, but more importantly: can be programmed by powering it up as a USB memory stick.

_MG_1606-2

Wednesday was the kick-off / trial day, with 120 kids dropping by and creating their own FanBot. The FanBots will all be used for the main event to cheer on the main RoboCup contestants. Here’s a quick impression of the first 80 “fans” (it’s a huge task to get them all up there, checked, stapled, and connected – not to mention the power/network setup!):

_MG_1704

It’s a really wonderful project, IMO: lots of young kids get exposed to new technology, learning about robots by building their own, and creating a huge collection of truly individual and personal robots, all cheering together!

For more info, see Peter and Marieke’s KekBot weblog – there’s also a progress page.

The RoboCup championship itself uses more sophisticated robots, such as these:

BvOF RoboCup2013

Many more pictures of this event can already be found on the RoboCup 2013 website and on their Flickr group. The event has only just started so if you’re in the neighbourhood: it’s free, and bound to be oodles of fun for kids of any age!

Myra and I had a wonderful time, and I even had a chance to see Asimo in action, live!

And JeeLabs ended up getting a spot on the sponsor page – not bad, eh?

Update – Forgot to mention that one of the requirements of RoboCup is that everything must be made open source after the event. This means that any advances made can be used by anyone else in the next year. What a fantastic way to stimulate shared progress!

Packaged but not virtualised

In Hardware, Linux, Software on Jun 26, 2013 at 00:01

Since VMware started virtualising x86 hardware many years ago, many uses have been found for this approach of creating fully self-contained software environments. I’ve used VMware many years, and was pleased when Apple switched the Macs to “Intel inside”.

Nowadays, I can run numerous variants of Windows as well as Linux on a single laptop. I switched to Parallels as VM core, but the principle remains the same: a large file is used as virtual hard disk, with an operating system installed, and from then on the whole environment simply “runs” inside the Mac host (in my case).

Nowadays, we all take this for granted, and use virtual environments as ultra-low cost web servers without even giving it any thought. I have a number of virtual machines running on a Mac Mini for all the JeeLabs sites in fact (and some more). One piece of hardware, able to suspend and resume N completely independent systems at the click of a mouse.

But there’s a drawback: you end up duplicating a lot of the operating system and main services in each VM, and as a result this stuff not only consumes disk space but also leads to a lot of redundant backup data. I keep the VM’s very lean and mean here, but they still all eat up between 3 and 10 gigbytes of disk space. Doesn’t sound like much, but I’m pretty sure my own data uses less than 10% of that space…

Both Parallels and VMware (and probably also VirtualBox) support snapshotting, which means that in principle you could set up a full Linux environment with a LAMP stack, and then use snapshots to only store what’s different for each VM. But that’s not useful in the long run, because as soon as you get system updates, they’ll end up being duplicated again.

It’s a bit like git “forks”: set up a state, create a fork to create a variant, and then someone decides to add some features (or fix some bugs) to the original which you’d also like to adopt. For git, the solution is to merge the original changes into your fork, and use “fast-forwarding” (if I understand it correctly – it’s all still pretty confusing stuff).

So all in all, I think VM’s are really brilliant… but not always convenient. Before you know it, you end up maintaining and upgrading N virtual machines every once in a while.

I’ve been using TurnkeyLinux as basis of all my VM’s because they not only maintain a terrific set of ready-to-run VM images, but because they also make them self-updating out of the box, and because they’ve added a very convenient incremental daily backup mechanism which supports restarting from the back-up. You can even restart in the cloud, using Amazon’s EC2 VM “instances”.

And then someone recently told me about Docker – “The Linux container engine”.

This is a very interesting new development. Instead of full virtualisation, it uses “chroot” and overlay file systems to completely isolate code from the rest of the 64-bit Linux O/S it is running on. This lets you create a “box” which keeps every change inside.

My view on this, from what I understand so far, is that Docker lets you play git at the operating system level: you take a system state, make changes to it, and then commit those changes. Not once, but repeatedly, and nested to any degree.

The key is the “making changes” bit: you could take a standard Linux setup as starting point (Docker provides several base boxes), install the LAMP stack (if someone hasn’t done this already), commit it, and then launch that “box” as web server. Whereby launching could include copying some custom settings in, running a few commands, and then starting all the services.

The way to talk to these Docker boxes is via TCP/IP connections. There’s also a mechanism to hook into stdin/stdout, so that you can see logs and such, or talk to an interactive shell inside the box, for example.

The difference with a VM, is that these boxes are very lightweight. You can start and stop them as quickly as any other process. Lots of ‘em could be running at the same time, all within a single Linux O/S environment (which may well be a VM, by the way…).

Another example would be to set up a cross compiler for AVR’s/Arduino’s (or ARMs) as a box in Docker. Then a compile would be: start the box, feed it the source files, get the results out, and then throw the box away. Sounds a bit drastic, but it’s really the same as quitting an application – which throws all the state in RAM away. The point is that now you’re also throwing away all the uninteresting side-effects accumulated inside the box!

I haven’t tried out much so far. Docker is very new, and I need to wrap my mind around it to really understand the implications, but my hunch is that it’s going to be a game changer. With the same impact on computation and deployment as VMware had at the time.

As with VM’s, Docker boxes can be saved, shared, moved around, and launched on different machines and even different environments.

For more info, see this page which draws an analogy with freight containers, and how one standard container design has revolutionised the world of shipping and freight / cargo handling. I have this feeling that the analogy is a good one… a fascinating concept!

Update – Here’s a nice example of running a Node.js app in Docker.

FanBots at RoboCup 2013

In ARM, Hardware, Linux, Software on Jun 25, 2013 at 00:01

There’s an event coming up in a few days in Eindhoven, called the RoboCup 2013:

teun

This is the world championship of robotic football. For all ages, and with various levels of sophistication. Some robots are tiny cars, trying to work together to play a match, some robots are little human-like machines consisting of lots of servos to make them walk on two feet, and some robots are very sophisticated little “towers” on three wheels, zipping along at impressive speeds and able to catch, hold, and kick a standard-size football.

I’m not directly involved in this, but I saw some of the preparations and it really promises to be a fantastic event. Lots of geeks with laptops, soldering irons, and mechanical stuff. The kick-off is next Wednesday and the event lasts for five days, with the finals on Sunday.

On the side, there is a gorgeous (not-so) little project going on, whereby kids of ages 8 to 12 can visit a workshop to build their own FanBot (for free). The FanBot can blink its eyes and mouth, and wave its arms – part of the exercise is to create a little “program” of things it does at the press of a button, so this will also be a first encounter with programming!

There’s a Dutch page about the project and a general page in English mentioning FanBots.

But the really exciting goal will be to create a huge stand for all the FanBots and make them cheer the football-playing robots in the main event hall. The aim is to get up to 1000 of them, all blinking and waving – and all orchestrated and controlled from a central system. It’s all being designed and built by Peter Brier and by Marieke Peelen of KekkeTek.

One task in the project is to register all the FanBots and print out a little “passport” as last step – which the kids can then use to pick up their own FanBot once the RoboCup 2013 event is over. This is the part I volunteered to help with.

I’ll describe the setup in more detail soon, but that’s where the Raspberry Pi’s w/ LCD screen and webcams will be used. It’ll be fun to see whether we can get 1000 kids to build and sign up their little robots during three days – there’s quite a bit of logistics involved!

Admission is free, so if you’re in the neighbourhood: don’t miss it – it’s going to be fun!

Using eMMC as root disk

In Hardware, Linux on Jun 24, 2013 at 00:01

The Odroid/U2 mentioned yesterday also has the option to add an eMMC card, right next to the µSD card slot – I went for a whopping 64 GB “SSD” in this case:

DSC_4489

The reason to use this, is that it’s indeed nearly three times as fast:

# hdparm -tT /dev/mmcblk0

/dev/mmcblk0:
 Timing cached reads:   1604 MB in  2.00 seconds = 802.41 MB/sec
 Timing buffered disk reads: 146 MB in  3.02 seconds =  48.40 MB/sec

That’s faster than the maximum transfer rate of USB 2.0, by the way.

But how do you set these things up? The bottom view shows yet another connector, yuck:

DSC_4490

It turns out that you can get an adapter from the Odroid/U2 shop:

DSC_4491

That turns it into a µSD card, but unfortunately it wasn’t recognised in my Mac laptop. Luckily, this concoction did seem to do the trick:

DSC_4492

Through this, I was able to burn the Debian disk image onto it, and through some clever logic in the bootstrap loader, the eMMC card simply takes precedence when present and starts up fine with the same device name as the initial µSD card (which now ends up on /dev/mmcblk1 if also present).

One last step is needed to resize the root partition to take full advantage of the entire eMMC card. Google found this article which explains the whole (nasty) procedure.

Final result:

# free
             total       used       free     shared    buffers     cached
Mem:       2031632      77660    1953972          0       9540      37420
-/+ buffers/cache:      30700    2000932
Swap:            0          0          0

And… tada!

# df -H
Filesystem      Size  Used Avail Use% Mounted on
rootfs           62G  1.2G   58G   2% /
udev            1.1G     0  1.1G   0% /dev
tmpfs           209M  222k  208M   1% /run
/dev/mmcblk0p2   62G  1.2G   58G   2% /
tmpfs           5.3M     0  5.3M   0% /run/lock
tmpfs           417M     0  417M   0% /run/shm
/dev/mmcblk0p1  133M  8.5M  124M   7% /boot

Neat, neat, neat – although the total system cost is close to $200 at this point, due to the expensive eMMC memory card – five times the cost of a Raspberry Pi, but with four times the RAM, a comfy 60 GB of fast SSD storage, and probably 5..10 times the performance.

It’s not for everyone and it has no GPIO pins to hook anything up, but I like it!

More about the Odroid/U2

In ARM, Hardware, Linux on Jun 23, 2013 at 00:01

As mentioned recently, there are many alternatives to the Raspberry Pi. I’m looking mostly at ARM-based systems these days, because Node.js support for MIPS is not really there (yet?), and you really want a JIT-type system to get the most out of a Node.js based setup.

Well, having received the Odroid/U2, first thing I had to do is get a micro-HDMI to HDMI adapter (always some new connector/cable type, yawn…). Also had to get a 16 GB µSD card, because the Debian image I wanted to try was for cards of 8 GB or more (yawn!).

But now that everything is in, I’m finally able to take that little black cube for a spin:

article_img

First impression: it’s fast, much snappier than a Raspberry Pi. Try launching aptitude, for example – which takes a long time on RPi’s and other low-end ARM & MIPS systems.

Both are running class-10 SD cards, as far as I can tell. The RPi is running at 700 MHz:

# cat /proc/cpuinfo 
Processor   : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS    : 697.95
Features    : swp half thumb fastmult vfp edsp java tls 
[...]
Hardware    : BCM2708

The OU2 has four cores running at 1.7 GHz:

# cat /proc/cpuinfo 
Processor   : ARMv7 Processor rev 0 (v7l)
processor   : 0
BogoMIPS    : 1992.29
processor   : 1
BogoMIPS    : 1992.29
processor   : 2
BogoMIPS    : 1992.29
processor   : 3
BogoMIPS    : 1992.29
Features    : swp half thumb fastmult vfp edsp thumbee neon vfpv3 tls 
[...]
Hardware    : ODROIDU2

Disk speeds are interesting, first RPi then OU2:

# hdparm -tT /dev/mmcblk0
/dev/mmcblk0:
 Timing cached reads:   340 MB in  2.00 seconds = 169.91 MB/sec
 Timing buffered disk reads:  62 MB in  3.00 seconds =  20.66 MB/sec

# hdparm -tT /dev/mmcblk0
/dev/mmcblk0:
 Timing cached reads:   1616 MB in  2.00 seconds = 808.23 MB/sec
 Timing buffered disk reads:  52 MB in  3.05 seconds =  17.03 MB/sec

I haven’t set up the eMMC card yet, which is said to be several times faster than µSD.

Power consumption of the OU2 is 2.9 W on the AC mains side of a little 5V adapter I’m using. Not bad. I’m tempted to try and set this up as my only always-on server here at JeeLabs, including all the web server stuff even. There’s 2 GB of RAM in this thing, should be enough to run some serious stuff. Perhaps even the (Java-based) CrashPlan backup system I’ve been using for almost a year now.

I don’t really care that much about file storage – a 64 GB eMMC disk would be plenty for everything that needs to be online here at all times, perhaps with an external 2.5″ USB hard disk for secondary / archival backup.

Cheap webcam

In Hardware on Jun 21, 2013 at 00:01

For a project I’m involved in (yeah, yeah, it’ll all be posted in due time), I needed a couple of webcams to take simple snapshots. Started out with a cheap unit from eBay, but that one really wasn’t up to its task. Then I found this limited-stock offer at Conrad:

DSC_4486

It’s €10 and it even includes a headset which I don’t need. Go figure…

Can’t be much, eh? Well, how about 1280×1024 with auto-focus and auto-white balance?

snap

(you can click-through to see the full-size image)

Amazing stuff. Amazing bargains. Amazing internet. Amazing mail-order. Wow…

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:

DSC_4494

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:

SCR67

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:

SCR68

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:

SCR69

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:

SCR70

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):

SCR78

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!

Again?

In Hardware on Jun 18, 2013 at 00:01

After yesterday’s puzzle, I thought that would be the end of it. But sensitised to this, I did check again this morning. And guess what… the problem came back!

Screen Shot 2013-06-17 at 08.32.41

This time, I was determined to find the culprit. Starting around my office with lots of powered devices, I narrowed it down to the power adapter of an Acer Inpire One netbook:

Screen Shot 2013-06-17 at 09.03.52

Seems conclusive, right? Extra evidence: I took that netbook apart a while ago to install more RAM. All went well, except that the battery charge circuit never seems to have recovered – it’s pretty tiny stuff in there, I must have damaged or disconnected something. Luckily, I was using this netbook only in the lab, i.e. plugged in, so no big deal for me.

Except… this netbook was not plugged in before yesterday. This is a different puzzle!

And digging a little deeper, the pattern is not even exactly tied to when it’s plugged in.

Oh well – this gives me an excuse to talk about knapsacks… stay tuned.

Oscilloscope sampling rate

In Hardware, Linux on Jun 16, 2013 at 00:01

Just to finish the series on Raspberry Pi I/O – here’s proof of its GPIO pulsing speed:

SCR57

The trouble is the irregularity caused by Linux’s multi-tasking properties, and I wanted to show you some examples of that. After a few dozen captures, I came up with this one:

SCR58

Looks pretty bad, right? Tons of hickups in what was meant to be a 5.2 MHz pulse train.

Not so fast…

The sample rate used by the oscilloscope for this capture was 10 MHz, so it’s sampling the signal at 100 ns intervals. That’s extremely risky, because when the signal is also pulsing at this rate, you might end up missing each peak for a substantial amount of time. This would make it appear as if the signal was low or high all the time, despite its rapid changes.

This effect is called “aliasing”, and the solution is simple:

Do Not Sample At A Rate Close To The Frequencies In Your Signal!

I’m inclined to discard the above snapshot – it’s probably a measurement artefact.

Here’s another screen, this time at 50 MHz sample rate, i.e. 20 ns between captures:

SCR59

At that rate, it’s impossible to miss pulses which are all in the range of 100 ns or longer. As you can see, there are still glitches (almost on every snapshot there is one), but it’s not as bad as the previous screen shot was suggesting.

Anyway. Enjoy your RPi and all the Linux high-level stuff it can do (like, ehm, run the Arduino IDE and cross-compile stuff for ATmega’s), but beware of treating it like a CPU which is exclusively at your service.

A Raspberry Pi is fast most of the time, but it’s (occasionally) a bit occupied with itself…

Fast I/O on a Raspberry Pi

In Hardware, Linux, Software on Jun 15, 2013 at 00:01

To follow up on yesterday’s post about WiringPi and how it was used to display an image on a colour LCD screen attached to the RPi via its GPIO pins.

A quick calculation indicated that the WiringPi library is able to toggle the GPIO pins millions of times per second. Now this might not seem so special if you are used to an ATmega328 on a JeeNode or other Arduino-like board, but actually it is

Keep in mind that the RPi code is running under Linux, a multi-tasking 32-bit operating system which not only does all sorts of things at (nearly) the same time, but which also has very solid memory and application protection mechanisms in place:

  • each application runs in its own address space
  • the time each application runs is controlled by Linux, not the app itself
  • applications can crash, but they cannot cause the entire system to crash
  • dozens, hundreds, even thousands of applications can run next to each other
  • when memory is low, Linux can swap some parts to disk (not recommended with SD’s)

So while the LCD code works well, and much faster than one might expect for all the GPIO toggling it’s doing, this isn’t such a trivial outcome. The simplest way to deal with the RPi’s GPIO pins, is to manipulate the files and directories under the /sys/class/gpio/ “device tree”. This is incredibly useful because you can even manipulate it via plain shell script, using nothing but the “echo”, “cat”, and “ls” commands. Part of the convenience is the fact that these manipulations can take place entirely in ASCII, e.g. writing the string “1” or “0” to set/reset GPIO pins.

But the convenience of the /sys/class/gpio/ virtual file system access comes at a price: it’s not very fast. There is too much involved to deal with individual GPIO pins as files!

WiringPi uses a different approach, called “memory mapped files”.

Is it fast? You bet. I timed the processing time of this snippet of C code:

int i;
for (i = 0; i < 100000000; ++i) {
  digitalWrite(1, 1);
  digitalWrite(1, 0);
}
return 0;

Here’s the result:

    real    0m19.592s
    user    0m19.490s
    sys     0m0.030s

That’s over 5 million pulses (two toggles) per second.

This magic is possible because the I/O address space (which is normally completely inaccessible to user programs) has been mapped into a section of the user program address space. This means that there is no operating system call overhead involved in toggling I/O bits. The mapping is probably virtualised, i.e. the kernel will kick in on each access, but this is an interrupt straight into protected kernel code, so overhead is minimal.

How minimal? Well, it takes less than 90 ns per call to digitalWrite(), so even when running at the RPi’s maximum 1 GHz rate, that’s less than 90 machine cycles.

Note how the RPi can almost toggle an I/O pin as fast as an ATmega running at 16 MHz. But the devil is in the details: “can” is the keyword here. Being a multi-tasking operating system, there is no guarantee whatsoever that the GPIO pin will always toggle at this rate. You may see occasional hick-ups in the order of milliseconds, in fact.

Is the RPi fast? Definitely! Is it guaranteed to be fast at all times? Nope!

What it took to generate that LCD image

In Hardware, Linux, Software on Jun 14, 2013 at 00:01

As shown yesterday, it’s relatively easy to get a bitmap onto an LCD screen connected to a few I/O pins of the Raspberry Pi.

But there were some gotcha’s:

  • the image I wanted to use was 640×480, but the LCD is only 320×240 pixels
  • the WiringPi library has code to put a bitmap on the screen, but not JPEGs
  • this is easy to fix using the ImageMagick “convert” command
  • but the result has 24-bit colour depth, whereas the LCD wants 16-bit (5-6-5)

The “convert” command makes things very easy, but first I had to install ImageMagick:

    sudo apt-get install ImageMagick

Then we can run “convert” from the command-line (long live the Unix toolkit approach!):

    convert snap.jpg -geometry 320x240 -normalize snap.rgb

This handles both the rescaling and the transformation to a file with (R,G,B) types, each colour is one byte. As expected, the resulting image file is 320 x 240 x 3 = 230,400 bytes.

I didn’t see a quick way to convert the format to the desired 5-6-5-bit coding needed for the LCD, and since the code to write to the LCD is written in C anyway (to link to WiringPi), I ended up doing it all in a straightforward loop:

#define PIXELS (320*240)
uint8_t rgbIn24 [PIXELS][3];
unsigned rgbOut15 [PIXELS];

[...]

for (x = 0; x < PIXELS; ++x) {
  uint8_t r = rgbIn24[x][0] >> 3;
  uint8_t g = rgbIn24[x][1] >> 2;
  uint8_t b = rgbIn24[x][2] >> 3;
  rgbOut15[x] = (r << 11) | (g << 5) | b;
}

Note that this is a C program compiled and running under Linux on the RPi, and that it can therefore easily allocate some huge arrays. This isn’t some tiny embedded 8-bit µC with a few kilobytes – it’s a full-blown O/S running on a 32-bit CPU with virtual memory!

The other gotcha was that the bitmap to be supplied to the LCD library on top of WiringPi was expected to store each pixel in a 32-bit int. Total waste of space, and probably the result of a rushed port from the UTFT code (written to assume 16-bit ints) to the RPi. Which is why rgbOut15 is declared as “unsigned” (int, i.e. uint32_t) array, although the image really only needs an uint16_t. Oh well, what’s an extra 150 kB, eh?

Anyway, it works. Perfection can wait.

Note that this sends out all the data pixel by pixel to the display, and that each pixel takes the bit-banging of 2 bytes (the interface to the LCD is 8-bit wide), so each pixel takes at least 20 calls to digitalWrite(): 8 to set the data bits, and 2 two to toggle a clock pin – times two for the 2 bytes per pixel. That’s at least 4.6 million GPIO pin settings in half a second!

Tomorrow, I’ll show how WiringPi can make GPIO pins change in under 100 nanoseconds.

Getting an image on the LCD

In Hardware, Linux on Jun 13, 2013 at 00:01

To follow up on yesterday’s setup, I’ve managed to drive the display from Linux, using the WiringPi library by Gordon Henderson.

It supports driving the Raspberry Pi’s GPIO pins from C using Arduino- / Wiring-like calls to digitalWrite(). That, in combination with the UTFT library by Henning Karlsen, and some work done by iTead to combine everything was enough to get this self-portrait:

DSC_4482

The display is a bit shiny, and the contrast and brightness are a bit low, unfortunately :(

Drawing the image takes about half a second, but considering that it’s all done through bit-banging of a few I/O pins from a “user space” program, that’s pretty good actually!

There are a couple of interesting (and sneaky) details, which I’ll go into in the next post.

Hurray for open source and the remixing / sharing it enables!

LCD screen for the RPi

In Hardware, Linux on Jun 12, 2013 at 00:01

For a little side-project I’m involved in (more on that in a future post), I wanted to try adding a little LCD screen with touch sensor to a Linux setup. Found this one at iTead:

DSC_4480

There’s a little ribbon cable and adapter (just re-wiring) available for it, which allows plugging this thing into a Raspberry Pi. The nice thing about this screen, apart from being 320×240 pixels and 16-bit color TFT, is its physical size – just right for a stacked setup:

DSC_4481

Stay tuned, as I explore how to hook this thing up and make it show stuff…

Accurate timing with jittery packets

In Hardware on Jun 11, 2013 at 00:01

A few days back I mentioned the SYNC message mechanism in CANopen, and how it can have about 150 µs jitter when sent out on a CAN bus running at 1 Mbit/s.

Here’s the basic idea of sending out SYNC packets at a pre-defined fixed rate:

JC's Grid, page 78

Once you have such a mechanism, you can do things like send out commands which all devices need to perform on the next sync for example. Nice for controlling the X, Y, and Z axis of of a CNC machine with the accuracy needed to make them all move exactly in sync.

The SYNC message has a very very high priority on the CAN bus, but even so, it can be delayed if it wants to send while some other transmission is taking place. So even though it will probably be first one to go out, it still has to wait for the bus to become available:

JC's Grid, page 78 copy

As a result, that SYNC pulse we wanted to arrive on time T ended up coming in at T + X. With X being under 200 µs when the bus is running at 1 MHz, but still.

Can we do better?

Yes, and no. We can’t avoid the jitter in that SYNC packet. But while the master sending out that SYNC packet cannot time it more precisely, it does know when the packet actually went out. So it does in fact know what T + X ended up being for that transmission.

And here’s the clever bit: the master can now send out a second (slightly lower priority) packet with a time stamp in it, i.e. containing that “T + X” value, down to the microsecond in fact. The arrival time of that time stamp packet is not so important. What matters is that each slave tracks exactly when the sync came in, and then uses the time stamp to adjust for any difference or drift that may be taking place.

This won’t help make the SYNC pulses come in more accurately, but it will let each slave know exactly what the time of that pulse was, and hence how accurately their own clocks are running. With this mechanism, all clocks can safely be assumed to run within 1..2 µs of each other, and therefore all future commands can now be tied to specific times which are known to be matched up between all slaves with two orders of magnitude better accuracy.

Ingenious, that CAN bus, eh?

What’s inside that chip?

In AVR, Hardware on Jun 9, 2013 at 00:01

Came across an interesting post the other day, from a Russian site which looks “under the hood” of some sophisticated chips – some well-known in the West, some less so.

First, the technique of using sulfuric and nitric acid is described and illustrated:

SONY DSC

But the really bit interesting bit is what comes out. Here’s the ATmega8:

atmega8

(both pictures were copied from that site, i.e. zeptobars.ru – I hope that’s ok)

The size of this chip is 2855 x 2795 µm, i.e less than 3 x 3 mm.

Fascinating! I wonder what all the different bits and pieces are…

Trying out CANopen

In ARM, Hardware on Jun 8, 2013 at 00:01

Time for some electronics doodling… here are two LPCxpresso boards, with LPC11C24 ARM chips on each. One of them has been cut in half and hacked, as you can see:

DSC_4477

The reason for using this chip is that they have CANopen drivers built into them, in ROM. That makes it a lot easier to get started, with so many things being unclear anyway – from the compiler toolchain (I ended up with a mix of ARM’s Linaro toolchain and NXP’s LPCxpresso IDE), to figuring out how to get a basic CAN packet on the bus and off again.

Anyway, couple of days of hardware + firmware tinkering, and here’s the result:

SCR56

I’m getting a lot of mileage out of the Hameg HMO2024 scope as you can see, including its hardware CAN bus decoding (a paid option, but free at the time I got the intro bundle).

You’re looking at 4 packets, i.e. 2 request/response pairs going over the bus.

Note how the voltages are jumping up and down a bit. For CAN, this is irrelevant, because it works based on the difference between the CAN-L and CAN-H levels. It’s caused by the master node running its CAN interface at a slightly lower voltage (USB + diode drop). Then again, it’s rather useful for debugging because you can see who sends what! As is clearly visible above, the ACK bit comes from the other node in each exchange.

In terms of speed, there’s one packet every 145 µs, which translates to 55 Kbyte/sec for the 8-byte payload, i.e. 440 Kbit/s out of 1000 Kbit/s actual throughput (more, since there is also an address, the ACK bit, etc). It might not seem like much, but keep in mind that this is also the worst-case timing. The CAN bus does not start thrashing or losing packets when pushed to its limit – all that can happen on a maximally loaded-bus is that the lowest-priority messages will hardly ever get a chance to pass through.

On the software side, a CAN bus is really quite simple to use, since the built-in hardware does all the hard work of acquiring and releasing the bus, resending on packet damage (a noise spike, for example), adding and checking CRCs, buffering a few incoming packets, and even filtered reception – so that only specific ranges of message IDs get picked up.

Not much of this is available for Atmel chips, alas. And that ARM world sure is a lot less physical computing friendly w.r.t. open-source and platform-agnostic toolchains.

All those ARM Cortex chip manufacturers still seem to be living in the dark ages…

CANopen sits on top of CAN

In Hardware on Jun 7, 2013 at 00:01

The CANopen protocol sits on top of the low-level CAN bus protocol. Due to the way CAN bus packets are tagged with a message ID, but not specifically routed from or to a specific device (i.e. node), and due to the maximum packet payload size of 8 bytes, you really need something like CANopen to make it usable. For reference, here’s a 2-node CAN bus setup:

can-term

The interesting bit about CANopen, is that it’s all about data acquisition and process control (that’s what you do when you put this stuff in a car, after all). And what intrigues me about that, is the similarity with monitoring and controlling stuff around the house.

I’ve been reading myself silly lately, to wrap my head around all the CANopen terminology and to try and distill the essence of… ehm, CANopen, life, and a few other things :)

But instead of just describing CANopen as it is, and pouring lots of its concepts and new terminology on you, let me try to describe this from an outsider’s perspective:

  • CANopen works in terms of accessing and saving objects. It’s not necessarily 100% centralised, but that’s how it often gets used: a central CANopen node to control, inquire, and manage a bunch of CANopen slave nodes, all on the same CAN bus.

  • There are a lot of conventions w.r.t. these objects, because the goal of CANopen is to allow devices from different manufacturers to inter-operate (that’s probably why it’s called “open”). So there’s a standard way to find out which devices are present and what their basic capabilties are, to enable/disable each one of them, to configure their communication settings, to start and stop data acquisition streams – all with lots of room for manufacturer- and device-specific details to be managed as well.

  • The central concept here is the “Object Dictionary” in each device, which is indexed by a 16-bit number, plus a numeric 8-bit subindex for entries which are more structured. Objects can be 1..4 bytes, in which case they can be exchanged in one packet, or larger, in which case CANopen takes care of all the packing and unpacking.

  • There is a simple yet effective heartbeat mechanism, so that each device (and of course also the master) can figure out which devices are currently present, which are active, and – with timeouts – which devices seem to have dropped out for some reason.

  • Each device announces itself when powering up, so auto-discovery is possible, even for devices which the master has never seen before – although it’ll be more effective when the master has a detailed description of each type of device, so that it can optimally manage and control it.

  • There are mechanisms for urgent error reporting, dropping out gracefully, and throttling to avoid bus congestion.

  • Everything is prioritised (the CAN bus does that), with top priority (msg ID 000) given to essential (but infrequent) master messages, such as starting and stopping device activity on the bus. Note that, due to the top priority, these will always get through.

  • Next in priority is a time synchronisation message, which can be used to make all device clocks “sing in sync”. With a 1 Mbit/s bus rate, these sync messages will never have more than about 150 µs jitter (and there’s a clever optional scheme to increase the time resolution in all slaves to 1 µs).

There is much more which I can’t all describe in this post, but the one design idea I’d like to highlight is the distinction between managing a large set of objects (via SDO’s, i.e. Service Data Objects) and maximally efficient data streams (via PDO’s, i.e. Process Data Objects). Where PDO’s can be set up to be sent across in a regular time-synchronised manner or in a more ad-hoc / event-based / asynchronous fashion.

I really like this distinction: there is a large heterogenous mix of data objects, which can be accessed and changed via individual SDO requests, and there are streams of PDO data which don’t waste time and bandwidth on describing themselves – just the raw bytes. The heterogenous data objects can fully describe those streams, their exact byte (even bit) structure, the conditions under which data gets sent, their frequency, and their priority.

Lots of interesting connections with the way the RF12 driver sends packets, the announcer packet idea, and the way HouseMon distinguishes between incoming data and the meta-data inside each driver describing these incoming packets.

A thousand days!

In AVR, Hardware on Jun 6, 2013 at 00:01

It’s getting a bit repetitive, but I just noticed this:

Screen Shot 2013-06-05 at 17.27.15

That’s over 1000 days of sending out one packet a minute on this thing:

dsc_1822

… and over 100 days on the recent JeeNode Micro v3:

DSC_2858.jpg

The battery boost version runs off a single Eneloop AA battery, and is doing fine too:

DSC_4401

Onwards!

What if you’re out of wireless range?

In Hardware on Jun 5, 2013 at 00:01

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

Ok, so you’ve got some JeeNodes up and running, all talking to each other or to a central node via the wireless RFM12B module. Or… maybe not: the signal is too weak! Now what?

There are several approaches you can try to improve wireless range:

  • optimise your existing antenna(s)
  • lower the data rate and reduce the bandwidth
  • use a more advanced type of antenna
  • use a directional antenna
  • install a repeater of some kind

Let’s go through each of these in turn.

First thing to try is to optimise the little wire “whip” antenna’s that come standard with a JeeNode. Make sure the antenna wire is 82 mm long (that’s for 868 MHz), is sticking up (or sideways) perpendicular to the board, and check that both antenna’s are pointing more or less in the same direction (but not in the direction of the other node: the RF field is circular around the wire, not on top or below).

One thing to keep in mind with these weak signals, is that salty bags of water (us people, that is) tend to absorb RF energy, so these radios work better with us out of the way. Be sure to take a step back while tweaking and hunting for the best orientation!

If that doesn’t help enough, you can do one more thing without messing with electronics or hardware: reduce the datarate of the transmitter and receiver (they have to match). See the RFM12B Command Calculator for settings you can change. To reduce the data rate by two thirds, call rf12_control(0xC614) after the call to rf12_initialize(), for example. The bad news is that you have to do this in all the nodes which communicate with each other – all the data rates have to match!

This in itself won’t extend the range by that much, but with lower data rates you can also reduce the bandwidth in the receiver (with rf12_control(0x94C2)). You can think of this approach as: speaking more slowly and listening more closely. The effects should be quite noticeable. Radio amateurs have been using this technique to get halfway around the world on mere milliwats, using a system called QRSS.

If that doesn’t give you the desired range – here are a few more tricks, but they all require extra hardware: improve the antenna, use “directional” antennas, or use a repeater.

Here’s an example of an improved omni-directional antenna design, as seen on eBay:

omni-antenna

And here’s a directional “Yagi” antenna, which needs to be aimed fairly accurately:

yagi

I haven’t tried either of these (you can build them yourself), but the omni-directional one was mentioned and described in Frank Benschop’s presentation on JeeDay. He reported getting quite good results, once all the antenna + cabling quirks were resolved.

If neither of these are an option, then the last trick you can try is to add a relay / repeater node to your network, as described in this weblog post some time ago. This will double the range if you place that node in the middle of the two nodes which can’t reach each other, but it adds some complexity to the packet addressing mechanism.

Move over, raspberry

In Hardware, Linux on Jun 4, 2013 at 00:01

The Raspberry_Pi is a great little board at an amazing little price. But as mentioned yesterday, it’s not very fast as a server. I suspect that a lot of it has to do with the SD card interface and the SD card itself, so I started looking around for alternatives.

And boy, there sure are lots of ‘em – still well below €100. I’ll single out one system, the Odroid U2 – knowing full well that there must be over a dozen others out there:

article_img

It’s smaller than a Raspberry Pi, but it comes mounted on a “big” (6x6x6 cm) heat sink.

The specs are pretty impressive:

Screen Shot 2013-06-01 at 11.45.13

And the board is neat – the result of a huge mobile phone market driving size down:

201301251344193656

201301251345520979

Could this be used as central web / file / home automation server?

Speedy Raspberry

In Hardware, Linux on Jun 3, 2013 at 00:01

The Raspberry Pi is an amazing little board, with an amazing amount of power and functionality at an incredible price – it’s probably fair to say that our technology geek’s world will never be the same again, now that we have the RPi.

But it’s no speed monster…

Sometimes during development, it really gets in the way – especially when you’re used to working on a modern fast laptop, which is some 20 times faster (and that’s per-core).

So I decided to overclock one of my RPi’s, and see what it does. Overclocking in Raspbian is trivial with the standard raspi-config utility:

Screen Shot 2013-05-28 at 16.52.58

Just go to the Overclock section, and pick one:

Screen Shot 2013-05-28 at 16.46.48

I went for the fastest there is, but decided to run a 2-hour test to make sure it really works. Turns out that someone has already done all the work, and even created such a stress test:

root@raspberrypi:~# ./overclock-test.sh 
Testing overclock stability...
reading: 1
945+1 records in
945+1 records out
3965190144 bytes (4.0 GB) copied, 352.455 s, 11.3 MB/s
reading: 2
[...]
reading: 10
945+1 records in
945+1 records out
3965190144 bytes (4.0 GB) copied, 358.522 s, 11.1 MB/s
writing: 1
512+0 records in
512+0 records out
536870912 bytes (537 MB) copied, 95.2065 s, 5.6 MB/s
writing: 2
[...]
writing: 10
512+0 records in
512+0 records out
536870912 bytes (537 MB) copied, 83.4848 s, 6.4 MB/s
./overclock-test.sh: line 18:  2414 Terminated
              nice yes > /dev/null
CPU freq: 1000000
CPU temp: 58376
[    5.217175] Registered led device: led0
[    8.943589] EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)
[    9.418819] EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)
[   19.181046] smsc95xx 1-1.1:1.0: eth0: link up, 100Mbps, full-duplex, lpa 0x45E1
[   19.431053] bcm2835-cpufreq: switching to governor ondemand
[   19.431082] bcm2835-cpufreq: switching to governor ondemand
[   21.736829] Adding 102396k swap on /var/swap.  Priority:-1 extents:1 across:102396k SS
[   22.134893] ip_tables: (C) 2000-2006 Netfilter Core Team
[   22.174573] nf_conntrack version 0.5.0 (7774 buckets, 31096 max)
[  750.951153] smsc95xx 1-1.1:1.0: eth0: kevent 2 may have been dropped
Not crashed yet, probably stable.

Ya gotta love that last message, nicely semi re-assuring ;)

I did fit a set of cooling fins from Watterott (some nice IR heat pictures there):

DSC_4475

As checked with vcgencmd measure_temp, the temperature never rose above 58.4°C.

Onwards!

Solar PV production

In Hardware on Jun 2, 2013 at 00:01

This is the sort of graph I’ve been waiting for – now that there is more sun, at last:

Screen Shot 2013-05-29 at 00.28.30

(the steep increases and decreases are probably due to shadows from the other roofs)

All values were obtained from the SB5000TL inverter as 5-minute readouts over Bluetooth:

  • total delivered power on AC mains – 29 kWh for the entire day
  • total incoming power on the east-facing roof (12 panels)
  • total incoming power on the west-facing roof (10 panels)

The east-facing panels are actually slight to the north, and the west-facing ones slightly to the south. Which might explain the similar peak production levels despite the different number of panels, i.e. different “insolation” angles.

The peak values are not the highest I’ve seen so far. A cold day with light clouds recently pushed the maximum to over 4700 watts. But that was a rare event. These values are fine with me – I find such levels of solar PV output in a location well up north on this planet (52°N, to be precise) pretty amazing, in fact.

It takes two to CAN

In ARM, Hardware on Jun 1, 2013 at 00:01

The CAN bus described yesterday keeps drawing my interest. It feels right on many levels…

Anyway, for a real CAN bus test, I’ve set up two nodes, to be able to see a full handshake:

SCR39

That’s one node sending out a 0x101 packet, and another node responding to it with a 0x202 packet with the same payload. There are lots of interesting things going on here:

  • The CAN protocol requires any receiving node to send out an ACK bit the moment it has received a valid packet – this doesn’t tell the sender who got it – only that some node was listening and got it. The only thing you can conclude at this stage really, is that there is actual communication – it’s up to higher level layers to verify things.

  • The sender is a node connected to a 3.3V-based CAN transceiver, so the voltages it puts out on the bus are lower than the receiving / echoing node (which is an ARM-based LPCxpresso 11C24 board with a 5V transceiver, running a standard CAN example in the LPCxpresso IDE). As you can see, voltages are hopping a bit, but all that matters is the voltage difference between the two lines, so everything is fine.

  • There is no one listening to the reply, so the LPC11C24 doesn’t get a good ACK on that, and keeps re-sending the packet. It does this a number of times and will then give up.

  • The Hameg HMO2024 scope with its added serial decoding options is very effective in this setup – I made it trigger on a 0x202 packet, and it shows a nice list of the data it has captured. Since I’m using the analog channels, the levels are also clearly visible.

  • The bus is running at 500 KHz, so the basic bit timing is in multiples of 2 µs. Zooming in, I saw that the gap between each packet is 22 µs, which matches exactly the CAN bus specs requiring nodes to wait for at least 11 idle bits before they start. Speaking of which: the CAN names for “0” and 1″ are “dominant” and “recessive”, respectively – because a dominant bit always wins and forces the bus to a “0” (voltage applied).

  • The packet times here are ≈ 250 µs, so there’s some 10% of overhead for the gaps between packets, and the total “overhead” for getting 8 bytes of payload across (i.e. 128 µs) is about 100% – but that includes things like bit-stuffing, a message ID, a CRC check, and an ACK. Half the theoretical bit rate to be able to send real-time data with little latency, good reliability, and precisely tagged is actually very good.

Note that the CAN bus requires special transceiver chips. The level conversions are minimal (from “0” and “1” to pulling the two lines apart, in terms of voltage), but what they also add is a substantial amount of protection against common-mode signals, which is when both signals move up or down by the same voltage. This is extremely important in a car, where large currents can lead to huge spikes and voltage changes, but it really doesn’t hurt in other applications either: the CAN bus is a very nice way to tie pieces together – and when there is an issue with ground levels, the whole design even allows for opto-couplers to be used for complete isolation between nodes.

The “standard” way to hook up CAN nodes is through three pins (CAN-H, CAN-L, and GND), but it’s not uncommon to include a +5V supply pin, making this a neat 4-wire bus.

Yes, we CAN bus

In Hardware on May 31, 2013 at 00:01

The CAN Bus is a very interesting wired bus design, coming from the automobile industry (and probably built into every European car made today). It’s a bus with an ingenious design, avoiding bus collisions and supporting a good level of real-time responsiveness.

I’ve been intrigued by this for quite some time, and decided to dive in a bit.

There are several interesting design choices in CAN bus:

  • it’s all low-voltage, just 0..5V (even 0..3.3V) is all it takes on each connected node
  • the bus is linear, reaching from 40 m @ 1 Mbit/s to 500 m @ 125 kbit/s, or even longer
  • signalling is based on voltage between two wires, and terminated by 120 Ω on each end
  • signals are self-clocked, with bit-stuffing to insert bit-transitions when needed

But the three most surprising aspects of the CAN bus design are probably the following:

  • the design is such that collisions cannot happen: one of the two senders always wins
  • each CAN bus packet can have at most 8 bytes of data (and is CRC-checked)
  • as described recently, messages have no destination, but only a message ID (type)

What’s also interesting is that – like I2C – this protocol tends to be fully implemented in hardware, and is included in all sorts of (usually ARM-based) microcontrollers. So unlike UARTs, RS485, I2C, and SPI, you simply get complete and valid packets in and out of the peripheral. No need to deal with framing, CRC checking, or timing decisions.

You can almost feel the car-like real-time nature of these design trade-offs:

  • short packets – always! – so the bus is released very quickly, and very often
  • no collisions, i.e. no degradation in bus use and wasted retransmits as it gets busier
  • built-in prioritisation, so specific streams can be sent across with controlled latencies
  • with a 16-bit CRC on each 0..8 byte packet, chances of an undetected error are slim

Since my scope includes hardware CAN bus decoding, I decided to try it out:

SCR37

The message has an ID of 0x101 (message ID’s are either 11 or 29 bits), eight bytes of data (0xAA55AA55FF00FF00), and a CRC checksum 0x1E32. I’m using a 500 KHz bit clock.

If you look closely, you can see that there are never more than 5 identical bits in a row. That’s what bit-stuffing does: insert an opposite bit to avoid longer stretches of identical bits, as this greatly helps deduce exact timings from an incoming bit-stream.

It seems crazy to limit packets to just 8 bytes – what could possibly be done with that, without wasting it all on counters and offsets to send perhaps 4 bytes of real data in each packet? As it turns out, it really isn’t so limiting – it just takes a somewhat different mindset. And the big gain is that multiple information streams end up getting interleaved very naturally. As long as each of them is reasonable, that is: don’t expect to get more than 2 or 3 data streams across a 1 Mb/s bus, each perhaps no more than 100 kb/s. Then again, you can expect these to arrive within a very consistent and predictable time, regardless of what other lower-priority burst traffic is going on.

Neat stuff…

90 days on a coin cell

In Hardware on May 26, 2013 at 00:01

Just saw that my JeeNode Micro test setup has been running and “blipping” for 90 days:

Screen Shot 2013-05-25 at 11.08.00

The voltage is starting to drop a bit, and the voltage drop before and after using the radio has increased from 0.08 to 0.16 V (reported with a granularity of 0.02 V), but everything seems to be fine. It has pumped out over 120,000 packets so far.

The other test is a JeeNode Micro with boost regulator, running of one Eneloop AA battery. That battery voltage has also dropped a bit, but as you can see, the boost regulator is doing its thing and still providing the exact same 3.04 V as it did when the test was started.

It’ll be interesting to see how long each of these setups holds out. I have no idea, really. It’s not just a matter of capacity – with the coin cell, it’ll also depend on how long the battery can continue to provide these brief 20..20 mA power bursts for each transmission.

Onwards!

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 www.kitenergie.com, with thanks:

MPPT_knee_diagram

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:

SCR27

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:

SCR26

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:

SCR28

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:

SCR24

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:

SCR25

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:

SCR31

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 :)

DSC_4454

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);
  delay(8000);
}

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:

DSC_4453

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

Perfect!

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:

DSC_4452

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:

SCR12

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 () {
    cli();
    Sleepy::powerDown();
}

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:

SCR14

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):

SCR11

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

20130216_364130

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.

What if I turn the chip around?

In Hardware on May 8, 2013 at 00:01

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

Ok, you’re all excited, you’ve built some electronic circuit – either by assembling a kit, or all on a breadboard, or perhaps you’ve even go so far as to design and create a custom PCB.

Any non-trivial circuit will have polarised components on it, whether capacitors, diodes, transistors, regulators, or… the most common one in oh so many varieties: a “chip”, with 6..40 pins, or sometimes even more.

Mr. Murphy loves chips. Because sooner or later, you’ll connect one the wrong way around. Even if you know what you’re doing, sometimes the orientation marker on a chip is fairly hard to see, especially on the smaller SMD types.

So what happens if we put things in the wrong way around?

Obvious answer: it depends (on the chip).

Comforting answer: more often than not, nothing will happen, the thing will get hot, and it’ll still work fine once you fix the problem, i.e. turn the chip around and reconnect it.

The good news is that it’s not so easy to really damage most chips, with a few precautions:

  • use a “weak” power supply, i.e. one which can’t put out to much current, as current leads to heat, and heat is usually the cause of component damage – a lab power supply with adjustable “current limiting” set to a low value is a very good idea
  • keep your hands near the ON/OFF switch when powering up a circuit for the first time, keep your eyes open, and … use your nose: bad stuff due to heat often shows itself as smoke (by then, it’s often too late), and as components getting far too hot, and starting to smell a bit
  • for low-voltage circuits, and this includes almost all digital circuits: place your fingers on several of the key components right after turning power on: if you sense anything getting hot, turn off the power – NOW!
  • sensing heat is an excellent way to save a project from serious damage: we can easily tell if something heats up to 50 °C or more, yet most silicon-based chips will be able to heat up way beyond that before actually getting damaged (125..175 °C) – so as long as you turn the power off quickly enough, chances are that nothing really will break down, and chips and resistors will often start to smell – a useful warning sign!

Note that analog circuits tend to get damaged much more easily. Put a transistor the wrong way around, and it’ll probably go to never-never land the moment power is applied.

One reason digital chips are so resilient, is the fact that they are full of ESD diodes. These tend to be on each of the I/O pins of a chip, as protection against Electrostatic Discharge. Here’s what a typical I/O pin circuit on a digital chip looks like:

JC's Grid, page 72

Nothing happens under normal conditions, since the diodes are all in blocking mode. When the I/O pin voltage rises above VCC or drops below GND, however, the diodes start to conduct, while trying to remove the charge, so that the voltage levels never reach values which might damage the sensitive oxide isolation (that’s the “O” in CMOS and MOSFET).

Now have a look at what happens when a chip gets powered up with bad voltages on two of the I/O pins (the light-blue parts are not conducting and can be ignored):

JC's Grid, page 72 copy

The way to look at this is that the pin(s) with the highest voltage will start feeding into the (internal) VCC connections, and the pins with the lowest voltage will start drawing current from the (internal) GND connections. Or, to put it a different way – some I/O pins will act as VCC and GND supply lines, albeit with some internal ESD diodes in between:

JC's Grid, page 72 copy 2

In this diagram, VCC and GND are fed from pins which were not intended as such!

As you can see, the diodes now start conducting as well, drawing a certain amount of current. If these currents are not higher than the diodes can handle (usually at least a few mA per diode), then the chip will act more or less like a short to the rest of the circuit. With a bit of luck, your power supply will decide to lower its output voltage and enter “current limiting” mode. The result: nothing works, but nothing truly dramatic happens either. It just gets hot and all the voltages end up being completely wrong.

Sooo… next time you power up your new project for the first time: stay alert, use your fingers, be ready to cut power, and… relax. If it doesn’t work right away (it hardly ever does!), you’ll usually have time to figure out the problems, fix them, and get going after all.

Note that there are no guarantees (things do occasionally break), but usually it’s fixable.

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:

DSC_4448

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:

SCR11

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

Embedded Linux – Carambola 2

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

This has got to be one of the lowest-cost and simplest embedded Linux boards out there:

DSC_4447

It’s the Carambola 2 by 8devices.com:

Screen Shot 2013-05-04 at 11.02.06

The 28 x 38 mm (!) bare board is €19 excl VAT and shipping, and the development bundle (as shown above) is €33. The latter has a Carambola2 permanently soldered onto it, with 2 Ethernet ports, a slave USB / console / power port, a USB host port, a WiFi chip antenna (which is no longer on the base board, unlike the original Carambola), and a switching power supply to generate 3.3V from the USB’s 5V.

The processor is a MIPS-based Atheros chip, and with 64 MB ram and 11 MB of available flash space, there is ample room to pre-populate this board with a lot of files and software.

The convenience of the development setup, is that it includes an FTDI chip, so it comes up as a USB serial connection – you just need to find out what port it’s on, connect to it at 115200 baud via a terminal utility such as “screen” on Mac or Linux, and you’ll be hacking around in OpenWrt Linux in no time.

Note that this setup is very different from a Raspberry Pi: MIPS ≠ ARM, for one. The RPi has a lot more performance and RAM, has hardware floating point, and is more like a complete (portable) computer with its HDMI video out port. The benefit of the Carambola 2 is its built-in WiFi, built-in flash, and its low power – more on that tomorrow.

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:

DSC_4443

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:

DSC_4440

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):

20130206_765416

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:

20130206_765722

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:

SCR01

(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:

DSC_4438

DSC_2780.jpg

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.

Autotransformer

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:

DSC_4444

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

DSC_4445

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

DSC_4446

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:

300px-Tapped_autotransformer.svg

(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.

What if the supply is under 3.3V?

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

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

To follow up on a great suggestion from Martyn, here’s a post about the different trade-offs and implications of running an ATmega at lower voltages.

The standard Arduino Uno, and all models before it, have always operated the ATmega at 5.0V – which used to be the standard TTL levels used in the 7400 series of chips used in the 1960’s and 1970’s. The key benefit of a single standardised voltage level being that it made it possible to combine different chips from different vendors.

To this day, even though most semiconductor logic has evolved from bipolar junction transistor to CMOS, the voltage level has often been kept at 5V, with slightly adjusted – but compatible – voltage levels for “0” and “1”, respectively.

Nowadays, chips operate at lower voltages because it leads to lower power consumption and because it is a better fit for batteries and LiPo cells. In fact, lots of new chips operate at 3.3V and will not even tolerate 5.0V.

The ATmega328p is specified to run at a very wide range, from 1.8V all the way up to 5.5V. Which is great for ultra low-power use, supporting different battery options, and even for energy harvesting scenario’ such as a solar panel charging a supercap, for example.

But there are still many trade-offs to be aware of!

The first one is the system clock rate, which is limited (see also this older post):

Screen Shot 2013-04-30 at 21.59.07

If you look closely, you’ll see that 16 MHz is out of spec for 3.3V, the way the JeeNode is running, that is. In practice, this has never caused any known problems, but lowering the voltage further might just be too much.

The good news is that it’s not really the crystal oscillator which is causing problems, but the main circuitry of the ATmega, and that there’s a very easy fix for it: when running at voltages below 3.3V, you should set the ATmega’s pre-scaler to 2, causing the system clock to run at 8 MHz. When running even lower, perhaps under 2.4 V or so, set the pre-scaler to 4, i.e. run the system clock at 4 MHz. This also explains the presence of the divide-by-8 fuse bit: when you need to start up at low voltages, you can force the ATmega to always power up with a clock pre-scaler of 8, and then adjust the pre-scaler under software control after power-up, once the voltage has been verified to be sufficient. Without this setting, an ATmega would not be able to reliably start up at 1.8V, even if it’s meant to run much faster most of the time.

Note that the RF12 driver will still work at 4 MHz, but not less: the interrupt service time will be too slow for proper operation at any slower rate.

Another important issue to be aware of when running a JeeNode at voltages under 3.3V, is that the MCP1702 voltage regulator will no longer be able to regulate the incoming voltage. It can only reduce the input voltage for regulation, so when there is no “headroom” left, the regulator will just pass whatever is left, minus a small “dropout” voltage difference. Hence its name LDO: Low-DropOut.

The problem is that all LDO regulators start consuming (i.e. wasting) more idle current in this situation. See this weblog post for the measured values – which can be substantial!

To avoid this, you should really disconnect the LDO altogether, or at least its ground pin.

A third aspect of running at lower voltages, is that you need to verify that all the parts of the circuit continue to work. This applies to sensors as well as to the RFM12B radio – which should only be operated between 2.2V and 3.8V.

Actually, some experiments a while back showed that the radio could work down to 1.85V, but I suspect that things like transmit power will be greatly reduced at such supply levels.

Lastly, when the supply voltage is lowered, you need to keep some secondary effects in mind: the ADC will operate against a lower reference voltage as well, so its scale will change. One ADC step will be just under 3.3 mV when the supply is 3.3V, but this drops to under 2.0 mV per step with a 2.0V supply.

To summarise: yes, an ATmega/ATtiny can run at voltages below 3.3V, and even an entire JeeNode can, but you need to reduce the system clock by switching the pre-scaler to 2 or 4, and you need to make sure that all parts of your setup can handle these lower voltages.

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:

DSC_4441

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:

DSC_4442

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):

SCR02

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)

And:

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):

SCR94

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):

SCR95

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:

SCR96

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:

SCR97

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.

New series – What If?

In Hardware, News, Software on Apr 23, 2013 at 00:01

Questions are very useful: “what would happen if…” is the foundation of science, after all.

Conjectures and Refutations is a famous book by the late philosopher Sir Karl Popper. I could not possibly summarise it (heck, I haven’t even read it), but what I take away from what I’ve read and heard about it, is that theories can be judged on their predictive value. A theory in itself is no more than an intellectual exercise, but its real value lies in being able to apply it to what-if questions. The stronger a theory, the better it should predict outcomes. The way to “refute” a theory, is to come up with an example where it fails. Rinse and repeat, and you’ve captured the essence of science.

Want to predict what will happen when you place a 100 Ω resistor across a 9V battery? That’s easy, given the proper theory: take Ohm’s Law (i.e. a theory which has stood the test of time), and apply it – a current of ≈ 11 90 mA will flow. Actually a bit less due to the internal resistance of the battery, which goes to show how strong theories can be refined further, leading to even more accurate predictions.

The what-if question is a great way to experiment, especially in electronics and electro-mechanics, because it lets you be prepared and avoid silly (and sometimes catastrophic) outcomes, such as a damaged component, a harmful burn, or even an explosion.

This approach lends itself to all sorts of practical questions:

  • What if I short out a 3x AA battery pack?
  • What if I connect my chip the wrong way around?
  • What if I have to use a 12V power supply instead of 5V?

But also issues as varied as:

  • What if I omit a certain component from my circuit?
  • What if I unplug the Raspberry Pi without shutting it down?
  • What if I wanted to use HouseMon in combination with MySQL?

Properly phrased, what-if questions are essential for practical experiments, and – by extension – also the key to building useful circuits and automated installations.

A useful variation of the what-if question is to help predict “bad” outcomes and estimate the risk of an experiment, such as: can shorting out my power supply cause real damage?

Starting tomorrow, I’m launching a new series on this weblog, titled “What-If Wednesday”. As far as I’m concerned, it can run as long as there are interesting questions I can answer, so please feel free to suggest lots of topics in the comments below. These weekly posts will be tagged What-If, and I’m also setting up a new wiki page to collect them all.

Sooo… please help me out folks, and send in some nice what-if questions!

Cheap power analysis

In Hardware on Apr 21, 2013 at 00:01

Remember this screen shot?

annotated-room-packet.png

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:

DSC_4438

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.

Automated + manual 230V

In Hardware on Apr 20, 2013 at 00:01

(This is based on an idea by Ard Jonker, who planted a seed and watched the coin drop, if you excuse the mixed metaphors…)

The recent experiment with direct relay switching suggests that it is possible to switch a latching relay with just two I/O pins tied together plus a 100 µF cap.

The thing about that circuit, is that it draws no current in either ON or OFF state – it only needs a little energy to change the state.

That means it could in principle be powered by a very low-power source, such as this other fun projects I had to shelve a while back. The reasons for this remain as valid as ever: I can’t realistically turn this into a safe kit, given the direct connection to AC mains. So while the thought of having 80 of these sprinkled around the house and consuming under 1 Watt total is a tempting thought, it just isn’t going to happen.

Which doesn’t prevent ME from using it anyway, of course…

Ok, now let’s bring a couple of components together:

  • a JeeNode Micro
  • a 12 mW AC mains supply
  • a directly-powered latching relay
  • a toggle switch
  • power cabling

Here they are, with a nice plastic case (whoops, forgot to include the JNµ, oh well):

DSC_4433

The toggle switch is the small but essential ingredient here. Let me explain:

JC's Grid, page 70

This is a switch which can be operated manually and remotely. Flipping the switch or the relay has the same effect: toggling power, regardless of the state of the other component!

This means it can be operated even when the automated system is off or disconnected, or has crashed. And likewise, the power remains under remote control regardless of the state of the manual toggle switch. This solves a key problem with all those cheap remote power switches out there: the necessity to find the remote, because there is no local switch anymore. And the fact that it breaks down when the home automation system fails.

Given the relay used, I doubt that this solution will be able to control more than 30..50 W, but there are plenty of such devices around the house these days, even LED lighting.

I think I’m gonna have to start messing with AC mains again… with caution, of course.

(9)50 days and counting

In AVR, Hardware, Software on Apr 18, 2013 at 00:01

The new JeeNode Micro has joined the ranks of the test nodes running here to determine battery life in real time. The oldest one has been running over 2 and a half years now:

dsc_1822

That LiPo battery has a capacity of 1300 mAh, and since it’s still running, this implies that the average current draw must be under 1300/24/950 = 57 µA, including self-discharge.

The other two battery tests now running here are based on the new JeeNode Micro v3, i.e. this one – using a boost converter:

DSC_4401

… and another one using a coin cell. Here’s a picture of a slightly older version:

DSC_2858.jpg

The boost version is running off a rechargeable AA battery, of type Eneloop, which I use all over the house now. These batteries hold 1900 mAh, but there’s a substantial penalty for running off one AA cell with a boost converter:

  • energy is not free, i.e. drawing 10 µA at 3.3V means we will need to draw 30 µA at 1.1V, even if we could use a 100% efficient boost converter
  • real-world efficiency is more like 70..80% at these levels, so make that 40..45 µA
  • the boost converter has some idle current consumption, probably 10..20 µA, so this means we’ll draw 50..65 µA even if the JeeNode Micro only uses up 10 µA at 3.3V (actually, it’s 3.0V in the latest JNµ)

This would translate to 1900/.065/24/365, i.e. ≈ 3-year life. Or perhaps 2, if we account for the Eneloop’s 85% per year self-discharge.

The coin cell option runs off a CR2032 battery, which is rated at about 225 mAh, i.e. considerably less than the above options. Still, since there are no boost converter losses, this translates to 225/0.010/24/365, i.e. ≈ 2.5 years of life if the JNµ draws only 10 µA.

These figures look excellent, but keep in mind that 10 µA average power consumption is a very very optimistic value, particularly when there are sensors hooked up and packets are being sent out. I’d be quite happy with a 6-month battery life for a single AA or a coin cell.

For reference, here is an earlier post about all these power calculations.

Here are the current reports I’m getting via HouseMon:

Screen Shot 2013-04-17 at 11.12.08

That’s just about 50 days off a coin cell. Let’s see how it holds up. The nice bit in these tests is that the new nodes now report several different voltage level measurements as well (this also consumes some energy!). They haven’t dropped much yet, but when they do, I hope that we’ll be able to use the drop as a predictor.

Onwards!

JeeNode Micro start-up power

In AVR, Hardware on Mar 29, 2013 at 00:01

The JeeNode Micro v3 includes a P-channel MOSFET to control power to the RFM12B radio. This isn’t just a new gimmick – the goal was to “fix” the RFM12B wireless radio’s startup power consumption, which can prevent an ultra-low power source from ever building up a high enough supply voltage for a JeeNode to start up.

Now that the JNµ is in production, it’s time to measure how well such an approach works. Get ready for a bunch of scope screenshots, all based on the same circuit as before:

JC's Grid, page 51

… except that now the entire JeeNode Micro is in there, and I’m using a 10 Ω resistor.

I’ll be applying a 1 Hz ramp signal going from 0.0 to 3.0V using the power booster behind a signal generator, to see exactly what amount of current is being drawn. In all the images below, the yellow trace is the input voltage (i.e. a simulated power supply), and the blue trace is the voltage over the 10 Ω resistor – that means 1 vertical division on the blue trace corresponds to 0.5 mA when the display shows 5 mV/div:

SCR88

The above image is just a baseline: a simple blink sketch which never enables the radio, and which then toggles some I/O pins every 500 ms. As you can see, the ATtiny84 comes out of power-on reset at about 1.4V and ends up drawing about 3.5 mA at 3.0V.

Fuses are set to low=C2 high=D7 ext=FF, i.e. BOD disabled, startup asap on RC @ 8Mhz.

Now let’s look at the same setup with the JNµ running radioBlip2.ino:

SCR89

This time, the sketch enables the MOSFET to power up the radio, measures the battery voltage, tries to send out a packet (this will fail at 1.4V), and goes into deep sleep. A short but very quick (and high!) blip before power consumption drops to almost zero.

The third measurement is with a sketch doing nothing but powering down right away:

#include <JeeLib.h>

void setup () {
    cli(); // disable all interrupts
    Sleepy::powerDown();
}

void loop () {}

Which produces this result:

SCR90

I’ve bumped the scope sensitivity up to its maximum of 1 mV/div (i.e. 100 µA/div) and am now adding a lot of averaging to try and keep the displayed noise levels low. The “blip” is the ATtiny getting out of reset and powering down completely.

As last test, I repeated the above, but now using a sweep of 10 s (0.1 Hz), and filtering the signal through the lowest low-pass setting available, i.e. 5 Hz. This loses the important spike at 1.4V, which is of course still there, but improves the readout of the baseline:

SCR92

As you can see, the power consumption now never rises above ≈ 60 µA – that’s a ten-fold improvement over what we get with the RFM12B connected to power in the standard way.

The shape of this curve is quite interesting: it’s essentially resistive (since it’s more or less linear), but the current starts at 1.2V, i.e. after overcoming two extra diode drops.

This is the power-up “hump” which any ultra-low power supply based on solar cells or other energy harvesting techniques will need to overcome, so that the ATtiny can switch itself into power down mode and let the supply voltage rise further.

I think that’s an excellent result, and am looking forward to trying a few things out!

Wild goose chase

In AVR, Hardware, Software on Mar 25, 2013 at 00:01

Sometimes, when messing with stuff, you end up in a blind alley which makes no sense…

This happened to me a few days ago, as I was trying to get a good setup going for programming the new JeeNode Micro v3.

The code in the IDE was working, I was able to program the JNµ via avrdude on the command line, but for some crazy reason, the same thing just kept failing when launched through the new 1.5.2 Arduino IDE. Getting that to work would make all the difference in the world, since it means you don’t need to install anything other than the IDE (on any platform) and then simply drop in the ide-hardware folder.

Very odd: a Flash Board which works on one Mac with avrdude, but fails with the IDE, which also uses avrdude. Time to set up the scope in Logic Analyser mode! Lots of wires, lots of configuration to identity all the signals, and then the fun starts: locating the spot in the data stream which would allow me to see what was going on.

Here is a peek at the SPI bus, decoded where it is reporting the ATtiny84 signature bytes:

SCR77

Looks ok. Next, instead of looking at the SPI bus, I looked at the 9600 baud serial data:

SCR83

It’s a slower time scale, since the bit stream is not as fast, thus allowing to capture more information (2 M samples are not that much when sampling at fixed time intervals, since you have to sample often enough to reliably decode the data stream).

I even suspected the power supply lines, and had a look at VCC as an analog trace:

SCR85

And although it’s not very clean, this wasn’t the problem either. Drat…

Since the verification was failing, I decided to capture the data read-back in the second half of the programming process. The way to do this, is to set the trigger on the RESET line going low at the start, and then delaying the capture by about 4 seconds. As you can see in that last screenshot, this is the point where avrdude switches from writing data into flash memory to reading the data back.

And sure enough, the data read back was wrong. Not much, but just some bits flipped – consistently, and reproducably!

It wasn’t a hardware problem after all! A wild good chase: final episode tomorrow…

JeeNode Micro breakout

In AVR, Hardware on Mar 24, 2013 at 00:01

While messing around with a bunch of JeeNode Micro’s here, I decided to create a little convenience breakout board for it:

DSC_4399

Sooo many ways to mess up – it definitely helps to avoid silly mistakes! This particular board doesn’t do that much, but it’s still a nice convenience when you’re drowning in cables and trying to debug some of the nastier bits, such as the Flash Board ISP programmer:

DSC_4406

The above setup was the result of what turned out to be a wild goose chase – stay tuned…

Programming the JNµ – at last!

In AVR, Hardware, Software on Mar 21, 2013 at 00:01

Yesterday’s post shows that it the JNµ can be easily be programmed using the standard Arduino IDE, if you get all the pieces right (isn’t that always the case?):

Screen Shot 2013-03-19 at 14.34.08

The easiest way to get the connections right, is to assemble a custom cable (more):

DSC_4429

What about the software setup? Well, that too is now very simple:

  • download and install a copy of the Arduino IDE 1.5.2
  • create a folder called “hardware” inside your IDE’s “sketchbook” folder
  • download or – preferably – clone the new ide-hardware package from GitHub
  • rename it to “jeelabs” (!) and move it inside the “hardware” folder

The new jcw/ide-hardware project on GitHub was adapted from the arduino-tiny project on Google Code. I didn’t want to wait for that project (it hasn’t been updated for over 6 months), and decided to create a fork on GitHub instead. I did find two other such forks – rambo/arduino-tiny and james147/arduino-tiny, but neither of them appears to offer a major advantage – and since I had to rearrange things to make it work with the IDE 1.5.x structure, there does not seem to be much point in basing things off those forks.

The result of all these steps is that you now have the following new options:

  • use the Tools -> Programmer menu to select “Arduino as ISP”
  • select “JeeNode Micro” from the Tools -> Boards menu to build for that setup
  • use the Tools -> Burn Bootloader menu to set up the fuses
  • use the standard “Upload” button to upload a sketch using this ISP-based setup:

    Screen Shot 2013-03-20 at 16.42.05

Those two warnings are harmless, and can be ignored (I don’t know how to avoid them).

That’s it!

Update – Fixed a problem with setting fuses, make sure you use latest code from github.

Programming the JNµ – again

In AVR, Hardware on Mar 20, 2013 at 00:01

Given that the JeeNode Micro is based on an ATtiny84 and not the standard ATmega used in Arduino’s and clones, it has always been quite tricky to make things work on the JNµ.

No more:

Screen Shot 2013-03-19 at 14.34.08

The new (and still somewhat experimental) Arduino IDE 1.5.2 adds much better support for other process cores, making it possible to set up things as shown above, and then you can just use the “Upload” button to get things loaded into a JeeNode Micro.

It’s all based on setting up a JeeNode (or other 3.3V-level Arduino clone) to run as ISP programmer, and then a few wires to hook it up to a “target” JeeNode Micro. The IDE now includes an ISP programmer setup, but I tend to use the Flash Board for this – in combination with the isp_flash.ino sketch, which was recently updated to run at 9600 baud i.s.o. 19200, to make it compatible with what the IDE expects by default:

DSC_1400_large

For more information about ISP programming, see this post and tag on this daily weblog.

Tomorrow, I’ll describe the steps needed to set things up. Stay tuned…

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:

relay-final

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

DSC_4421

Bottom side:

DSC_4422

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);
  else
    PORTD &= ~ (bit(5) | bit(6));
}

void loop() {
  setLatch(true);
  delay(1000);
  setLatch(false);
  delay(1000);
}

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.

Onwards!

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:

relay-cap

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:

SCR73

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:

SCR74

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);

  delay(3);
  
  pinMode(5, INPUT);
  pinMode(15, INPUT);
  pinMode(6, INPUT);
  pinMode(16, INPUT);
}

void loop() {
  setLatch(true);
  delay(1000);
  setLatch(false);
  delay(1000);
}

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:

SCR63

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:

SCR64

(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:

SCR65

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
  }

  delay(3);

  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:

SCR70

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:

DSC_4417

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

DSC_4418

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

SCR53

…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:

SCR51

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:

DSC_4412

Whoa – nice FM antenna!

SCR39

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:

DSC_4413

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

SCR41

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:

DSC_4414

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

SCR42

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!

Hot spots on a JeeNode USB

In Hardware on Mar 13, 2013 at 00:01

Recently, a blower door test was done here at JeeLabs, as a way to measure – not guess – how air currents are affecting the house, and what sort of insulation measures would be most effective. This was a fascinating and very extensive test, combined with a thorough scan of the entire house – inside and outside – using a high-end thermal imaging camera.

While the guys from Bergenbos were doing their tests, I asked them to take some close-ups of a JeeNode which had been running RF12demo for a while (i.e. not in sleep mode):

IR_10307

IR_10309

Fantastic resolution, as you can see. No big surprises, but nice pictures nevertheless…

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):

SCR37

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:

DSC_4410

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

SCR23

(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:

SCR34

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:

rc

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):

SCR20

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:

SCR21

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:

sweep-gen

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:

sweep-scope

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:

SCR36

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:

SCR35

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:

Rail_caps_extract

 

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”:

GoldenMax53-SERIES

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.

Programming the JNµ v3 – part 1.5

In AVR, Hardware on Mar 5, 2013 at 00:01

After having created the cable, I was going to set up the AVRISP MkII programmer…

AVRISPmkII

Things didn’t work out as planned, alas. When having some problems (unrelated, and due to a wrong part choice, as it turned out), I wanted to make sure that the AVRISP was really set up properly, and decided to install AVR Studio 6.0 …

Hm. Since I don’t have any computers running Windows, this had to be done in a virtual machine (running under Parallels in my case). Easy, right? Yeah, well, I do keep an image around for cases like these, so I downloaded the installer from Atmel, and a little later it was indeed running. Lost some 4 GB of disk space (nuts), and it installed all sorts of stuff as part of the deal (nuts), but hey, that’s how software should be… apparently (nuts!).

Plugging in the AVRISP, I got a message from AVR Studio that I had to upgrade its firmware (it worked fine with avrdude, but hey, who am I to argue). This was not an option, but a requirement (nuts).

So I proceded with the upgrade… piece of cake, right?

Whoops! As part of the upgrade, the device drops off the USB bus, at which point Parallels ceased to recognise it. Unrecognised devices can’t be attached to a Windows VM.

So the end result is: a “bricked” AVRISP programmer, which can probably only be restored on a non-VM install of Windows. Nuts!

I’m going to switch to the Flash Board, which works and has a normal upgrade process:

DSC_1400_large

Note that I’m not using the on-board EPROM or button. A few wires could also be used.

It’s easy to use as a programmer, when you’re used to the Arduino IDE and avr-gcc way of doing things: install the flash.ino sketch on a JeeNode, insert this thing on top, and you end up with an ISP programmer which is recognised by avrdude by using the parameters “-p stk500v1″ and “-B 19200″, and the serial port as “-P …”.

So much for closed source & lock-in – stuff I can’t control. ISP mode resumes tomorrow!

JNµ battery tests

In AVR, Hardware on Mar 4, 2013 at 00:01

With the LiPo battery “blipping” along happily for years now, I’ve started two new tests, based on the JeeNode Micro v3. Here’s the boost unit, running an updated radioBlip2.ino:

DSC_4401

This one converts the incoming 1.2 .. 1.4 V from a single-cell Eneloop AA battery to roughly 3.0 V, as you can see in this overview in HouseMon (using an updated “radioBlip” driver):

Screen Shot 2013-03-04 at 00.59.28

The other new node runs off a CR2032 coin cell, which is struggling a bit to maintain a stable voltage each time a packet gets sent out, as indicated by the 3.20 -> 3.08 V drop. In case you’re wondering how a node can report its battery voltage after already having sent the data, simple: measure the voltage and send it out in the next packet.

The technique used to measure one’s own battery voltage was described in a post last year. Measuring the battery voltage in this way does not consume very much power in itself, since the ATtiny is placed in a special low-power “ADC-only” sleep mode while doing so:

SCR72

The energy used for the measurement is the area under those last four little “blips” after the main packet transmission: there’s almost no penalty in performing this measurement before and after each packet transmission. Over time, hopefully the trend of the before + after voltages can be used as predictor for the amount of life left in them little coin cells…

PS – The main change in the radioBlip2 sketch, apart from adapting it to work on the ATtiny, is that the packet now includes a “sender ID” byte. This way all the battery test nodes can re-use the same node ID here at JeeLabs – since the number of ID’s used is starting to become a concern (there are 30 unique ID’s in each net group). For nodes like these, which only send, it’s no problem at all to “re-use” node ID’s this way.

Update – I’ve added a “BOOST” option to report the battery input voltage, which is much more useful. It’s measured with a jumper from PWR to the AIO pin (PA0, analog 0).

Programming the JNµ v3 – part 1

In AVR, Hardware on Mar 3, 2013 at 00:01

The new JeeNode Micro v3 announced yesterday does some very subtle things w.r.t. how it deals with the SPI bus during ISP programming (don’t you love those silly acronyms?). I’ll have a lot more to tell about this in a future weblog post, but for now let’s just focus on getting a new sketch into the ATtiny84 chip!

As mentioned yesterday, there is no longer a standard 2×3 ISP header on this board. It’s just a 4-pin header, with GND and VCC obtained from the 8-pin header on the side of the board. For reference, here is the ISP header pinout as most ISP programmers expect it:

ISP 6 way pinout

In my case, I wanted to use the modified AVRISP mkII programmer, so I’ve set up a little cable + breadboard hack, as follows:

DSC_4396

The 2×3 to 6-pin (actually 5-pin) header was constructed from an Extension Cable. Here is the hookup, using 2×3 long header pins to connect the 2 female ends together:

DSC_4397

And here’s the breadboard side of things, in close-up:

DSC_4398

Note the sixth wire (providing or sensing VCC power), which goes to either +3V or PWR on the main header. This flexibility will in fact turn out to be quite convenient when dealing with direct-power vs boost-power versions of the JeeNode Micro.

So much for the hardware side of things. The software side turned out to be a lot trickier, and I’d like to take a little more time to work out the best way to do things. After a short intermezzo tomorrow, will come part 2 – stay tuned!

Meet the JeeNode Micro v3

In AVR, Hardware on Mar 2, 2013 at 00:01

There’s a new kid in town, the JeeNode Micro v3 with ATtiny84 + optional boost converter:

DSC_4392

(Can you spot the differences? That’s without and with buck/boost converter…)

It’s even shorter than the v2, and has all the components on one side again:

DSC_4385

The main reason for the reduced size is the reduced number of header pins. One of the biggest changes in that regard, is that v3 no longer has a full 2×3 ISP header – just the 4 data pins. The idea is that GND and +3V can be connected to the 8-pin “port+” header.

As it so happens, there’s a fifth pad on the bottom side of the PCB which connects to GND. This can be put to good use for experimentation, by connecting some headers as follows:

DSC_4393

Note that the 6th pin was removed from the female header – this is very easy to do: just pull on the pin from the bottom with some pliers and it’ll slide out.

That leaves just power to be connected up for SPI programming. More details tomorrow…

Taking the JNµ to 3.0 V

In AVR, Hardware on Mar 1, 2013 at 00:01

As mentioned in yesterday’s post, lower supply voltages lead to lower power consumption.

There’s a new JeeNode Micro v3 revision coming which applies this logic to try and get the power consumption as low as possible. It also has changed slightly in its pinout:

Screen Shot 2013-02-26 at 09.30.47

The main physical changes are: it’s now 16 x 43 mm, and the ISP pins are no longer 2×3.

Let’s just focus on the power side of things for now, though. The JNµ v3 can be operated from several power sources:

  • Direct power: this runs without regulation, and requires a 2.2V .. 3.8V power source
  • Boost power: using the same circuit as the AA Power Board, runs from 0.9V .. 5.0V

The boost power circuit is very flexible as you can see, but it adds a certain amount of quiescent power consumption of its own, making the whole setup draw more idle current than when it is directly powered. What you do get with the boost power hookup, is that it’ll try to stay running as long as possible, down to a 0.5 V input under ideal conditions, so this thing will squeeze the last drop of energy out of its power source. Great for “empty” AA’s!

Boost power supplies are very clever and useful circuits, but they can’t break the laws of physics: a 100% efficient boost supply will draw 15 mA when asked to generate a 3.3 V @ 5 mA output from a 1.1 V input source. The current it draws will be triple that which it produces (more like four times, in fact, since the real circuit is far from 100% efficient).

Note that – in the light of yesterday’s story – it would really make no sense to pump up the voltage to say 5V, only to end up with a more wasteful circuit. That’s not just a quadratic increase, those losses would in fact be proportional to the third power of the voltage!

With a boost circuit, it really pays to work with as low an output voltage as possible. Which is why the JeeNode Micro v3 now comes with a 3.0V version of the boost chip, not 3.3V.

Let’s do the math, assuming a 100% efficient boost supply:

  • a 3.0 V booster draws 3.0 / 3.3 ≈ 91% of the current in comparison to a 3.3 V one
  • running at 3.0 V instead of 3.3 V consumes ≈ 83% of the power (with a resistive load)
  • combined, that means we’ll be using 3.0 ^ 3 / 3.3 ^ 3 ≈ 75% of the power at 3.0 V
  • so the total power consumed is 25% less at 3.0 V compared to what it’d take at 3.3V

That translates to 3 more months on a battery lifetime of 1 year – quite a bit!

This doesn’t just apply to the boost regulator: coin cells often have a 3.0V rating, and so do 2 alkaline AA batteries in series. Note also that 2 rechargable AA batteries will still work fine, as these will supply 2.4..2.6 V, well within the direct power range of the JNµ v3.

Note that for all the standard JeeNodes, nothing changes: these will continue to be populated with 3.3V regulators. One key reason for this is that they are already operating slightly beyond their specs (“overclocked”) with the clock running at 16 MHz. We shouldn’t push our luck with these settings, which are standard in the Arduino world. So the JN, JN SMD, and JN USB will all continue to be operated at 3.3V – no changes!

As for the many different JeePlugs: these all run at 3.3V, and the chips used on these plugs are normally qualified to run at either 3.0 .. 3.6V or 2.7 .. 3.3V, so we’re still fully in range.

Is it all win, then? Well, yes, but note that the noise margins are slightly reduced at 3.0V, which can slightly affect the accuracy of analog pin measurements and the cable lengths at which I2C chips still operate reliably. These effects are going to be minimal, I expect, but it’s something to watch out for.

Update – As pointed out in the comments, the above calculations are not correct. There is a small effect on booster circuit efficiency in all this, but the power savings are closer to 20% than 25% – not quite 3 months per year, as I claimed.

Dropping below 3.3 V

In AVR, Hardware on Feb 28, 2013 at 00:01

One of the departures from the Arduino world has always been that JeeNodes operate at 3.3 V, whereas the standard Arduino’s all ran at 5 V. Things are changing, with the ARM-based “Arduino Due”, for example, which also runs at 3.3 V. There’s not really a choice: ARM chips all run at 3.3V or less (3.6V max actually, which leaves a nice safety margin).

So what’s this trend towards lower voltages all about, eh?

Well… you may have seen an older post in the Easy Electrons series (whoa, over two years ago.. time flies!). If you think about it for a moment, all the electric energy pumped into a circuits will end up being converted into some other form of energy: a teeny tiny bit of radiated RF energy in the case of a JeeNode, but mostly heat, really.

Odd as it may seem, all that electronic stuff is just a way to turn current into heat. There is a purpose for this, since we’re usually interested in the side effects: some physical sensing and some computation, leading to the information we’re interested in. But the electricity consumption is just an (unavoidable) side-effect.

Whenever we can lower the voltage and/or current consumption, we’ll end up consuming less power as a result (W = I x V). Lowering the voltage on a circuit often leads to a dramatic reduction in power, since part of a circuit is always resistive. Ohm’s law says that voltage = resistance x current, or to put it differently: current = voltage / resistance. So halving the voltage (V) over a resistor also halves the current (I) it draws. The effect: half the voltage leads to a quarter of the power consumption, in purely resistive circuits:

JC's Grid, page 65

Unfortunately, you can’t just use 0.1 V to power a circuit: bipolar semiconductors such as diodes and transistors have a 0.6V threshold voltage, anything below that renders them useless. In the real world, running digital circuits at under 1.0 V is rarely done. Even that 1.8 V level down to which an ATmega and ATtiny can be operated is pushing some limits.

Another reason is that lower voltages make capacitive effects more dominant. The lower you go, the longer it takes to charge or discharge a capacitor. Which explains why the ATmega’s maximum clock speed must drop to 4 MHz with a supply voltage of 1.8 V.

But lowering the clock speed is somewhat self-defeating, as this means that the ATmega and ATtiny have to remain powered-up longer before going back into deep-sleep mode! Lots of trade-offs. Still: a low supply voltage is often a good idea – generally speaking.

Tomorrow, I’ll describe the choices made for the next revision of the JeeNode Micro…

Small oops on the LED Node v2

In Hardware on Feb 23, 2013 at 00:01

The new LED Node v2 has been re-done slightly, by fixing the labels of the FTDI connector on the back side, but unfortunately Mr. Murphy pulled another one on me by making me ignore another issue at the time these new boards were ordered.

The current release of the LED Node v2 has a “disconnected ground plane”, meaning that some large copper areas on the back are not attached to ground!

The circuit is correct, in the sense that the board will function as is, but for better noise suppression and higher range of the on-board RFM12B radio, it’s best to make a small modification. Sooo… time to get out the hobby knife and start scratching!

Here is the back of the LED Node v2, unmodified (the silk screen may differ slightly):

DSC_4371

What you have to do is scratch off the solder mask, without cutting the trace:

DSC_4374

The result will be a bit of bare copper on both the trace and the ground plane next to it. Then, apply a bit of solder to connect everything together. Note that doing so may require quite a bit of heat, as the ground plane is hard to heat up – just keep your soldering iron on the spot until the solder flows freely:

DSC_4375

That’s it. The ground of the circuit and the ground plane are now electrically connected, at least under the RFM12B module.

While I’m at it, here’s another modification – unlike the previous “mod”, this one should not be done in a standard setup, with 12V feeding the LED strips as well as the LED Node itself. This is a change you need only consider if you are using voltages higher than 12V, i.e. for 24V LED strips, or when running off batteries which go up to 14V or more.

The reason for this change, is that the MCP1702 regulator of the LED Node is rated only up to about 13V. Anything higher will damage it, even if applied briefly – I’ve seen several cases of this in the past.

The solution is to cut the trace between the power connector and the LED Node, but keep in mind that you then have to power the LED Node logic from the FTDI connector or one of the PWR pins on the headers at all times:

DSC_4372

Just use a sharp hobby knife to cut through the trace this time:

DSC_4376

So much for hacking the LED Node!

Solar fingernails

In Hardware on Feb 11, 2013 at 00:01

A couple of weeks ago, I described a little indoor solar energy test setup, based on a couple of fingernail-sized CPC1824 solar cell chips, with 0.47 Farad supercaps for storage:

DSC_4351

It has been an interesting setup to keep running for a while, and now that 20 days have passed, it’s sort of intriguing to see how well, or badly, these solar energy cells performed. To summarise, here is what the four different test were about:

  1. One CPC1824, very lightly loaded with 20 MΩ, i.e. a 0.15..0.20 µA current draw
  2. One CPC1824, lightly loaded with 2 MΩ, i.e. a 1.5..2.0 µA current draw
  3. One CPC1824, moderately loaded with 0.2 MΩ, i.e. a 15..20 µA current draw
  4. Two CPC1824’s in parallel, moderate load with 0.2 MΩ, again 15..20 µA current draw

In addition, there is a top-up voltage cycling once per ≈ 2 hours, to prevent any the supercaps from discharging much further than about 2.7V. This is not a realistic situation if this setup were to be used for real, but I wanted to prevent a total discharge of the supercaps, to try and find out whether the supercaps would get better (i.e. less leaky) over time, as the constant charge conditions those membranes full of useable electrons.

Here are the results of 20 days, superimposed one upon the other:

solar

(click two times to see it in full scale – X axis is in minutes since midnight UTC)

  • #1 = blue, #2 = bright green, #3 = orange (dotted), #4 = red (longer dots)
  • the last day is marked in black for all four cases
  • around noon, all cells fall into the shadow, so energy generation almost stops
  • note how only the blue lines stay above 3.0V (except in the first 2..3 days)

This was a wintery mix of sunny and cloudy days, which has a huge effect on the charge / discharge curves. Looks like indoor solar with these tiny cells is not going to work…

One conclusion is that only the lightest load of 0.15..0.20 µA allows the supercap to retain a decent amount of charge through each night. On the other end of the range: with two solar cells in parallel, a 15..20 µA load might be able to stay alive for a few hours each day.

Ehm, well, just maybe – this will really depend on the startup power consumption curves!

HouseMon resources

In AVR, Hardware, Linux, Musings, Software on Feb 6, 2013 at 00:01

As promised, a long list of resources I’ve found useful while starting off with HouseMon:

JavaScript – The core of what I’m building now is centered entirely around “JS”, the language behind many sites on the web nowadays. There’s no way around it: you have to get to grips with JS first. I spent several hours watching most of the videos on Douglas Crockford’s site. The big drawback is the time it takes…

Best book on the subject, IMO, if you know the basics of JavaScript, is “JavaScript: The Good Parts” by the same author, ISBN 0596517742. Understanding what the essence of a language is, is the fastest way to mastery, and his book does exactly that.

CoffeeScript – It’s just a dialect of JS, really – and the way HouseMon uses it, “CS” automatically gets compiled (more like “expanded”, if you ask me) to JS on the server, by SocketStream.

The most obvious resource, http://coffeescript.org/, is also one of the best ways to understand it. Make sure you are comfortable with JS, even if not in practice, before reading that home page top to bottom. For an intruiging glimpse of how CS code can be documented, see this example from the CS compiler itself (pretty advanced stuff!).

But the impact of CS goes considerably deeper. To understand how Scheme-like functional programming plays a role in CS, there is an entertaining (but fairly advanced) book called CoffeeScript Ristretto by Reginald Braithwaite. I’ve read it front-to-back, and intend to re-read it in its entirety in the coming days. IMO, this is the book that cuts to the core of how functions and objects work together, and how CS lets you write on a high conceptual level. It’s a delightful read, but be prepared to scratch your head at times…

For a much simpler introduction, see The Little Book on CoffeeScript by Alex MacCaw, ISBN 1449321046. Also available on GitHub.

Node.js – I found the Node.js in Action book by Mike Cantelon, TJ Holowaychuk and Nathan Rajlich to be immensely useful, because of how it puts everything in context and introduces all the main concepts and libraries one tends to use in combination with “Node”. It doesn’t hurt that one of the most prolific Node programmers also happens to be one of the authors…

Another useful resource is the API documentation of Node itself.

SocketStream – This is what takes care of client-server communication, deployment, and it comes with many development conveniences and conventions. It’s also the least mature of the bunch, although I’ve not really encountered any problems with it. I expect “SS” to evolve a bit more than the rest, over time.

There’s a “what it is and what it does” type of demo tour, and there is a collection on what I’d call tech notes, describing a wide range of design docs. As with the code, these pages are bound to change and get extended further over time.

Redis – This a little database package which handles a few tasks for HouseMon. I haven’t had to do much to get it going, so the README plus Command Summary were all I’ve needed, for now.

AngularJS – This is the most framework-like component used in HouseMon, by far. It does a lot, but the challenge is to understand how it wants you to do things, and altough “NG” is not really an opinionated piece of software, there is simply no other way to get to grips with it, than to take the dive and learn, learn, learn… Let me just add that I really think it’s worth it – NG can be magic on the client side, and once you get the hang of it, it’s in fact an extremely expressive way to create a responsive app in the browser, IMO.

There’s an elaborate tutorial on the NG site. It covers a lot of ground, and left me a bit overwhelmed – probably because I was trying to learn too much as quickly as possible…

There’s also a video, which gives a very clear idea of NG, what it is, how it is used, etc. Only downside is that it’s over an hour long. Oh, and BTW, the NG FAQ is excellent.

For a broader background on this sort of JS frameworks, see Rich JavaScript Applications by Steven Sanderson. An eye opener, if you’ve not looked into RIA’s before.

Arduino – Does this need any introduction on this weblog? Let me just link to the Reference and the Tutorial here.

JeeNode – Again, not really much point in listing much here, given that this entire weblog is more or less dedicated to that topic. Here’s a big picture and the link to the hardware page, just for completeness.

RF12 – This is the driver used for HopeRF’s wireless radio modules, I’ll just mention the internals weblog posts, and the reference documentation page.

Vim – My editor of choice, lately. After many years of using TextMate (which I still use as code browser), I’ve decided to go back to MacVim, because of the way it can be off-loaded to your spine, so to speak.

There’s a lot of personal preference involved in this type of choice, and there are dozens of blog posts and debates on the web about the pro’s and con’s. This one by Steve Losh sort of matches the process I am going through, in case you’re interested.

Best way to get into vim? Install it, and type “vimtutor“. Best way to learn more? Type “:h<CR>” in vim. Seriously. And don’t try to learn it all at once – the goal is to gradually migrate vim knowledge into your muscle memory. Just learn the base concepts, and if you’re serious about it: learn a few new commands each week. See what sticks.

To get an idea of what’s possible, watch some videos – such as the vim entries on the DAS site by Gary Bernhardt (paid subscription). And while you’re at it: take the opportunity to see what Behaviour Driven Design is like, he has many fascinating videos on the subject.

For a book, I very much recommend Practical Vim by Drew Neil. He covers a wide range of topics, and suggests reading up on them in whatever order is most useful to you.

While learning, this cheatsheet and wallpaper may come in handy.

Raspberry Pi – The little “RPi” Linux board is getting a lot of attention lately. It makes a nice setup for HouseMon. Here are some links for the hardware and the software.

Linux – Getting around on the command line in Linux is also something I get asked about from time to time. This is important when running Linux as a server – the RPi, for example.

I found the linuxcommand.org resource which appears to do a good job of explaining all the basic and intermediate concepts. It’s also available as a book, called “The Linux Command Line” by William E. Shotts, Jr. (PDF).

There… the above list ought to get you a long way with all the technologies I’m currently messing around with. Please feel free to add pointers and tips in the comments, if you think of other resource which can be of use to fellow readers in this context.

Dive Into JeeNodes

In AVR, Hardware, Linux, Software on Feb 1, 2013 at 00:01

Welcome to a new series of limited-edition posts from JeeLabs! Read ‘em while they last!

Heh… just kidding. They’ll last forever of course, as does everything on this thing called internet. But what I’m going to describe in probably a dozen posts or so is the following:

dijn-essence

Hm, that doesn’t quite explain it, I guess. Let me try again:

JC's Grid, page 63

So this is to announce a new “DIJN” series of weblog posts, describing how to set up your own Wireless Sensor Network with JeeNodes, as well as the infrastructure to report a measured light-level somewhere in your house, in real time. The end result will be fully automated and autonomous – you could take your mobile phone, point it to your web server via WiFi, and see the light level as it is that very moment, adjusting as it changes.

This is a far cry from a full-fledged home monitoring or home automation system, clearly – but on the other hand, it’ll have all the key pieces in place to explore whatever direction interests you: ready-made sensors, DIY sensors, your own firmware on the remote nodes, your own web pages and automation logic on the central server… it’s up to you!

Everything is open source, which in this context matters a lot, because that also means that you can really dive into any aspect of this to learn and explore the truly magical world of Physical Computing, Wireless Sensor Networks, environmental sensing and control, as well as state-of-the art web technologies.

The focus will be on describing every step needed to implement this from scratch. I’ll cover setting up all the necessary software and hardware, in such a way that if you know next to nothing about any of the domains involved, you can still follow along and try it out – whether your background is in software, electronics, wireless, or none of these.

If technology interests you, and if I can bring across even a small fraction of the fun there is in tinkering with this stuff and making new things up as you g(r)o(w) along, then that would be a very nice reward for everyone involved, as far as I’m concerned.

PS. “Dijn” is also old-Dutch for “your” (thy, to be precise). Quite a fitting name in my opinion, as this sort of knowledge is really yours for the taking – if you want it…

PPS. For reference: here is the first post in the series, and here is the overview.

Blink Plug meets NG

In Hardware, Software on Jan 29, 2013 at 00:01

Last month, I described how to hook up a JeeNode with a Blink Plug to Node.js via SocketStream (“SS”) and a USB connection. Physical Computing with a web interface!

That was before AngularJS (“NG”), using traditional HTML and JavaCoffeeScript code.

With NG and SS, there’s a lot of machinery in place to interface a web browser with a central Node process. I’ve added a “blink-serial” module to HouseMon to explore this approach. Here’s the resulting web page (very basic, but fully dynamic in both directions):


Screen Shot 2013-01-28 at 19.17.40


The above web page is generated from this client/templates/blink.jade definition:

Screen Shot 2013-01-28 at 18.42.02

There are two more files involved – client/code/modules/blink.coffee on the client:

Screen Shot 2013-01-28 at 18.43.41

… and briqs/blink-serial.coffee, which drives the whole shebang on the server:

Screen Shot 2013-01-28 at 20.17.40

I’m not quite happy yet with the exact details of all this, but these 3 files are all there is to it, and frankly I can’t quite imagine how a bidirectional real-time interface could be made any simpler – given all the pieces involved: serial interface, server, and web browser.

The one thing that can hopefully be improved upon, is the terminology of it all and the actual API conventions. But that really is a matter of throwing lots of different stuff into HouseMon, to see what sticks and what gets messy.

Onwards!

PS – What’s your take on these screenshots? Ok? Or was the white background preferable?

PPS – Here’s another test, code inserted as HTML – suitable for copying and pasting:

# Define a single-page client called 'main'
ss.client.define 'main',
  view: 'index.jade'
  css: ['libs', 'app.styl']
  code: ['libs', 'app', 'modules']

Update – Yet another approach, using a a WordPress plugin (no Jade / Stylus support?):

# Define a single-page client called 'main'
ss.client.define 'main',
  view: 'index.jade'
  css: ['libs', 'app.styl']
  code: ['libs', 'app', 'modules']

Bad LiPo charge chip

In Hardware on Jan 26, 2013 at 00:01

(Not planned this way, but still a nice follow-up on yesterday’s Junk USB post…)

While thinking about some minor tweaks for the JeeNode USB board, I wanted to try out a different LiPo charger chip – mostly to reduce costs, given than not everyone using the JN USB would be interested in the LiPo charge capability (it’s also fine as a JeeNode-with-built-in-USB-BUB after all).

So I had a look at the MCP73832T – in fact, Paul Badger and I went ahead and had a new board made with it:

DSC 3220

The good news: as a LiPo charger, it works absolutely fine.

The bad news: without an attached LiPo battery, it’s not usable.

It turns out that this chip uses some sort of charge/discharge cycle. This is what happens without LiPo attached:

SCR34

IOW, it’s delivering 4.2V for a while, and then dropping the voltage to see whether the LiPo itself will fill in the gaps. A pretty clever way to figure out the state of the attached battery, if you ask me.

One way to use the chip without attached LiPo would be to bypass the Vin and Vout pins of the chip, i.e. just disable it altogether via a (solder-) jumper. Drawbacks: 1) you have to remember this, and act accordingly, 2) this means PWR would be 4.2V with LiPo attached, and 5V without, and 3) when bypassed, there would be no over-current protection for the USB port.

Especially that 3rd issue is bad – JeeNodes are about tinkering with stuff, and JN USB’s are about tinkering while attached to a computer USB port. Without over-current protection, tinkering can damage your computer – scary!

There is one more way to solve this, but it’s not very practical: add a big electrolytic cap which sort of takes the place of a battery. I used a 6800 µF (which pulls too much current on power-up, BTW). The result:

SCR36

A voltage on the PWR pin which carries 3.8 .. 4.2V, with a 10 Hz ripple. Not great, but good enough to make the JeeNode’s internal regulator work. Except that a 6800 µF capacitor is huge and highly impractical, of course!

Sooo… back to the MAX1555 it is. That chip works differently: it senses the charge current and the output voltage.

Note to self: don’t replace chips without testing all essential modes they’ll be used in.

And good bye Mr. Murphy, how considerate of you to drop by once in a while…

Junk USB power

In Hardware on Jan 25, 2013 at 00:01

The P1 JeeNode which was recently hooked up to my smart meter stopped working – or maybe I switched USB adapter and never checked?

First thought was to check it out, and although that provided some useful insight, it didn’t solve the problem: node blinking furiously and – more importantly – no data packets!

Well, it turns out that this thing was the problem:

DSC_4354

That’s not a Texas Instruments unit, or rather: it’s probably from a rejected batch which found its way to the “surplus” market again (got it from Pollin in Germany, long ago).

Hooking it up to the scope tells the whole story at a glance – first the unloaded output:

SCR59

Not stellar, but not shocking either. Let’s zoom in on the start of the voltage bumps:

SCR56

Mweh… nasty. But here’s the same output with a JeeLink plugged in:

SCR58

Whoa, right… totally useless as a “5V supply”. Ready for the garbage bin… plunk!

Solar… again

In Hardware on Jan 20, 2013 at 00:01

These dark and cold winter days are not really effective for solar energy: the entire month of January will probably not generate more power energy than two peak days in July!

Still, it’s a good baseline to try things with. And one of the experiments I haven’t given up on is making nodes run off solar power, using a supercap to hold the charge. Maybe they’ll not last through the night, but that’s fine – there are still various uses (especially outdoor) where being able to run during daytime with nodes that never need to have their batteries changed would be really nice.

In previous attempts, I’ve always immediately tried to power the actual node, but now I’d like to try something simpler: a solar cell, a supercap, and a resistor as load. Like this:

JC's Grid, page 61

I’m using a tiny solar cell by Clare again, the CPC1824, with the following specs:

Screen Shot 2013-01-19 at 15.28.51

Not much, but then again, it’s a cell which is just the size of a fingernail. As SOIC-16 package, and with the specs of the available current next to it:

Screen Shot 2013-01-19 at 15.28.28   Screen Shot 2013-01-19 at 15.29.26

In fact, I’d like to try this out with 4 different resistive loads:

  • one cell, 2x R = 20 MΩ = 0.2 µA current draw at full output
  • one cell, 2x R = 2 MΩ = 2 µA current draw at full output
  • one cell, 2x R = 200 KΩ = 20 µA current draw at full output
  • two cells in paralel, 2x R = 200 KΩ = 20 µA current draw at full output

There may be a flaw in this approach, in that the leakage of the supercap could completely overshadow the current draw from the resistors. But my hope is that supercaps get better over time when kept charged. Hmmm… not sure it applies if they run down every night.

So the second part of the idea, is to alternate solar cell use and dumb charging – just to measure how that affects output voltage over time. One hour, DIO will be on, and put the supercap on about 2.7V, the other hour it’ll be off and the solar cell takes over. With a bit of luck, the output voltage changes might show a pattern, right?

I think it’s worth a try and have made a setup with 4x the above – more tomorrow…

P1 revisited

In Hardware on Jan 13, 2013 at 00:01

The P1 port connection I set up recently for picking up data from the utility company’s smart meter isn’t working reliably yet, so I dove a bit deeper into it.

Here’s how I now think the P1 interface is implemented inside that smart meter:

JC's Grid, page 59

There’s no way to ascertain whether a PNP or NPN transistor is used, without opening the box (impossible without breaking a seal, so definitely not an option!). But given that NPN is more common, the above circuit is my best guess.

The resistance was measured between the DATA and GND pin. The resistance between DATA and REQUEST is usually over 1 MΩ, which indicates that the phototransistor is open. Makes sense: pull the data low regardless of the REQUEST line state, and pull it high when the internal IR LED in that optocoupler is lit. That also explains the awkward inverted TTL logic levels provided by this interface.

What you can see is that the REQUEST line is really nothing but the power supply to the isolated side of the optocoupler. But the surprise is the value of that pulldown resistor!

Let’s do the math: when REQUEST is 5V, and the phototransistor is conducting, it’ll have about a 0.2V collector-to-emitter voltage drop, leaving 4.8V to feed the 180 Ω resistor (I measured 4.75 V, so yeah, close enough).

Whoa… 4.8 V over 180 Ω is 26 mA, a pretty hefty current draw in µC terms!

My conclusions from all this are: there’s no external pull-up or pull-down needed after all, and my hunch is that it’ll work just as fine with REQUEST powered by 3.3V (reducing the current somewhat). All you have to make sure when working with this P1 interface, is that your REQUEST pin can supply those 25-odd milliamps.

If the above is accurate, then nothing forces us to actually use that resistor, by the way. We could simply connect the REQUEST and DATA pins and leave GND dangling. In fact, by re-using the phototransistor in a different way, one could even make it work in active-high mode again (only if no other P1 devices are connected, evidently).

Note that this is for the Landis & Gyr E350 (PDF) smart meter I have – others may differ!

Flukso with RFM12B

In Hardware, Linux on Jan 12, 2013 at 00:01

Some exciting new developments going on…

DSC_4347

You’re looking at the final prototype of the latest Flukso meter, which can be connected to AC current sensors, pulse counters, and the Dutch smart metering “P1″ port. Here’s the brief description from that website:

Flukso is a web-based community metering application. Install a Fluksometer near your fuse box and you will be able to monitor, share and reduce your electricity consumption through this website.

The interesting bit is that it’s all based on a Linux board with wired and wireless Ethernet, plus a small ATmega-based add-on board which does all the real-time processing.

But the most exciting news is that the new version, now entering production, will include an RFM12B module with the JeeNode-compatible protocol. A perfect home automation workstation. Yet another interesting aspect of this, is that Bart Van Der Meersche, the mastermind behind Flusko, is working on getting the Mosquitto MQTT broker running permanently on that same Flukso meter.

Here’s the basic layout (probably slightly different from the actual production units):

Screen Shot 2013-01-11 at 21.10.20

Flukso runs OpenWRT, and everything in it is based on the Lua programming language, which is really an excellent fit for such environments. But even if Lua is not something you want to dive into, the open-endedness of PubSub means this little box drawing just a few Watt can interface to a huge range of devices – from RF12 to WiFi to LAN, and everything flowing in and out of that little box becomes easily accessible via MQTT.

PS. I have no affiliation with Flukso whatsoever – I just like it, and Bart is a nice fellow :)

Audio DAC

In Hardware on Jan 11, 2013 at 00:01

Last year, I got one of these little low-cost audio Digital-to-Analog Converters on eBay:

DSC_4343

Takes digital SPDIF coax in, and produces analog left and right channels out. I got them before the bigger picture of the audio chain in the living room got fleshed out, and in the end I don’t really need this type of converter anymore.

Besides, there was some hiss and hum with these, so it’s not really high-end anyway.

Here’s what’s inside:

DSC_4344

That’s a Cirrus Logic CS8416 “192 kHz Digital Audio Interface Receiver”, which apparently has all the smarts to detect and decode a range of serial bit formats, plus a Cirrus Logic CS4344 “10-pin, 24-Bit, 192 kHz Stereo D/A Converter” to generate the L/R audio signals.

I’m a bit surprised by the hiss/hum issues, since the audio DAC is specified as -90 dB THD+N and 105 dB Dynamic Range, which to me sounds like it should be pretty good. Maybe not audiophile level, but hey… neither are my ears, anyway!

Picking up P1 data

In Hardware on Jan 1, 2013 at 00:01

Just in time for 2013, I hooked up the smart meter which was installed a month ago:

DSC_4341

This connects DIO4 to the output of the P1 port, which has the following pinout:

Screen Shot 2012-12-31 at 11.25.43

The circuit is as follows:

JC's Grid, page 52

The request pin has to be pulled to 5V (it very likely just powers the isolated side of the built-in optocoupler). The 10 kΩ signal pull-up is needed to improve the rising flank of the signal, and the 10 kΩ resistor to the I/O pin prevents problems when the input signal rises above the 3.3V powering the ATmega.

Tomorrow, I’ll describe the software that goes along with this.

RFM12B startup power consumption

In Hardware on Dec 29, 2012 at 00:01

For quite some time, I’ve wanted to know just how much current the RFM12B module draws on power-up. Well, time for a test using the power booster described recently:

JC's Grid, page 51

So the idea is to apply a sawtooth signal to the RFM12B, rising from 0 to 3V at the rate of say 10 Hz, and to measure the voltage drop across a 100 Ω resistor at the same time. This will have a slight effect on measurement accuracy – but no more than 2%, so I’m ok with it.

Here is the outcome:

SCR51

The yellow trace is VCC, the supply voltage – from 0..3V. The magenta trace is the current consumption, which turns out to be 0..650 µA. As you can see, the current draw quickly rises between 1 and 2V, and then continues to increase sort of linearly.

Note that this power consumption can’t be reduced: we don’t have the ability to send any commands to the RFM12B until it has started up!

This type of analysis can also be done using the X-Y mode on most oscilloscopes:

SCR48

It’s essentially the same picture as before, because the sawtooth is a straight line, and so voltage rise is the same thing as time in this case. Here’s what happens when the input signal is switched to a sine wave:

SCR49

As expected, the essence of the curve hasn’t changed one bit. Because it really doesn’t matter how we vary VCC over time. But there’s an intriguing split in the curve – this is most likely caused by a different current consumption when VCC is rising vs when it is dropping. Keep in mind that the changes are occurring at 10 Hz, so there’s bound to be some residual charge in the on-board capacitors of the RFM12B module.

Anyway. It’s a bit of a silly distraction to do things this way, but now I do have a better idea of how current consumption increases on startup. This relatively high 0.65 mA current draw was the main reason for including a MOSFET in the new JeeNode Micro v2, BTW.

Assembling the LED Node v2

In AVR, Hardware on Dec 28, 2012 at 00:01

After yesterday’s little mistake, here’s a walk-through of assembling the LED Node v2:

DSC_4332

Note that the LED Node comes with pre-soldered SMD MOSFETs so you don’t have to fiddle with ‘em.

The LED Node is really just a JeeNode with a different layout and 3 high-power MOSFET drivers, to control up to 72W of RGB LED strips through the ATmega’s hardware PWM. Since there’s an RFM12B wireless module on board, as well as two free JeePorts, you can do all sorts of funky things with it.

As usual, the build progresses from the flattest to the highest components, so that you can easily flip the PCB over and press it down while soldering each wire and pin.

Let’s get started! So we begin with 7 resistors and 1 diode (careful, the diode is polarised):

DSC_4333

Be sure to get the values right: 3x 1 kΩ, 3x 1 MΩ, and 1x 10 kΩ (next to the ATmega).

(note: I used three 100 kΩ resistors i.s.o. of 1 MΩ, as that’s what I had lying around)

Next, add the 4x 0.1 µF capacitors and the IC socket – lots of soldering to do on that one:

DSC_4334

Then the MCP1702 regulator and the electrolytic capacitor (both are polarised, so here too, make sure you put them in the right way around), as well as the male 6-pin FTDI header:

DSC_4335

Soldering the RFM12B wireless radio module takes a bit of care. It’s easiest if you start off by adding a small solder dot and hold the radio while making the solder melt again:

DSC_4336

Then solder the remaining pins (I tend to get lazy and skip those which aren’t used, hence not all of them have solder). I also added the 3-pin orange 16 MHz ceramic resonator, the antenna wire, the two port headers, and the big screw terminal for connecting power:

DSC_4337

Celebration time – we’ve completed the assembly of the LED Node v2!

Here’s a side view, with the ATmega328 added – as you can see it’s much flatter than v1:

DSC_4338

And here’s a top view of the completed LED Node v2, in all its glory:

DSC_4339

You can now connect the FTDI header via a USB BUB, and you should see the greeting of the RF12demo sketch, which has been pre-loaded onto the ATmega328.

To get some really fancy effects, check out the Color-shifting LED Node post from a while back on this weblog. You can adjust it as needed and then upload it through FTDI.

Next step is to attach your RGB strip (it should match the 4-pin connector on the far left). Be sure to use fairly sturdy wires as there are up to 2 amps going through each color pin and a maximum of 6 amps total through the “+” connector pin!

Lastly, connect a 12V DC power supply (making absolutely sure to get the polarity right!) and you will have a remote-controllable LED strip. Enjoy!

Murphy strikes the silkscreen

In Hardware on Dec 27, 2012 at 00:01

Uh, oh – silly mistake time! Here’s an excerpt of the new LED Node v2:

      TOP:   top       BOTTOM:   bottom

These are the top and bottom view of the FTDI connector in the middle of the board, flipped horizontally.

The bottom view has the “GND” label on the wrong pin!

Drat. Will do a re-spin with the corrected silkscreen, but the first few units will be like this so make sure you use the alignment shown on the top of the board.

The good news is that connecting the FTDI cable or BUB the wrong way is harmless.

Connecting a Blink Plug to a web browser

In Hardware, Software on Dec 23, 2012 at 00:01

Here’s a fun experiment – using Node.js with SocketStream as web server to directly control the LEDs on a Blink Plug and read out the button states via a JeeNode USB:

JC's Grid, page 51

This is the web interface I hacked together:

Screen Shot 2012-12-21 at 23.34.20

The red background comes from pressing button #2, and LED 1 is currently on – so this is bi-directional & real-time communication. There’s no polling: signalling is instant in both directions, due to the magic of WebSockets (this page lists supported browsers).

I’m running blink_serial.ino on the JeeNode, which does nothing more than pass some short messages back and forth over the USB serial connection.

The rest is a matter of getting all the pieces in the right place in the SocketStream framework. There’s no AngularJS in here yet, so getting data in and out of the actual web page is a bit clumsy. The total code is under 100 lines of CoffeeScript – the entire application can be downloaded as ZIP archive.

Here’s the main client-side code from the client/code/app/app.coffee source file:

Screen Shot 2012-12-22 at 00.48.12

(some old stuff and weird coding in there… hey, it’s just an experiment, ok?)

The client side, i.e. the browser, can receive “blink:button” events via WebSockets (these are set up and fully managed by SocketStream, including reconnects), as well as the usual DOM events such as changing the state of a checkbox element on the page.

And this is the main server-side logic, contained in the server/rpc/serial.coffee file:

Screen Shot 2012-12-22 at 00.54.07

The server uses the node-serialport module to gain access to serial ports on the server, where the JeeNode USB is plugged in. And it defines a “sendCommand” which can be called via RPC by each connected web browser.

Most of the work is really figuring out where things go and how to get at the different bits of data and code. It’s all in JavaScript CoffeeScript on both client and server, but you still need to know all the concepts to get to grips with it – there is no magic pill!

Tomorrow, I’ll describe how I created this app, and how to run it.

Update – The code is now on GitHub.

Meet the LED Node v2

In Hardware on Dec 14, 2012 at 00:01

The LED Node has been around for a while, but I wasn’t 100% happy with it. In principle, the LED Node v1 is a JeeNode plus 1.5 MOSFET Plugs plus an optional Room Board.

There is a small but significant difference with regular JeeNodes (apart from their very different shape), in that all three MOSFETs are tied to pins with hardware PWM support. This is important to get flicker-free dimming, i.e. if you want to have clean and calm color effects. Software PWM doesn’t give you that (unless you turn all other interrupt sources off), and even with hardware PWM it requires a small tweak of the standard Arduino library code to work well.

The neat thing about the LED Node is the wireless capability, so you can control the unit in all sorts of funky ways.

But I didn’t like the very sharp pulses this board generates, which can cause problems with color shifts over long strips and also can produce a lot of RF interference, due to the LED driving current ringing. The other thing which didn’t turn out to be as useful as I thought was the room board part.

So here’s the new LED Node v2:

jlpcb-146

The big copper areas on the left are extra-wide traces and cooling pads, dimensioned to support at least 2 Amps for each of the RGB colors, for a total of 6 A, i.e. 72 W LED strips @ 12 V. But despite the higher specs, this board will actually be lower profile, because it uses a different type of MOSFETs. They are surface mounted and come pre-soldered so you don’t have to fiddle with them (soldering such small components on relatively large copper surfaces requires a good soldering iron and some expertise).

This new revision has the extra resistors to reduce ringing, and replaces the room board interface with two standard 6-pin port headers: one at the very end, and one on the side. These are ports 1 and 4, respectively, matching a standard JeeNode and any plugs you like. If you want, you could still hook up a Room Board, but this is now no longer the only way to use the LED Node.

Wanna add an accelerometer or compass to make your LED strips orientation aware? Well… now you can! And then place them inside your bike wheels? Could be fun :)

Details to be posted on the Café wiki soon, as well as in the Shop.

The world of audio

In Hardware on Dec 13, 2012 at 00:01

There’s a huge world out there which I’ve never looked into: audio. And it has changed.

It used to be analog (and before my time: vacuum tubes, or “valves” as the British say).

Nowadays, it’s all digital and integrated. The common Class-D amplifier is made of digitally switching MOSFETs with some cutoff filters to get rid of the residual high-frequency this generates. Leaving just the “pure” audible portion to drive the speakers.

With the recent switch to a new small TV, away from the Mac Mini, for our TV & music system, I lost the original hook-up we had, which was a (far too cheap) little analog amplifier driving (far too expensive) speakers we’ve had here for a long time.

So now we have this TV with built-in tiny 2.5W speakers blasting to the rear – a far cry from the sound we had before. And no music playback capability at all in the living room right now. Not good!

Our needs are simple: CD-quality music (we’re no audiophiles) and decent TV sound. I am going to need a setup soon, as the Christmas vacation time nears.

Trouble is: the sound source for our music is on the Mac Mini server, which is in an impossible place w.r.t. the TV and the speakers. So my first thought was: an Airport Express. It can play over WiFi, and has optical audio output. But… the AE draws 4W in standby. And turning it on for each use is awkward: waiting a minute or more to get sound from the TV is not so great.

The other options for music are an Apple TV or a specially-configured Raspberry Pi.

The only remaining issue is how to get sound from line-level analog audio or (preferably) digital audio to the speakers. I ended up choosing something fairly simple and low-end, a component from miniDSP called “miniAMP”:

DSC 4302

This takes all-digital I²S signals and produces 4x 10W audio. It needs a 12..24V @ 4A supply, i.e. a simple “brick” should do. But that’s just half a solution: it needs I²S…

This is where the “miniDSP” component comes in (the SOIC chip at the top is a PIC µC):

DSC 4301

So the whole setup becomes as follows – and I’ll double up the miniAMP (one for each channel) if the output is not powerful enough:

Screen Shot 2012 12 12 at 23 11 57

The miniDSP takes 2x analog in, and produces up to 4x digital I²S out. The nice part is that it’s fully configurable, i.e. it can do all sorts of fancy sound processing:

Screen Shot 2012 12 12 at 23 21 17

This is perfect for our setup, which includes old-but-incredibly-good separate speakers for the highs and the lows. So a fully configurable cross-over setup is just what we need:

Screen Shot 2012 12 12 at 23 23 11

The way this works is that you set it up, burn the settings into the DSP front-end via USB, and then insert it into the audio chain.

It’s tempting to start tinkering with this stuff at an even lower level, but nah… enough other things to do. Although I do want to look into auto shut-off at some point, to further lower power consumption when no audio is being played. But for now this will have to do.

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:

SCR09

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:

SCR10

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:

SCR17

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:

SCR19

SCR20

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:

SCR17

(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!

Ringing MOSFETs

In Hardware on Dec 5, 2012 at 00:01

The LED Node uses MOSFETs to drive the red, green, and blue LED strings, respectively.

Here’s the circuit (note that the LED strips must also include current-limiting resistors):

JC s Grid page 39

Well… in the LED Node v1, input pin B and resistor R2 are missing, and R1 is 10 kΩ.

This leads to a fair amount of electrical trouble – have a look:

SCR31

The yellow line is the input, a 6V signal in this case (not 3.3V, as used in the LED Node). The blue line is the voltage over the MOSFET. The input is a 1000 Hz square wave with 20% duty cycle, i.e. 200 µs high, 800 µs low.

When the input voltage goes low, the N-MOSFET switches off. In this case, I don’t use an actual LED strip as load, but a 1 Ω power resistor, driven from a 2V power supply line to keep the heat production manageable during these tests. So that’s 2 A of current going through the MOSFET, and when it switches off that happens so quickly that the current simply has nowhere to go (the power supply is not a very nice conductor for such high-frequency events, alas).

As you can see, this signal ringing is so strong in this case, that the voltage will overshoot the power supply by a multiple of 2V.

Here are the leading edge (MOSFET turns on & starts to draw 2 A) and the trailing edge (MOSFET turns off & breaks the 2 A current) of that cycle again, in separate screenshots:

SCR34 SCR36

The horizontal time scale is 1 µs per division.

The vertical scales are 0.5 V and 5 V (!) per division for the input (yellow) and MOSFET voltage (blue), respectively. Note the 30V overshoot when turning that MOSFET off!

This has all sorts of nasty consequences. For one, such high frequency signals will vary across the length of the LED strip, which will affect the intensities and color balance.

But what’s much worse, is the electromagnetic interference these signals will generate. There’s probably a strong 5..10 MHz component in there. Yikes!

There are various solutions. One is to simply dampen the turn-on / turn-off slopes by inserting a resistor in series between the µC’s output pin and the MOSFET’s gate. If you recall the schematic above, I switched the output signal to pin B, made R1 = 1 MΩ and R2 = 1 kΩ. Here’s the effect – keeping all other conditions the same as before:

SCR35 SCR37

What a difference! Sure, the flanks have become quite soft, but that ringing has also been reduced to one fifth of the original case. And those soft flanks (about 2 µs on the blue line) will probably just make it easier to dim the LED strips to very low levels.

The little hump at about 1V is when this particular MOSFET starts to switch – these units were specifically selected to switch at very low voltages, so that they would be fully switched on at 3.3V. This helps reduces heat generation in the MOSFETs – an important detail when you’re switching up to 2 Amps. And indeed, the STN4NF03L MOSFETs used here don’t get more than hand-warm @ 2A – pretty amazing technology!

The new LED Node v2 will include those extra resistors in the MOSFET gate, obviously. And that 1 kΩ value for R2 seems just about right.

The other resistor (R1) is a pull-down, it only serves to avoid unpleasant power-up spikes – by keeping the MOSFET off until the µC enables its I/O pins and starts driving it.

In case you’re wondering about the ringing on the yellow input trace: there’s something called the Miller effect, which amplifies the capacitance between the drain and the gate, causing strong signals on the output to leak back through to the gate. The input signal from my signal generator has a certain impedance and can’t fully wipe them out.

Oh, by the way, have a nice Sinterklaas! :)

Meet the Color Plug

In Hardware on Dec 4, 2012 at 00:01

Yet another plug designed by Lennart Herlaar:

DSC 4291

It contains the TAOS TCS3414 color sensor. JeeLib now includes a new ColorPlug class which simplifies reading out this chip, as well as a colorDemo.ino sketch:

Screen Shot 2012 12 03 at 15 17 47

Sample output:

Screen Shot 2012 12 03 at 14 03 40

One nice use for this sensor and code is to determine the color temperature of white light sources, such as incandescent lamps, CFL’s, and LED’s. I’m trying to find a pleasant replacement for a few remaining warm white halogen lights around the house here and such a unit (especially portable) could be very handy when shopping for alternatives.

Hardware description in the Café to follow soon, as well as in the JeeLabs shop.

Onwards!

Meet the Precision RTC Plug

In Hardware on Dec 3, 2012 at 00:01

Here’s another new board, the Precision RTC Plug – this is is a revision of a design by Lennart Herlaar from almost a year ago – my, my, this year sure went by quickly:

DSC 4292

The current RTC Plug from JeeLabs will be kept as low-end option, but this one reduces drift by an order of magnitude if you need it: that’s at most ≈ 1 second per week off over a temperature range of 0 .. 40°C. Or one minute per year.

Drift can go up to twice that for the full -40 .. +85°C range, but that’s still one sixth of the crystal used in the original RTC Plug. Considerably better than this, in fact, if you need the extended temperature range. Here’s a comparison between both plugs, from the datasheet:

Screen Shot 2012 12 02 at 12 58 23

The way the Precision RTC works is with a Temperature Compensated Crystal Oscillator (TCXO): once a minute, the approximate temperature is determined and the capacitance used by the crystal oscillator is adjusted ever so slightly to try and keep the 32,768 Hz frequency right on the dot. Since the chip also knows how long it has been running, it can even apply an “aging” correction to compensate this small effect in every crystal.

The temperature can be read out, but it’s only specified as accurate to ± 3°C.

No need to use any special software for this, all the normal clock functions are available through the same code as used with the original RTC Plug. If you want to use fancy functions, or perhaps calibrate things further for an even lower drift, you can access all the registers via normal I2C read and write comands.

The board will be added to the shop in a few days, and the wiki page on the Café updated.

Meet the JeeNode Micro v2

In Hardware on Dec 2, 2012 at 00:01

Just in yesterday, haven’t even had the time yet to assemble it!

DSC 4294

Dig that JeeLabs logo on there! :)

As you can see, the shape and layout have not changed much in this revision:

JMv2 traces

Here’s the main part of the new JeeNode Micro v2 schematic:

Screen Shot 2012 12 01 at 16 23 13

Several major changes:

  • the power to the RFM12B module is now controlled via a MOSFET
  • the PWR pin is connected to the +3V pin with 2 diodes
  • there’s room for an optional boost regulator (same as on the AA Power Board)
  • and there’s even room for a RESET button

When you look at the PCB’s, you’ll see that the extra headers have all been removed, there is just one 9-pin header left – the “IOX” signal from v1 now controls power to the RFM12B.

Through a sneaky placement of the ISP header, there is still a way to connect a single-cell AA or AAA battery to opposite ends of the board.

This extra power control is intended to reduce the current consumption during startup, but I haven’t tried it yet. The idea is that the RFM12B will not be connected to the power source before the ATtiny starts and verifies that the voltage level is high enough to do so. After that, it can be turned on and immediately put to sleep – in practice, its power probably never needs to be turned off again.

The other main change has to do with the different power options:

  • 2.2 .. 3.8V through the +3V pin, intended for 2-cell batteries of various kinds
  • 3.5 .. 5.1V through the PWR pin, for 5V and LiPo use
  • 0.9 .. 5.1V through the PWR pin when the boost regulator is present

The latter might seem the most flexible one, but keep in mind that the boost regulator has a 15 .. 30 µA idle current draw, even when the rest of the circuit is powered down, so this is not always the best option (and the extra switching supply components add to the cost).

As you can imagine, I’ll be running some final tests on all this in the next few days – but the new unit is now available for pre-order in the shop (“direct power” version only for now, the boost version will be available later this month). Design files are in the Café.

Picking up the P1 bus

In Hardware on Nov 30, 2012 at 00:01

With the smart meter installed, I just couldn’t resist a quick readout check of the serial data of the public “P1 port”. It’s an (inverted) TTL serial signal @ 9600 baud, even parity, 7 bits with data coming out the moment you put some voltage of the “request” line.

That request line is probably nothing other than the power feed of the optocoupler inside the unit, since the output voltage more or less matches the voltage I feed it. So this could probably be operated at 3.3V as well as 5V.

A good test case for the Hameg HMO2024 scope, which has serial bus decoding built-in:

SCR39

The green bars indicate correct parity. Not only is decoding a breeze this way, the latest scope firware update also added a “Bus Table” so that you can view the decoded data as a list and even dump it to a USB stick. Here’s the first part of what came out – as a CSV file:

  "Bus Table: BUS1 (UART: CH1, L, 9600,7,E,1)"
  Frame,Mark,Start time[s],Length,Data,State
  1,,7.90800e-6,1,'/',OK
  2,,1.04791e-3,1,'X',OK
  3,,2.08791e-3,1,'M',OK
  4,,3.12791e-3,1,'X',OK
  5,,4.16791e-3,1,'5',OK
  6,,5.20791e-3,1,'X',OK
  7,,6.24791e-3,1,'M',OK
  8,,7.28791e-3,1,'X',OK
  9,,8.32791e-3,1,'A',OK
  10,,9.36791e-3,1,'B',OK
  11,,10.40791e-3,1,'C',OK
  12,,11.44791e-3,1,'E',OK
  13,,12.48791e-3,1,'0',OK
  14,,13.52791e-3,1,'0',OK
  15,,14.56791e-3,1,'0',OK
  16,,15.60791e-3,1,'0',OK
  17,,16.64791e-3,1,'4',OK
  18,,17.68791e-3,1,'6',OK
  19,,18.72791e-3,1,'0',OK
  20,,19.76791e-3,1,'9',OK
  21,,20.80791e-3,1,'9',OK
  22,,21.84791e-3,1,0x0D,OK
  23,,22.88791e-3,1,0x0A,OK
  24,,23.92791e-3,1,0x0D,OK
  25,,24.96791e-3,1,0x0A,OK
  26,,26.00791e-3,1,'0',OK
  27,,27.04791e-3,1,'-',OK

Pretty trivial to decypher, so I whipped up a Tcl script for my trusty JeeMon swiss army knife (whatever works, right?):

Screen Shot 2012 11 29 at 18 08 52

And here’s the result of one scope capture (serial numbers were altered a bit):

  /XMX5XMXABCE000046099

  0-0:96.1.1(30313337323430332020202020202020)
  1-0:1.8.1(00003.540*kWh)
  1-0:1.8.2(00011.199*kWh)
  1-0:2.8.1(00000.000*kWh)
  1-0:2.8.2(00004.667*kWh)
  0-0:96.14.0(0002)
  1-0:1.7.0(0000.35*kW)
  1-0:2.7.0(0000.00*kW)
  0-0:17.0.0(999*A)
  0-0:96.3.10(1)
  0-0:96.13.1()
  0-0:96.13.0()
  0-1:96.1.0(3131323838323030303336383037303132)
  0-1:24.1.0(03)
  0-1:24.3.0(121129160000)(00)(60)(1)(0-1:24.2.0)(m3)
  (00014.684)
  0-1:24.4.0(2)
  !

(probably took some committee years of work to come up with this sort of gibberish)

Four electricity counter totals (night/day and consumed/produced, respectively), then two actual power consumption/production levels, then the gas meter readout. Note that the meter does not know the separate consumption and production levels – it only sees the total, but it can detect whether the flow is positive or negative.

Easy stuff. Access to the values used for our electricity and gas bill at last!

PS. This will also allow comparing and calibrating the results obtained by other means: three 2000 pulse/kWh counters attached to a JeeNode and three current transformers attached to the Flukso Meter. They each measure different things, but it’s all hooked up in such a way that the total consumption or production can be calculated with each setup.

Smart metering

In Hardware on Nov 29, 2012 at 00:01

JeeLabs has entered the 21st century…

The electricity company just installed a new “smart meter” – because they want to track consumed and produced electricity separately, something the total count on the old Ferraris-wheel meter cannot provide:

DSC 4279

See that antenna symbol on there? Its green LED is blinking all the time.

At the bottom on the right-hand side is an RJ11 jack with a “P1″ connection. This is a user-accessible port which allows you to get readings out once every 10 seconds. It’s opto-coupled with inverted TTL logic, generating a 9600 baud serial stream from what I’ve read. Clearly something to hook up one of these days.

The gas meter hanging just beneath it was also replaced:

DSC 4280

Why? Because it sends its values out periodically over wireless to the smart meter, which then in turn sends it out via GPRS to the utilities company.

Apparently these gas counter values are only reported once an hour. Makes sense, in a way: gas consumption is more or less driven by heating demands, and aggregated over many households these probably vary fairly slowly – depending on outside temperature, wind, humidity, and how much the sun is shining. Not nearly as hard to manage as the electricity net, you just have to keep the gas pressure within a reasonable range.

Electricity is another matter. And now it’s all being monitored and reported. Not sure how often, though – every 2 months, 15 minutes, 10 seconds? How closely will big brother be watching me? First internet & phone tracking, and now this – I don’t like it one bit…

Welcome to the 21st century. Everything you do is being recorded. For all future generations to come.

Snooping with an Optocoupler

In Hardware on Nov 28, 2012 at 00:01

The thing with OpenTherm, is that the amount of current going through the wire is used by the boiler to send messages to the thermostat.

The reverse path, i.e. from thermostat to boiler, is signalled by voltage changes, which are considerably easier to detect. So let’s save that for later.

There is a small complication, in that the polarity of the wiring between boiler and thermostat is not defined, so either one of them could be “”+” and “-“, respectively. Of course once you’ve hooked things up, that polarity never changes again.

Can we measure the current going through a wire, without knowing in which direction it is flowing? We know it’ll be 5..7 mA for one signalling state and 20..25 mA for the other.

Here’s what I came up with:

JC s Grid page 47

There are two optocouplers in there, with the diodes connected in opposite ways. Depending on the direction of the current, one of them will block and the other one will light up – once the voltage over the 82 Ω resistor exceeds about 1V, i.e. at ≈ 12 mA.

For documentation purposes, the actual build:

DSC 4272

The voltage drop over this circuit is at most just over 1V, which may or may not interfere with proper operation of the boiler and thermostat. Testing will be needed to find out.

The first advantage of this circuit is that it works with either polarity without needing a bridge rectifier (which would introduce yet another voltage drop). In addition, the output signal is galvanically isolated from the OpenTherm loop, i.e. “floating”. That means it can be connected in whatever way is needed.

The second part of an “OpenTherm snooper” – if it ever materialises – will be to measure the voltage between the wires and hopefully also to self-power the rest of the circuit. Note that the optocoupler LED lights up when a high current is passing through, and this is also the state where the photo transistor is drawing more current through the 10 kΩ resistor.

Here’s the diode voltage (yellow) and output (blue), using the same ± 10V @ 50 Hz signal as yesterday. The vertical zero axis is one division down from the centre, for both traces:

SCR96

Note how the output triggers on both positive and negative excursions of the input signal due to the anti-parallel LEDs, which is why it ends up having twice as many pulses. So the first half is one LED turning on and off, and the second half is the other LED – both lead to the common OUT pin being pulled down. For OpenTherm use, there’d never be both polarities – only one LED would be active, depending on how the circuit is connected.

The pulse-width asymmetry you see is an artefact of the way the sine wave is applied (using a 150 Ω resistor). This will not happen with a 7..25 mA current toggle and 82 Ω. And while the MCT62 is not one of the fastest optocouplers, especially with a 10 kΩ collector pull-up, I expect that the resulting pulses will still be accurate enough.

So far so good. I haven’t built the rest yet – just doodling and trying to figure it all out.

Sensing with an Optocoupler

In Hardware on Nov 27, 2012 at 00:01

The OpenTherm setup keeps me thinking…

I haven’t given up on the OpenTherm Gateway yet, but I’ve also been toying with related ideas for some time to try and just listen in on that current/voltage conversation using a self-powered JeeNode, which then reports what it sees as wireless packets.

It’s all based on Optocouplers, so here’s a first circuit to try things out:

JC s Grid page 47

A very simple test setup, which I’m going to feed a ±10V sine wave @ 50 Hz, just because the component tester on my oscilloscope happens to generate exactly such a signal. The 1 kΩ resistor is internal to the component tester, in fact. Here’s what comes out:

SCR93

The yellow trace is the voltage over the IR LED inside the optocoupler, the blue trace is the voltage on the OUT pin. VCC is a 3x AA Eneloop battery pack @ 3.75V – what you can see is that the LED starts to conduct at ≈ 0.8V, and generates just enough light at 0.975V for the photo transistor to start conducting as well, pulling down the output voltage. With 1.01V over the LED, it already generates enough light for the output to drop to almost 0V.

In other words: within a range of just 41 mV at about 1V, the optocoupler “switches on”.

So much for the first part of this experiment. My hope is that this behavior will be just right to turn this MCT62 optocoupler into a little OpenTherm current “snooper” – stay tuned…

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).

Bi-directional signalling and power

In Hardware on Nov 25, 2012 at 00:01

It looks like the OpenTherm gateway is sensitive to noise and wiring lengths. All my attempts to move the gateway upstairs, next to the boiler/heater, failed. Somehow, this:

  THERMOSTAT  <=>  GATEWAY  <=>  10 m wire  <=>  HEATER

… is not the same as this!

  THERMOSTAT  <=>  10 m wire  <=>  GATEWAY  <=>  HEATER

The OpenTherm documentation (PDF) specifically allows up to 50 meters of untwisted wiring, but I’m clearly running into some issue here.

Time to drag the scope downstairs and hook it up between gateway and heater:

SCR87

The yellow trace is the voltage between the two wires, while the blue trace is the current through those wires. I used a 1 Ω resistor and measured the voltage drop, but had to switch to the most sensitive scale (since I’m using the standard x10 probe), hence all that noise.

Still, you can see the magic of the way the OpenTherm protocol works:

  • in rest, there’s 6V between the wires and about 6 mA of current flowing (a 1 kΩ load)
  • this is used by the thermostat to power itself (by keeping a capacitor charged)
  • when the thermostat sends data, it briefly reduces its current draw
  • since the boiler (or gateway) is feeding a constant current, this makes voltage go up
  • that voltage change is then detected and decoded by the boiler / gateway
  • about 40 ms later, the boiler / gateway then sends a reply
  • it does this by briefly forcing more current down the wire
  • this in turn can be detected by the thermostat, which then decodes that reply
  • there’s a small residual ripple, as the thermostat tries to maintain its 7V idle level

I was going to perform the same measurement on the other side of the gateway, i.e. the connection to the thermostat, but for some reason the gateway really doesn’t like me touching anything or connecting any wires to it (let alone a grounded scope probe). Maybe some noise is picked up and feeding back into one of the PIC’s I/O pins, and completely throwing it off. Luckily, the whole gateway always resets properly when left alone again.

I also sometimes see the thermostat indicating a fault (even just by touching the wire with the scope probe) – so it seems to be getting some power, but it’s definitely not happy.

Maybe the gateway’s output circuit is too sensitive, due to some high-impedance parts in the circuit? That would explain why even just using some long wires two floors down prevents the gateway from working.

Hm, not good – especially since I only wish to monitor the wire, not control it…

Update – these problems are caused by a floating ground. More on this once I get it all sorted out. With many thanks to Schelte Bron for dropping by and helping analyse this!

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:

SCR84

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.

But…

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:

Mystery

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

SCR83

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

Bonus question: is this circuit actually useful for anything?

Tackling OpenTherm

In Hardware on Nov 18, 2012 at 00:01

Another project I’ve been meaning to tackle for a very long time is to monitor the central heating and warm water system. Maybe – just as with electricity – knowing more about what’s going on will help us reduce our fairly substantial natural gas bill here at JeeLabs.

The gas heater is from Vaillant and it’s connected to a Honeywell ChronoTherm – this is a “modulating” thermostat which automatically chooses its set-points based on the time of day and the day of the week. It all works really well.

The heater upstairs and the thermostat in the living room are connected by a two-wire low-voltage connection, using the OpenTherm protocol. There’s not that much “open” about this protocol, but people have hacked their way in and have discovered all the basic information being exchanged between these units.

A while back, I got a free PCB (thx, Lennart!) of a circuit by Schelte Bron, called the OpenTherm Gateway, and since all the required components were listed and easily available from Conrad, I decided to give it a go. Here’s the whole thing assembled:

DSC 4244

The documentation is very well done: schematics, parts list, troubleshooting, and more.

This is a “gateway” in that it sits between the heater and the thermostat, so it can not only listen in on the conversation but actually take over. Things you can do with it is to adjust the set-point (i.e. desired room temperature), feed in the temperature from an outside sensor, set the ChronoTherm’s clock, and probably more. I’m only interested in monitoring this stuff for now, i.e. reading what is being exchanged.

The gateway is based on an 8-bit PIC controller, and has some funky electronics to do its thing – because the way these signals are encoded is pretty clever: there are only two wires, yet the heater actually powers the thermostat through them, and supports bidirectional I/O (hint: it uses voltage and current modulation).

One little gotcha is that this gateway brings out its interface as an RS232-compatible serial port. And to my surprise, I found out that I don’t even have any laptops to read out these +/- 12V level signals anymore!

So the next task was to get things back into “normal” logic levels. Simple, although it’s a bit of a hack: remove the on-board MAX232 level converter chip, and insert wires to bring out the original 5V logic levels instead:

DSC 4250

(bare wire + green clip = GND, read wire + yellow clip = RX, white wire + white clip = TX)

Step two: hook it up to a USB-BUB, set to handle 5V logic levels:

DSC 4251

Step three: plug the USB cable into my laptop to pick up the data coming in at 9600 baud.

As you can see, this has wires dangling all over – just to check that the gateway works:

  OpenTherm Gateway 3.2
  T80190000
  B40193900
  T10010A00
  BD0010A00
  T80000200
  B40000200
  ...

Yeay, looks like we’re getting something! Coming up next: making sense of this data…

Ultra-low power op-amp

In Hardware on Nov 17, 2012 at 00:01

Op-amps are one of the building blocks of the modern analog electronics industry.

Here’s an interesting one, the MAX4470 .. MAX4474 series:

Screen Shot 2012 11 14 at 13 09 51

Simple layout, again in a tiny SMD package:

DSC 4269

The other members of this family are dual and quad versions, if you need more op-amps.

This chip is nice because of its phenominally low current consumption: 750 nA at 5V. It gets even better: at 3.3V, I measured a ridiculously low 190 nA!

Here are some more specs from the Maxim datasheet:

Screen Shot 2012 11 14 at 13 14 17

Might not be the highest-performance op-amp out there, but still – this thing could be quite handy to implement comparators, voltage followers, oscillators, amplifiers, filters, and more. Especially when the “power budget” is really really low.

PS. I’m assuming this chip isn’t oscillating with the above test setup, but in normal use you really need to tie the input pins to something to avoid that.

Nanoampere regulator

In Hardware on Nov 16, 2012 at 00:01

The TPS78233 from Texas Instruments looks like a standard LDO linear voltage regulator:

Screen Shot 2012 11 14 at 00 57 17

It takes an input voltage up to 5.5V and regulates it down to 3.3V (the above image from the datasheet is the 2.7V regulator). Not a spectacular voltage range, but it has a very nifty trick up its sleeve:

This regulator only draw 450 nA, i.e. 0.45 µA, when unloaded!

That’s about a quarter of the current consumption of the already-spectacular MCP1702 and MCP1703 used in JeeNodes – a ridiculously low 2.5 microwatts.

Here’s a little test setup (yep, those SMD’s are small – can you see the two 10 µF caps?):

DSC 4258

To get a sense of this level of current consumption: 3x AA batteries of 2000 mAh would last 5 centuries (ehm, well, except for their pesky self-discharge) – which is a bit silly, of course.

To get another idea: when I measure the output voltage with a multi-meter, the current consumption “jumps” to about 750 nA. Why this relatively big change? Because most multi-meters have a 10..11 MΩ input impedance, and 3.3V over 11 MΩ is… 300 nA!

In case you’re wondering: measuring minute currents is easy with Dave Jones’ µCurrent.

The fascinating thing about the TPX82xx series is that it achieves this extremely low idle current while still being able to regulate and supply up to 150 mA. Furthermore, that enable pin might come in very handy for certain ultra-low energy harvesting scenario’s.

But I’m not going to replace the regulator on JeeNodes for a number of reasons:

  1. The MCP1702 can handle input voltages up to 13V (vs only 5.5V for the TPS78233).

  2. There’s no through-hole version, so this would not work for standard JeeNode kits.

  3. Those extra savings only kick in when you get everything into the few-µA range, and so far, things like Room Nodes still draw a few dozen µA’s.

  4. In many cases, when the max is 5.5V anyway, no regulator will be needed at all (note that running only the RFM12B on it may create a problem with signal levels).

But hey, it’s good too know that these chips exist. A few microwatts… wow!

Microwave interference?

In Hardware on Nov 15, 2012 at 00:01

To get more options with remote nodes, I wanted to get this DCF77 clock working again, broadcasting the current time of day once a minute:

3311819588 20f3b58d12 o

Last time I tried (long ago), it didn’t work – but I’ve been running the OOK Relay for ages now, and since it still had the DCF77 receiver hooked up, I decided to have another go.

Sure enough – all it was is a broken wire… doh!

Now there are time-of-day packets in the air again, here at JeeLabs – sent by ookRelay2:

Screen Shot 2012 11 13 at 12 24 29

It works really well – at last – and will come in handy soon enough, I expect.

But the curious thing is those 3 missed packets at 12:13, 12:16, and 12:19.

Could it be the microwave? It was just around the time I was heating up something…

More investigation needed.

Watts up?

In Hardware on Nov 14, 2012 at 00:01

Ok, so all the solar panels are in place and doing their thing (as much as this season allows, anyway). But seeing that live power usage on my desk all day long kept tempting me to try and optimise the baseline consumption just a tad more…

Previous readings have always hovered around 115 Watts, lately. Since the JeeLabs server + router + internet modem use about 30 W together, that leaves roughly 85 W unaccounted for. Note that this is without fridges, boilers, heat circulation pumps, gas heaters, or other intermittent consumers running. This baseline is what we end up consuming here no matter what – vampire power from devices in “standby” and other basic devices you want to keep running at all times, such as the phone and internet connection.

It’s not excessive, but hey: 100 W day-in-day-out is still over 850 kWh on a yearly basis.

Well, today I managed to get the baseline down waaay further:

DSC 4242

That’s including the JeeLabs server + router + modem. So the rest of the house at JeeLabs is consuming under 40 W. Perfect: I’ve reached my secret goal of a baseline under 50 W!

Here’s how that “idle” power consumption was reduced this far:

  • I turned off an old & forgotten laptop and Ethernet switch, upstairs – whoops!
  • I removed another gigabit Ethernet switch under my desk (more on that later)
  • the 10-year old Mac Mini + EyeTV + satellite dish setup has been dismantled and replaced by a small all-in-one TV drawing 0.5W in standby (the monitor is re-used)
  • I’m switching to DVB-C (i.e. coax-based) reception, available from the internet modem by upgrading to the cheapest triple-play subscription with “analog + digital” channels
  • that means: no settop box, just the internet modem (already on anyway) and a new low-end but modern Sharp 22″ TV / DVB-C / DVD-player / USB-recorder

As it turns out, the Mac Mini (about 10 years old) plus the master-slave AC mains switch controlling everything else were drawing some 20 W – day in day out. Bit silly, and far too much unnecessary technology strung together (though working, most of the time).

The other biggie: no more always-on Ethernet switches, just the WRT320N wireless router in front of the server, with a second wired gigabit connection to my desk. That’s two really fast connections where it matters, everything else uses perfectly-fine WiFi.

The main reason for having an Ethernet switch near my desk was to allow experimenting with JeeNode-based EtherCards, Raspberry Pi’s, and so on. But… 1) that switch was really in the wrong place, it would be far more convenient to have Ethernet in the electronics corner at JeeLabs, and 2) why keep that stuff on all the time, anyway?

So instead, I’m now re-using a spare Airport Express as wireless-to-wired Ethernet extension router. Plug it in, wait a minute for it to settle down, and voilá – instant wired Ethernet anywhere there is an AC mains socket:

DSC 4243

And if I need more connections, I can route everything through that spare Ethernet switch.

It’s not the smallest solution out there, but who cares. Why didn’t I think of all this before?

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:

Esd

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…

Using watchdog resets

In AVR, Hardware, Software on Nov 9, 2012 at 00:01

The Bluetooth readout node running the “smaRelay” code is ready to go:

DSC 4237

As mentioned yesterday, I’ve decided to take the easy way out and completely power down the Bluetooth module and go through a full powerup/connect/readout cycle about once every 5 minutes.

The advantage for me of a battery-powered unit, is that I don’t have to locate this thing near a power outlet – it can be placed out of sight, unobtrusively doing its work.

I seem to have developed an allergy for power cables and wall warts all over the place…

The power on/off logic held a little surprise, about which I’ll report tomorrow.

Here’s is the new part of the updated smaRelay.ino sketch:

Screen Shot 2012 11 07 at 14 27 33

Quite a different use of the watchdog here:

  • on powerup, go into low-power mode and wait for 5 minutes
  • prepare the watchdog to perform a reset in 8 seconds
  • power up Bluetooth, connect to the SMA, and read out some values
  • then power down Bluetooth and power up the RFM12 radio
  • send out a data packet over RF12
  • lastly, turn the radio off and power down
  • let the watchdog do the reset and make this sketch start over

This approach has as “benefit” that it’ll fail gracefully: even if anything goes wrong and things hang, the hardware watchdog will pull the ATmega out of that hole and restart it, which then starts off again by entering an ultra-low power mode for 5 minutes. So even if the SMA is turned off, this sketch won’t be on more than about 1% of the time.

Here’s the energy consumption measurement of an actual readout cycle:

SCR80

The readings are a bit noisy – perhaps because I had to use 1 mV/div over a 1 Ω resistor (the 10 Ω used before interfered too much with this new power-switching code).

As you can see, the whole operation takes about 4 seconds. IOW, this node is consuming 153 milli-Coulombs every 300 seconds. That’s 0.5 mC/sec, or 0.5 mA on average. So the estimated lifetime on 3x AA 1900 mAh Eneloops is 3800 hours – some 5 months.

Update – The first set of batteries lasted until March 18th, 2013 – i.e. over 4 months.

Good enough for now. Deploy and forget. Onwards!

Bluetooth power consumption

In Hardware on Nov 8, 2012 at 00:01

The Bluetooth module in yesterday’s setup has a nasty power consumption profile:

SCR78

The yellow line is total power consumption, which to over 60 mA at times, and the smaRelay.ino sketch is querying the SMA inverter roughly every 10.5 seconds. The drop in baseline is the ATmega going to sleep as it waits for the next period, so you can clearly see what the Bluetooth module is doing – while kept on and connected to the SMA in fact.

I’m not sure that the Hameg’s math integral function is up to summing such fast-changing values, but it’s the best I’ve got to measure power consumption here at JeeLabs at the moment (well, either this or tracking the discharge on a hefty electrolytic capacitor).

Note the baseline consumption of about 5 mA, and the frequent but highly irregular brief power consumption pulses. That’s BT doing its frequency hopping thing, I assume.

Anyway, my goal was to get an estimate of the average power consumption, so here we go:

  • two cursors were used to peg the integral (summed) value over one cycle
  • charge usage over one 10.5 second period turns out to be 134 millicoulombs
  • that’s 134 / 10.5 ≈ 12.75 mC per second, i.e. 12.75 mA average

Whoa… not much of a candidate for battery-power this way!

That leaves a couple of options:

  • just power it via a USB adapter and move on
  • explore the RN-42’s low-power mode, which is claimed to go as low as 300 µA
  • completely turn off power to the RN-42

I’m inclined to go for the latter. I don’t really need solar PV readings that often, since the SMA accumulates its daily and total generated power anyway. And during the night, all this reading and reporting activity is also quite useless.

That would also solve – or rather: work around – the intermittent problems present in the current code, in which the sketch stops relaying after a few minutes. It always seems to get stuck after a while, waiting for incoming data from the Bluetooth module.

One readout every 10 minutes would probably be plenty for me, and since the SMA has a time-of-day clock which can be read out over BT, I can stop readouts during the night (or even simpler: add an LDR and switch off when it’s dark).

It looks like powering up, establishing a connection, and reading out one set of values can be done in under 6 seconds, so that leads to a 1% duty cycle. Let’s say 200 µA on average – this ought to run a year on 3x AA Eneloops.

Sometimes, sophisticated solutions are just distractions – whatever works, right?

Relaying SMA data as RF12 packets

In Hardware, Software on Nov 7, 2012 at 00:01

Yesterday’s post shows how to read out the SMA solar PV inverter via Bluetooth. The idea was to install this on the Mac Mini JeeLabs server, which happens to be in range of the SMA inverter (one floor below). But that brings up a little dilemma.

Install a potentially kernel-panic-generating utility on the main JeeLabs server? Nah…

I don’t really care whether this issue gets fixed. I don’t want to have the web server go down for something as silly as this, and since it’s a kernel panic, there’s no point trying to move the logic into a Linux VM – the problem is more likely in Apple’s Bluetooth / WiFi stack, which will get used no matter how I access things.

The alternative is to implement a little “SMA Relay” using a JeeNode with a Bluetooth module attached to it, which drives the whole protocol and then broadcasts results periodically over RF12. That way I can figure out and control it.

I tried to use the SoftwareSerial library built into the newer Arduino IDE releases, but ran into problems with lost bytes – even with the software UART speed down to 19200 baud.

So I ended up first debugging the code on an Arduino Mega, which has multiple hardware UARTs and allows good ol’ debugging-with-print-statements, sending out that debug info over USB, while a separate hardware UART deals with all communication to and from the Bluetooth module.

Once that worked, all debugging statements were removed and the serial Bluetooth was switched to the main (and only) UART of the JeeNode. The extra 10 kΩ R’s in the RX and TX lines allow hooking up a USB BUB for re-flashing. The BUB will simply overrule, but needs to be removed to try things out:

DSC 4236

(the Bluetooth module I used in this setup is Sparkfun’s BlueSMiRF Silver)

Next step was to add a little driver to JeeMon again, the aging-but-still-working Tcl-based home monitoring setup at JeeLabs. Fairly straightforward, since it merely needs to extract a couple of 16-bit unsigned ints from incoming packets:

Screen Shot 2012 11 06 at 10 39 10

And sure enough, data is coming in (time in UTC):

Screen Shot 2012 11 06 at 10 32 35

… and properly decoded:

Screen Shot 2012 11 06 at 10 33 08

The ATmega code has been added as example to JeeLib on GitHub, see smaRelay.ino.

I’m still debugging some details, as the Arduino sketch often stops working after a few minutes. I suspect that some sort of timeout and retry is needed, in case Bluetooth comms get lost occasionally. Bluetooth range is only a few meters, especially with the re-inforced concrete floors and walls here at JeeLabs.

Anyhow, it’s a start. Suggestions and improvements are always welcome!

New Flukso meter at JeeLabs

In Hardware on Nov 1, 2012 at 00:01

The Flukso is a little open-source box which can read out a couple of CT current clamps and/or pulse counters to provides electricity / gas / water consumption details – via a JSON/REST interface, either locally or on the Flukso site (private or shared, your call):

Flm02a top

The design is based on the Dragino, and includes an ATmega piggy-back board with extra circuitry specifically for reading out current clamps. It’s not every day that you see designs which can actually deal with power outages in such a way that the last readings get saved to EEPROM in the last few milliseconds – as the system is going down! – but that’s exactly what the Flukso does, showing its great attention to detail.

The Flukso meter’s designer, Bart Van Der Meerssche, is also the driving force behind the Electro:camp meetings, so we had some opportunities to chat and dream about the future these past few days. Lots of interesting options and wild ideas floating around. With Linux in the equation, a lot more sophistication becomes feasible.

To have a better test situation, I’ve decided to add a Flukso setup to JeeLabs, which is in fact trivial since it can connect over WiFi. Power consumption is under 3 W:

DSC 4231

I added the three current clamps as follows (consumption only, no PV solar yield for now):

  1. One 50 Amp CT clamp for the RCD-protected groups 1..3
  2. One 50 Amp CT clamp for the non-RCD-protected groups 4..7
  3. One 50 Amp CT clamp for the induction cooker, group 9

The total should match what I’m measuring with my other 2 pulse counters.

The daughterboard is a prototype with on-board RFM12B (software is work-in-progress).

The other news is that the pulse counter wiring has been fixed, so this is now correct:

DSC 4227

That’s an early morning with heavy clouds. Hey, where’s that sun when you need it!

Debugging with a scope

In Hardware, Software on Oct 30, 2012 at 00:01

Good, but not perfect… I was curious about the actual current consumption of this latest version of the homeGraph.ino sketch. So here’s another timing snapshot:

Annotated capture

This has trace persistence turned on, collecting multiple samples in one screen shot.

As you can see, the radio is turned on for ≈ 75 ms in this case (different JeeNode, slightly different watchdog timer period). Then after 30..35 ms the sketch goes to sleep again.

The second case is when nothing has been received after 150 ms: the “radioTimer” fires, and in this case the sketch turns off the radio as well, assuming there will be no packet coming in anymore.

But the interesting bit starts on the next packet coming in after one has been omitted. The logic in the code is such that the radio will be left on indefinitely in this case. As you can see, every late arrival then comes 100 ms later than expected: same radio-off + power down signature on the right-hand side of the screen capture, just much later.

Here is the code again:

Screen Shot 2012 10 21 at 22 41 49

And the main loop which calls this code:

Screen Shot 2012 10 21 at 22 06 18

That “if (!timingWasGood) …” code is probably wrong.

But it’s not so easy to fix, I’m afraid. Because the timing gets even more tricky if two or more packets are omitted, not just occasionally a single one. Sometimes, the radio doesn’t get switched off quickly – as you can see in this 30-minute capture at the end of the day, when power levels are starting to drop:

SCR56

Maybe I need to try out a software PLL implementation after all. The other reason is that there seems to be a fair amount of variation in watchdog clock timing between different ATmega’s. For one, I had to use 2800 as value for recvOffTime, with another 3000 worked a lot better. A self-locking algorithm would solve this, and would let us predict the next packet time with even more accuracy.

But this is still good enough for now. Normally the radio will only be on for about 100 ms every 3s, so that’s a 30-fold power reduction, or about 0.6 mA on average for the radio.

This still ought to run for a month or two on a 3x AA battery pack, at least for daytime use. Which brings up another idea: turn the whole thing off when it’s dark – the display is not readable without light anyway.

Oh well. Perfection is the enemy of done.

Final HomeGraph setup

In Hardware, Software on Oct 29, 2012 at 00:01

This concludes my little gadget to track home energy use and solar energy production:

DSC 4219

The graph shows production vs total consumption in 15-minute intervals for the last 5 hours. A summary of this infomation is shown at the bottom: “+” is total solar production in the last 5 hours, “-” is total energy consumption in that same period.

The actual consumption values are not yet correct because the home energy pulse counter is wired incorrectly, but they will be once that is fixed. The total home consumption is currently 1327 – 1221 + 7 = 113W, since the home counter is currently driven in reverse.

The graph is auto-scaling and I’m storing these values in EEPROM whenever it scrolls, so that a power-down or reset from say a battery change will only lose the information accumulated in the last 15 minutes.

Power consumption is “fairly low”, because the backlight has been switched off and the radio is turned off between predicted reception times. The mechanism works quite well when there is a packet every 3 or 6 seconds, but with longer intervals (i.e. at night), the sketch still keeps the receiver on for too long.

A further refinement could be to reduce the scan cycle when there are almost no new pulses coming in – and then picking up again when the rate increases. Trouble is that it’s impossible to predict accurately when packets will be skipped, so the risk is that the sketch quickly goes completely out of sync when packet rates do drop. The PLL approach would be a better option, no doubt.

But all in all, I’m quite happy with the result. The display is reasonably easy to read in daylight, even without the backlight. I’ll do a battery-lifetime test with a fresh new battery once the pulse counter wiring has been fixed.

The code has become a bit long to be included in this post – it’s available as homeGraph on GitHub, as part of the GLCDlib project. I’m still amazed by how much a little 200-line program can do in just 11 KB of flash memory, and how it all ends up as a neat custom gadget. Uniquely tailored for JeeLabs, but it’s all open source and easy to adapt by anyone.

Feel free to add a light sensor, a PIR motion detector, an RTC, whatever…

Onwards!

Who needs a server?

In Hardware, Software on Oct 25, 2012 at 00:01

With all those energy pulses flying through the air, we don’t even need a central setup to display this information on a little self-contained Graphics Board display – like so:

DSC 4214

The “homeGraph.ino” sketch which drives it has just been added to GitHub:

Screen Shot 2012 10 21 at 15 20 54

There’s room for a little graph, but it’ll have to wait until the home usage counter has been rewired to measure the proper value (the value shown above is in fact the surplus).

Goodbye Mousetrap

In Hardware on Oct 24, 2012 at 00:01

With the new “homePower” setup now in place and working, it is time to say goodbye to a good companion – this ATmega168-based mousetrap which started it all, 4 years ago:

DSC 4206

Note the dead spider :) – this thing has been soaked a few times, with water dripping from the kitchen on the next floor, yet all it took was a clean wipe, some time to dry, and it just resumed its duties over and over again:

DSC 4210

Very few problems other than that corrosion (probably also inside the mini 3-pin jacks):

DSC 4207

Less than a dozen resets / power cycles over all these years.

This is the predecessor of what eventually became the JeeNode, based on an RBBB by Modern Device. It works on 5V and uses resistor-based level converters for the RFM12B.

The gas measurements have been erratic for some time now, no doubt due to those bad contacts, so I’m going to look for another way to read those values.

And with it ends also the life of the node on the other side, a modified Arduino Mini plugged into the Mac Mini server using an FTDI cable:

DSC 4208

Also based on perf board with Kynar wire-wrapping wire to connect it all together:

DSC 4209

The code used between these two nodes was based on an early version of the RF12 driver protocol, and since it all worked perfectly, I never saw a need to change it. But I’m still going to miss these periodic packets in the logfiles:

  L 09:05:02.167 usb-FTE50C3P HM3 45 43 17 151 73 20 6 0 242 200 0 0 0 0
  L 09:05:07.363 usb-FTE50C3P HM3 45 44 18 151 80 20 6 0 242 200 0 0 0 0
  L 09:05:12.290 usb-FTE50C3P HM3 45 45 19 151 47 19 6 0 242 200 0 0 0 0
  L 09:05:17.361 usb-FTE50C3P HM3 45 46 20 151 200 19 6 0 242 200 0 0 0 0
  L 09:05:22.720 usb-FTE50C3P HM3 45 47 21 151 240 20 6 0 242 200 0 0 0 0
  L 09:05:27.646 usb-FTE50C3P HM3 45 48 22 151 49 19 6 0 242 200 0 0 0 0

Goodbye, dear nodes, and thank you for those nearly 4 years of perfect service!

PS – Don’t forget Elektro:camp next Friday and Saturday!

Solar at last

In Hardware, News on Oct 20, 2012 at 00:01

As mentioned recently, last step was getting the SMA 5000TL inverter and hooking it up:

DSC 4200

DSC 4203

Here’s the before-and-after shot of the hookup:

DSC 4190

DSC 4192

Three pulse-counters to help me measure what comes in, what goes out, and the induction stove (measured separately). Still a minor wiring error, but that’ll be fixed soon.

So that’s the end of the story for now. Let the sun shine!

Solar Railway Station

In Hardware on Oct 19, 2012 at 00:01

On a recent trip to Germany, we visited Uelzen, about 100 km north of Braunschweig. Its railway station was “upgraded” (pimped?) some 12 years ago by an Austrian artist called Friedensreich Hundertwasser in what looks very Gaudi-like in style and appearance:

PA175185

He was interested in organic shapes, creating round and uneven fairy-tale like interiors:

PA175215

But the reason I’m mentioning all this, is that the station also includes this display panel:

PA175218

The roof is covered with solar panels, and has been generating electricity for the community since 1997. Almost half a megigawatt-hour produced so far, and still generating just under 8 Kilowatt on a half-cloudy October day.

Way to go! So gibt mann das gute Vorbild!

PS. Calculating back from the figures shown, this would appear to be just 42 m2 of panels, which seems off by an order of magnitude. Oh, wait… that’s not accounting for the panel’s conversion efficiency, I’m guessing that to be somewhere in the 10% range for those panels.

Going solar – almost there!

In Hardware on Oct 15, 2012 at 00:01

It’s been over two years ago since I started looking for ways to collect solar energy on the roof, here at JeeLabs.

And then reality set in… the roofs of the houses in this street are covered with shingles from the late 70’s, and as we found out they contain asbestosyuck! Then, earlier this year, we were told that nothing could be done on the roof unless those shingles were first officially removed by a specially-equipped third party:

Image 5

So now at last, those “bad” shingles have been replaced and panels have been mounted:

DSC 4177

That little bulge is a “Solar tube” which brings extra sunlight into the stairway.

That’s 2 x 5 panels on this side, and 3 x 4 on the other roof:

DSC 4183

(the 10 panels you saw in the first picture are mounted on the roof to the far left)

For a total of 22 x 240 = 5280 Wattpeak. Not that they will ever all generate full power at the same time, because these two roofs are facing west and east, respectively. But hey, together they should still give us more than our annual 3100 kWh consumption. JeeLabs is about to become a net electricity producer!

Just one more step: wait for the SMA 5000 inverter to arrive and get it hooked up…

Mechanical relays

In Hardware on Oct 13, 2012 at 00:01

Hm… with such a nice switching 5V pulse, it’s sad to tear down yesterday’s circuit again.

One more experiment then. Let’s switch a little relay (the one used in the Relay Plug) at 10 Hz, and give it a serious beating. I’m going to put my dual power supply to work and put 5V @ 3A straight across the relay’s contacts. In other words, let’s see what happens when we switch the full 3A across those tiny relay contacts.

At first sight, it all looks reasonably ok:

SCR46

That’s 5V across the relay while it’s open, and about 0.3V when it closes. So these contacts seem to have a resistance of about 0.1 Ω. The overshoot when the relay opens up again is probably in the power supply, as it recovers from just having been shorted out at 3A. Note that any inductance in the wiring will have this same effect. Inductance is a bit like a flywheel – it wants to keep going after such massive current (i.e. magnetic field) changes.

It’s quite impressive to see how this little relay rattles away at ≈ 10 Hz, working just fine.

But those transitions look quite different when we zoom in:

SCR47

You’re seeing a mix of arcing and contact bounce, as all mechanical switches do.

Note that the switch hasn’t quite closed yet – there is still about 1.5V between the contact points, 30 µs after switching – due to contact bounce. This drops to 0.3V after some 400 µs, at which point the contacts are really firmly closed.

Here’s a much better example, this time using a 10 Ω resistor in series so the power supply just delivers 5V @ 0.5A without going into current-limiting mode:

SCR50

Opening is again not quite what it seems, once you zoom in:

SCR48

Two things happening here: the mechanical release of the switch (less resistance as the pressure on the contact decreases, followed by some arcing), and then a fairly linear ramp and some overshoot as the power supply recovers its 5V setting after having been shorted out. Think of a stretched rubber band, and how it “overreacts” when released.

So as you can see, a relay does some nasty things while switching on and off!

Digital opto switching

In Hardware on Oct 12, 2012 at 00:01

While on the subject of optocouplers, there’s another type besides “analog” ones and “digital” ones (which include a comparator), and that’s the opto-relay. Again with several kilovolts of isolation.

The Avago ASSR-1611 is an interesting one, for example, because it uses MOSFETs:

Screen Shot 2012 10 07 at 14 11 47

Basically, it lets you switch up to 60V at a few amps. To see how it performs, while I still have that linear ramp circuit up and running, I hooked it up – as a big mess-o-wires:

DSC 4173

It’s getting pretty crowded in there. The ASSR-1611 is on the left. Here’s its schematic:

Screen Shot 2012 10 07 at 14 07 07

The interesting bit is that there are diodes in there, so it can deal with alternating current when hooked up differently, i.e. by using pins 4 and 6 instead of 5 and 6.

First thing to notice, is that this thing behaves in a strange way when switched at 1000 Hz:

SCR43

It “sort of” triggers … slowly (keep in mind that turning on translates to shorting the output to ground, as before). And then it decides to turn off again very quickly. For some reason this repeats about 10 times per second.

To slow the triangle wave rate way down, I used a 10 µF capacitor instead of 0.1 µF:

SCR44

Aha! Much better. At about 0.7 mA (purple voltage over 1 kΩ = 0.7V), this solid state relay switches on, and once the current drops back to almost 0, it switches off. Note how these readings match the specs nicely: turning on, i.e. the blue line dropping to 0, takes a few ms, whereas turning off is virtually instant.

At a few Euro each, these chips are not really cheaper than mechanical relays, but when you only need to switch a few dozen Volt at a few Amps, then this solution still has the benefit that it switches far more cleanly – with no arcing or mechanical wear. And it’s totally quiet, of course…

Optocoupler current transfer

In Hardware on Oct 11, 2012 at 00:01

The past few days were about generating a linear ramp, in the form of a triangular wave, and as you saw, it was quite easy to generate – despite the lack of a function generator.

The result was a voltage alternating between about 0.6V and 3.0V in a linear fashion. Here’s why…

I want to see how the MCT62 optocoupler passes a signal through it. More specifically, how a linearly increasing voltage would come out. Let’s look at that chip schematic again:

Mct621

So the idea is to apply that linear ramp through a current-limiting resistor into the opto’s LED. Then we put the photo-transistor in a simple 5V circuit, with again a current limiting resistor between collector and 5V – like this:

JC s Grid page 35

From left to right:

  • apply a triangle wave to the LED, which varies from 0.6 to 3.0V
  • there’s a 1 kΩ rsistor in series, so the maximum current will stay well under 3 mA
  • the phototransistor is hooked up as a normal DC amplifier
  • there’s another 1 kΩ pullup, so this too cannot draw more than 5 mA current

Prediction:

  • when the LED is off, the output will stay at 5V, i.e. transistor stays off
  • until the input rises above the 1.2V threshold of the (IR) LED, not much happens
  • as the voltage rises linearly, so will the current through the LED
  • depending on the transfer function the transistor current will rise accordingly
  • and as a consequence, the output voltage will drop

So if that behavior is linear, then the output voltage should drop linearly. Let’s have a look:

SCR42

  • the YELLOW line is the triangle wave, as generated earlier
  • the PURPLE line is the voltage over the leftmost resistor
  • the BLUE line is the voltage on the transistor’s collector output
  • the RED line is the derivative of the BLUE line
  • the zero origin for all these lines in the image is at two divisions from the bottom

First of all, the purple line indeed rises slowly once we start rising above 1.0V, and it stays roughly 1.2V under the input signal (yellow line).

The blue line is the interesting one: it takes a bit of input current (i.e. LED light) for the transistor to start conducting, but once it does, the output voltage drops indeed. Once we’re above 2.0V, the blue line becomes quite linear. As indicated by the fact that the red line is fairly flat between horizontal divisions 5 and 7.

So in this range (and probably quite a bit above), we have a linear transfer from input current to output current. Or voltage … it’s all the same with resistors.

In terms of current, we can use the purple line: it’s flat with a diode current between 0.7 and 1.7 mA (and probably beyond).

The output voltage only drops to just over 2V, so the phototransistor is still far from reaching saturation (“conducting all out”).

So what’s the point of all this, eh?

Well, one thing this illustrates is that you can get a pretty clean signal across such an optocoupler, as long as you stay in the linear range of it all. There is no real speed limitation, so even audio signals could be sent across reasonably well – without making any electrical connection, just a little light beam!

It’s not hard to imagine how this could be done with discrete components even, sending the light to a glass fiber over a longer distance.

You can call it wireless signal transmission, albeit of a different type: optical!

Pretty good triangles

In Hardware on Oct 9, 2012 at 00:01

As of yesterday, we now have a “triangular wave generator”. Whee!

Except that I don’t want a voltage between 1.25V and 3.75V but slightly lower. One way to accomplish this is to lower the reference “1/2 Vcc” voltage used by the comparator and integrator circuits. So I added a 22 kΩ resistor in parallel on one half of the voltage divider:

+5V  <=>  10 kΩ  <=|=>  (10 kΩ and 22 kΩ in parallel)  <=>  GND
                   |
                  TAP

This online calculator says that the parallel value is 6.875 kΩ. Here’s the resulting signal:

SCR38

It’s now slightly asymmetric (we’re discharging faster than we’re charging), but more importantly, the signal now runs from about 0.6V to 3.0V, which is more in sync with what I need (more on that in an upcoming post).

Notice that on these screen shots, the waveforms look very nice and straight, although it’s hard to see just how linear those ramps really are.

This is where a scope with good math functions comes in. If you recall from mathematics, the derivative of a straight line is a constant. Or to put it differently: the straighter the line is, the closer its derivative should be to a constant value. Positive for upward slopes, and negative for downward slopes. Let’s zoom in a bit:

SCR37

(the red line’s origin is centered vertically, the yellow line is at 1 division from the bottom)

That red line is the scope’s calculated derivative of the yellow line (it’s really just a matter of calculating differences between successive points). As you can see, the upward slope is pretty straight from 1.3V to 2.9V. The downward slope less so, IOW the capacitor discharge is not quite as linear. The signal was averaged over 128 samples in this last screen.

Excellent. I now have the signal I need to perform my experiment. Stay tuned.

Triangular wave generator

In Hardware on Oct 8, 2012 at 00:01

Let’s build an oscillator, now that we can generate linear ramps. But to get there, we’ll need a second op-amp circuit (1/2 Vcc is the middle of two 10 kΩ R’s between Vcc and GND):

JC s Grid page 34

This is a comparator with hysteresis, or Schmitt trigger. Same rules as yesterday, of course.

In contrast to yesterday’s setup, there is no negative feedback here, but a resistor between “OUT” and “+”. So in this case, when the output rises, it’ll cause “+” to rise even more, instead of bringing it closer to the “-” input.

This circuit doesn’t work towards an equilibrium, it’s unstable. Let’s start with the output being VCC, i.e. +5V. What will the input need to be to make it change?

  • the desired change can only happen, when the “+” input drops below 2.5V
  • with OUT at +5, that’s 2.5V over 20 kΩ, i.e. 125 µA
  • to pull “+” under 2.5V, we need to draw at least 125 µA out through the 10 kΩ resistor
  • that’s 1.25V under 2.5V, i.e. with the IN level under 1.25V

So when IN drops under 1.25V, the op-amp has a change of heart so to speak, and starts bringing OUT down in an attempt to bring “+ and “-” back to the same level. The silly thing is that it can’t, because lowering OUT is never going to raise the “+” back up to 2.5V (still with me?). So the output just keeps keeps dropping all the way to its minimum, which will be more or less equal to 0V.

Let’s review what happened: we started dropping the input level, and once it reached 1.25V, the output violently flipped from +5V to 0V.

Now the situation is reversed: how far do we need to raise the input to make the output go up again? Well, that’ll be 3.75V – using the same reasoning as before, but now based on 2.5V (the “-” pin) + 1.25V (the voltage over the 10 kΩ resistor.

So what this circuit does is flip between 0 and 5V, at trigger points 1.25V and 3.75V.

Now the magic part: we tie the input of this circuit to the output of yesterday’s circuit, and vice versa, creating a control loop. If you look back at yesterday’s scope image, you’ll see that the triangular wave flips at… 1.23V and 3.72V. What a coincidence, eh? Nah… it’s all by design. The comparator drives the integrator by feeding it 0 and 5V levels, and it switches when the integrator output reaches 1.25V and 3.75V. Since the capacitor requires a little time to charge, this ends up being a nicely controlled oscillator. Perfect!

Here’s my test circuit (for a complete schematic, check this website, for example):

DSC 4170

Tomorrow, I’ll change the signal slightly and I’ll examine how linear those ramps are.

Triangular waves

In Hardware on Oct 7, 2012 at 00:01

For an upcoming experiment, I’m going to need a slowly rising voltage, and with my signal generator currently out for a check-up, it’s time to dive into some electronic circuitry again. Let’s try to generate a sawtooth or triangular wave signal with a few basic components. After my search for a simple sine wave generator, I’m happy to report that generating “ramp voltages” is actually a lot simpler.

The reason for this is that all you need to generate a linear ramp, is a constant current into a capacitor. This automatically produces a linear voltage ramp. The electrical notation for such a circuit is:

JC s Grid page 34 copy

The voltage over that capacitor will rise linearly over time. It looks so simple! (well, apart from figuring out how to build a constant current source, perhaps)

But that’s only half the story. What to do once the capacitor has been fully charged up? We need to discharge it again, clearly. One way to do this, is to put a transistor or MOSFET across the cap and periodically make it turn on (briefly!) to discharge the circuit again. Ok, so now we need a periodic pulse as well. Hmmm…

There is another solution: op-amps. The op-amp is a truly amazing little building block. What we need here, is to use two op-amps in different configurations: one as an integrator and one as a comparator.

Let’s start with the integrator, because that explains how we can get a linearly varying voltage out of the circuit:

JC s Grid page 34

An op-amp has two properties, both crucial for explaining this little 3-component circuit:

  • both inputs are very high resistance, so virtually no current flows in or out
  • the output is constantly adjusted to try and keep both inputs at the same voltage

That second property can also be described as: when “+” is higher than “-“, the output will go up (towards Vcc, the supply voltage), when it’s lower, the output will go towards 0 (the ground voltage in a single-supply setup).

Here we’re tying “+” to half Vcc, in this case 2.5V, so you can think of the op-amp as trying to do whatever it can to keep the “-” pin at 2.5V as well.

Let’s start with everything in perfect balance, then “+”, “-“, and “OUT” will all be at +2.5V, and the capacitor will have no charge. Now let’s take the input to +5V:

  • a constant current starts flowing into the resistor, since the other side is +2.5V
  • this current drives the “-” pin up, so the output will go down
  • how far down? well as much as needed to cancel out that incoming current
  • IOW, the same current is going to go into the capacitor, which starts to charge up
  • as the charge builds up, less current starts to flow into the capacitor
  • “no way” says the op-amp, and so it pulls its output lower
  • so a constant current flows into the cap, and the output drops lower and lower
  • at some point near 0V the op-amp reaches its limit, and the mechanism breaks down

To give a water analogy: think of pouring water into a glass at a constant rate while trying to keep the surface of the water the same. You have to gradually lower the whole glass to make this work. As you do, the glass (cap) will contain more and more water (voltage). You’ve integrated (collected) the water flow into the glass!

If we keep the input voltage high, nothing more will happen: the cap will end up being fully charged, and the op-amp can no longer do anything to keep the “-” input from rising all the way to the input voltage.

When we now drop the input voltage to 0V, the reverse happens. Current flows through the resistor in the other direction, and the cap starts discharging. Again, the op-amp will do whatever it can to maintain that “-” at 1/2 Vcc. It does this by raising its output pin causing the capacitor to discharge with that same constant current rate. And sure enough, the voltage over the capacitor drops linearly. Until we hit the limits, and the process stops.

Here’s the effect in action, as seen on an oscilloscope (R = 4.7 kΩ, C = 0.1 µF, and the op-amp is an OPA2340):

SCR35

The blue line is the input signal, the yellow line is the triangular wave output. Neat, eh?

Tomorrow, I’ll add an op-amp as comparator to make this circuit oscillate all by itself.

Murphy goes opto

In Hardware on Oct 6, 2012 at 00:01

It looks like Mr. Murphy has found some time to mess with things again…

The Optocoupler Plug is a little board to let you isolate two I/O pins. When you drive one end with a small voltage to light up a little LED inside, it shines that light onto a sensitive photo-transistor which then starts conducting. It’s effectively a tiny switch, driven by light.

The nice thing about light is that it lets you avoid an electrical connection. So this thing allows you to detect a (small) input voltage without actually making a connection to it. These units support over a thousand volt of isolation – perfect when messing with AC mains coupled circuits, for example.

But the Optocoupler plug is actually two plugs in one, because you can also use it as an output by using it in reverse: then, the two I/O pins on a port can be used as output to turn on the LEDs, and the phototransistors can then control some output circuit without having to actually connect to it.

Here’s the “dual-mode” configuration of the Opto-coupler Plug:

Jumpers

In one mode, it can be used as input (with current limiting resistors on the right), in the other it’s an output (current-limiting resistors on the left, and solder jumpers on the right).

The unit I picked for this board is an MCT62:

Mct62

Then we recently switched over to a HCPL-2631, without thinking much about it:

Opto 2631

Whoops! Different pinout, but also entirely different beast: the MCT62 contains a pair of independent simple “analog” type optocouplers. The HPCL-2631 on the other hand is a “digital” model with some built-in amplification. Which means that this thing needs a power supply, and to stay within the 8-DIP pinout, this can only be realised by tying a common “ground” together and re-using the other as supply voltage.

There’s a lot more to describe about this apparently simple device, but for now all I can say is “we messed up!”. Fortunately, only four people have been affected by this so far, and we’ve contacted each one of them to resolve the problem and send a replacement out. To each of you, my apologies for the confusion and for wasting your time if you’ve been trying to get those faulty Optocoupler Plug kits to work.

With thanks to Jupe Software for reporting the issue, and saving others more grief!

Pssst … this is post # 1111 !

ARMs on Foam

In ARM, Hardware, Linux on Sep 29, 2012 at 00:01

One of the things I’d really like to do is hack on that Laser Cutter I described recently.

The electronics is based on a LaOS Board, but I’d like to see what you can do with an embedded Linux board such as a Raspberry Pi in this context – driving that LaOS board, for example. Because adding Linux to the mix opens up all sorts of neatness.

So here’s my new prototype development setup:

DSC 4163

That oh-so-neat foam board acts as base, with two PCB’s fastened to it using, heh … remember these?

DSC 4164

They’re called “splitpennen” in Dutch. Long live foam board and splitpennen!

This is a pretty nifty setup, in my opinion. Tons and tons of ways to implement features on this combo, and there’s plenty of power and storage on both boards to perform some pretty neat tricks, I expect.

Anyway – this is more a big project for cold winter days, really. It’ll take a long time before anything can come out of this, but isn’t it incredible how the prices of these things have reached a point where one can now dedicate such hardware to a project?

ARM to ARM upload

In ARM, Hardware, Software on Sep 27, 2012 at 00:01

After yesterday’s basic connection of an LPCXpresso 1769 board to the Raspberry Pi, it’s time to get all the software bits in place.

With NXP ARM chips such as the LPC1769, you need a tool like lpc21isp to upload over a serial connection (just like avrdude for AVR chips). It handles all the protocol details to load .bin (or .hex) files into flash memory.

There’s a small glitch in that the build for this utility gets confused when compiled on an ARM chip (including the Raspberry Pi), because it then thinks it should be built in some sort of special embedded mode. Luckily, Peter Brier figured this out recently, and published a fixed version on GitHub (long live open source collaboration!).

So now it’s just a matter of a few commands on the RPi to create a suitable uploader:

    git clone https://github.com/pbrier/lpc21isp.git
    cd lpc21isp
    make
    cp -a lpc21isp ~/bin/

Next step is to get that board into serial boot mode. As it turns out, we’re going to have to do similar tricks as with the JeeNode a few days ago. And sure enough, I’m running into the same timing problems as reported here.

But in this case, the boot load process is willing to wait a bit longer, so now it can all easily be solved with a little shell script I’ve called “upload2lpc”:

# export the two GPIO pins to the shell
echo "18" >/sys/class/gpio/export >&/dev/null
echo "23" >/sys/class/gpio/export >&/dev/null

# use them as output pins
echo "out" >/sys/class/gpio/gpio18/direction
echo "out" >/sys/class/gpio/gpio23/direction

# pull ISP low and prepare for reset
echo "0" >/sys/class/gpio/gpio23/value
echo "1" >/sys/class/gpio/gpio18/value

(
  # it is essential to delay the reset pulse for lpc21isp
  sleep 0.3
  # pulse reset low
  echo "0" >/sys/class/gpio/gpio18/value
  sleep 0.1
  echo "1" >/sys/class/gpio/gpio18/value
  # set ISP line high again
  echo "1" >/sys/class/gpio/gpio23/value
) &

echo "Uploading... "
lpc21isp -debug0 -bin $1 /dev/ttyAMA0 115200 12000 \
  && echo "Done." || exit 1

The result? We can now reset the LPCXpresso from the Raspberry Pi and upload some blink code to it:

    $ sudo ./upload2lpc blink.bin
    Uploading...
    Done.

Yippie: it resets, it uploads, it blinks – and it does so consistently! Onwards! :)

Update – For best results, also add a “sleep 0.1″ between those two last echo 1’s.

ARM to ARM serial connection

In ARM, Hardware, Linux on Sep 26, 2012 at 00:01

After connecting a JeeNode to a Raspberry Pi, let’s do the same with the LPCXpresso I mentioned a while back. Let’s do it in such a way that we can upload new code into it.

With an LPC1769, this is even simpler than with an ATmega328, because the serial boot loader is built-into the chip out of the box. No need to install anything. So you can always force the chip back into serial boot loader mode – it can’t be “bricked” !

But the process is slightly different: you have to pull down a specific “ISP” pin while resetting the chip, to make it enter serial boot loader mode. So we’ll need one more GPIO pin, for which I’ll use the RPi’s GPIO 23. The wiring is even cleaner than before, because this time I planned a bit more ahead of time:

DSC 4156

Except that this runs into the same problem as before. The LPCXpresso does not have the essential 3.3V regulator next to the ARM chip, it’s on the part that has been cut off (doh!). So again, I’m going to have to add an SMD MCP1703 regulator:

DSC 4157

(that little critter is between pins 1 and 2, and upside down, to get the pinout right)

Here’s the complete hookup:

DSC 4159

First step is again to make sure that Linux isn’t doing anything with the serial port:

  • remove the two args referring to /dev/ttyAMA0 in the file /boot/cmdline.txt

  • add a hash (“#”) in front of this line in /etc/inittab to comment it out:

    T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
    
  • make the system aware of the changes in inittab with: kill -1 1 (or reboot)

Tomorrow, I’ll go into actually uploading to that LPC1769 ARM board. Stay tuned!

Note – As of October 1st, VAT prices in the Netherlands will increase from 19% to 21%. As a consequence some adjustments will also have to be made in the JeeLabs Shop. Up or down depends on many obscure factors, including exchange rates, current costs, stock levels, and the wish to stick to decently rounded values – so if you want to avoid any surprises and were planning to order stuff, please keep that switch-over date in mind.

Linux real-time hickups

In Hardware, Software on Sep 24, 2012 at 00:01

To give you an idea why a simple little Linux board (the Carambola on OpenWrt in this case) is not a convenient platform for real-time use, let me show you some snapshots.

I’ve been trying to toggle two I/O pins in a burst to get some data out. The current experiment uses a little C program which does ioctl(fd, GPIO_SET, ...) and ioctl(fd, GPIO_CLEAR, ...) calls to toggle the I/O pins. After the usual mixups, stupid mistakes, messed up wires, etc, I get to see this:

SCR18

A clean burst on two I/O pins, right? Not so fast… here’s what happens some of the time:

SCR19

For 10 ms, during that activity, Linux decides that it wants to do something else and suspends the task! (and the system is idling 85% of the time)

If you compare the hex string at the bottom of these two screenshots, you can see that the toggling is working out just fine: both are sending out 96 bytes of data, and the first few bytes are identical.

The situation can be improved by running the time-critical processes with a higher priority (nice --20 cmd...), but there can still be occasional glitches.

Without kernel support, Linux cannot do real-time control of a couple of I/O pins!

Upload to JeeNode fixed

In Hardware, Linux on Sep 23, 2012 at 00:01

Ok, I finally figured out what caused yesterday’s upload problem. It’s indeed timing.

But not quite as I thought, and I missed a hint in the scope signal capture yesterday (at 322 ms after the reset). My premature conclusion was that resetting the GPIO pin and then starting up avrdude was taking too long, so the boot loader would give up before receiving the proper starting character over the serial line.

But that doesn’t quite make sense. Looking at the screen shot again, we can see that the RF12demo greeting (blue line) starts about 800 ms after the RESET pin gets pulled low. Even though OptiBoot is supposed to wait a full second after power-up. And there are two handshake attempts well within that period.

The other subtle hint was in the not-quite-equidistant characters being sent out (yellow line). Why would handshake chars be sent out in such a repeatable yet irregular pattern?

Having written an avrdude replacement in Tcl for some experiments I did with JeeMon a while back, I decided to try and extend it a bit to toggle the reset pin right before sending out the data. That way no delay would interfere, so the reset would happen moments (probably mere milliseconds) before starting the boot loader serial handshake. I didn’t really want to start hacking on avrdude for such a “simple” task as toggling a GPIO pin on the Raspberry Pi. Besides, that replacement code is only 70 lines of Tcl, if all you have to deal with is the basic stk500 protocol understood by the boot loader.

Controlling the GPIO pin also turned out to be pretty straightforward:

Screen Shot 2012 09 20 at 23 59 50

But no matter what I tried, and no matter what timing delays I inserted, the darn thing just wouldn’t upload!

Then, just for the heck of it, I tried this variation – reversing the open and reset order:

Screen Shot 2012 09 21 at 00 01 18

And lo and behold – now it works: repeatedly and reliably!

Here’s the scope’s serial protocol analyser, showing a proper upload in progress:

SCR32

You can see data being sent to the JeeNode, and the 0x14h reply sent back to the RPi.

So was this all about timing? Yes and no. Let’s revisit yesterday’s list of pulses again:

Screen Shot 2012 09 21 at 00 06 02

A single pulse 322 ms after reset, and then several pulses at 673 ms (presumably the first boot loader protocol handshake character). The problem is really that first pulse – it’s not a valid character but a glitch!

What I think is happening is that the JeeNode resets, the glitch at 322 ms causes the boot loader to give up and launch the sketch, and then all subsequent boot handshake characters get ignored. Looks like opening the serial port produces a glitch on the transmit output pin.

By first opening the serial port and then doing the GPIO18 reset, the problem is avoided, and then it all works.

Thank you JeeMon – I hadn’t expected to fire you up again, but you’ve saved my day!

Timing troubles with upload

In AVR, Hardware on Sep 22, 2012 at 00:01

Since the Raspberry Pi can now reset a JeeNode, I assumed that uploading would be a piece of cake. Hmmm… maybe not quite.

The trouble is timing, and I’m currently I was pulling my hair out on this one:

  • the plan is to reset the JeeNode and then have avrdude upload new code to it
  • this works automagically when opening a serial port causes DTR to go low
  • but here, we don’t have DTR or RTS, this is a basic serial port on GPIO pins
  • what we do have, is a GPIO pin 18 which can be pulled low to force a reset

At the moment, there seems to be a major problem with timing:

SCR31

Here’s how to decode this screen shot:

  • the YELLOW line is serial from RPi to JeeNode
  • the BLUE line is serial from JeeNode to RPi
  • the MAGENTA line is the reset pulse on the GPIO pin

The way I test this, is via a shell script which first toggles reset using /sys/class/gpio/…, and then launches avrdude to perform the upload, using these commands:

echo 18 >/sys/class/gpio/export
echo out >/sys/class/gpio/gpio18/direction
echo 1 >/sys/class/gpio/gpio18/value
sleep 0.1
echo 0 >/sys/class/gpio/gpio18/value
avrdude -pm328p -carduino -P/dev/ttyAMA0 -D -Uflash:w:test.hex:i
echo 18 >/sys/class/gpio/unexport

Here’s what actually happens, I think:

  • the GPIO pin is correctly pulsed high and then dropped low after 0.1 s
  • the scope triggers on that falling edge, presumably same time as the ATmega resetting
  • after 323 ms, I see a 30 µs blip on the outgoing serial pin
  • after 674 ms, it looks like avrdude sends out it’s “0” wakeup character
  • after about 750 ms, the JeeNode starts sending the RFM12demo greeting
  • after 946 ms, the second “0” wakeup goes out
  • after 1197 ms, the third and final “0” goes out

In other words: it looks like avrdude is starting to send the 0’s too late! – and as a result, the JeeNode’s boot loader passes control to the sketch and never enters the upload cycle. After a few seconds, avrdude then gives up:

avrdude: ser_recv(): programmer is not responding

Note that reset and serial communication both work properly, as verified several times.

Trouble is, apart from redoing all in a single app, I see no way to reduce the startup time of avrdude. The SD card is perhaps not the fastest, but it’s no slouch either:

# hdparm -tT /dev/mmcblk0

/dev/mmcblk0:
 Timing cached reads:   248 MB in  2.00 seconds = 123.77 MB/sec
 Timing buffered disk reads:  50 MB in  3.05 seconds =  16.40 MB/sec
#

Is a reset + upload via GPIO not possible? I’m not giving up, but it sure ain’t workin’ yet!

Update – Problem solved, stay tuned for the explanation tomorrow…

Resetting a JeeNode from a RPi

In Hardware, Software on Sep 21, 2012 at 00:01

Now that the JeeNode talks to the Raspberry Pi, it’d be interesting to be able to reset the JeeNode as well, because then we could upload new sketches to it.

It’s not hard. As it so happens, the next pin on the RPi connector we’re using is pin 12, called “GPIO 18″. Let’s use that as a reset pin – and because this setup is going to become a bit more permanent here, I’ve made a little converter board:

DSC 4149

This way, a standard JeeLabs Extension Cable can be used. All we need is a board with two 6-pin female headers, connected almost 1-to-1, except for GND and +5V, which need to be crossed over (the other wire runs on the back of the PCB to avoid shorts).

This takes care of the hardware side of resets. Now the software. This is an example of just how much things are exposed in Linux (once you know where to find all the info).

There’s a direct interface into the kernel drivers called /sys, and this is also where all the GPIO pins can be exposed for direct access via shell commands or programs you write. Let’s have a look at what’s available by default:

$ sudo ls /sys/class/gpio/
export  gpiochip0  unexport
$

The “export” entry lets us expose individual GPIO pins, so the first thing is to make pin 18 available in the /sys area:

sudo echo 18 >/sys/class/gpio/export

That will create a virtual directory called /sys/class/gpio/gpio18/, which has these entries:

$ sudo ls /sys/class/gpio/gpio18/
active_low  direction  edge  power  subsystem  uevent  value
$

All we’ll need is the direction and value of that pin. Let’s first make in an output pin:

sudo echo out >/sys/class/gpio/gpio18/direction

Now, we’re ready to reset the JeeNode. I found out that the pin needs a negative transition (from 1 to 0) to do this, so the following three commands will do the trick:

sudo echo 1 >/sys/class/gpio/gpio18/value
sudo echo 0 >/sys/class/gpio/gpio18/value
sudo echo 1 >/sys/class/gpio/gpio18/value

And sure enough, the JeeNode resets, and the terminal I have running in another window shows the RF12demo startup message again:

Screen Shot 2012 09 18 at 14 32 09

We’re in control – shell over sketch!

Serial hookup JeeNode to Raspberry Pi

In Hardware on Sep 20, 2012 at 00:01

One way to connect an RFM12B to a Raspberry Pi is to simply plug in a JeeLink, using the built-in USB capabilities of the RPi. But that’s a bit of a detour – why go through USB?

Since the JeeNode’s FTDI connector can use 5V power and has TX/RX pins at 3.3V logic level, it’s actually a perfect match for directly connecting to a Raspberry Pi. Let’s do it.

I’ll be using the command shell on the RPi, using a network SSH connection, but this could also be done from the console with a keyboard, of course.

There are a couple of hurdles we’ll need to overcome. First one is to figure out which pins to use on the RPi’s 26-pin I/O connector. I found a good schematic on elinux.org:

Screen Shot 2012 09 16 at 17 26 45

We’re going to use 4 pins: 5V, Ground, TXD, and RXD. But first, let’s figure out how to reach those pins in Linux. I found out that the serial port we need is “ttyAMA0″:

$ ls -l /dev/ttyAMA0 crw-rw—- 1 root tty 204, 64 Sep 16 17:13 /dev/ttyAMA0 $

That port is only accessible by users in access group “tty” (and root). So first, let’s make sure user “pi” can access it, by adding ourselves to that group:

sudo usermod -a -G tty pi

Now logout and log back in to make these changes take effect.

> Note: not all RPi Linux distro’s are set up in the same way. If ttyAMA0’s group is “dialout” instead of “tty”, chances are that you’re already a member (type “id” to find out). In that case, skip the above usermod command.

But that’s not all. By default, there’s a “getty” process running on this serial port:

$ ps ax | grep getty 2126 tty1 Ss+ 0:00 /sbin/getty –noclear 38400 tty1 2127 tty2 Ss+ 0:00 /sbin/getty 38400 tty2 2128 tty3 Ss+ 0:00 /sbin/getty 38400 tty3 2129 tty4 Ss+ 0:00 /sbin/getty 38400 tty4 2130 tty5 Ss+ 0:00 /sbin/getty 38400 tty5 2131 tty6 Ss+ 0:00 /sbin/getty 38400 tty6 2132 ? Ss+ 0:00 /sbin/getty -L ttyAMA0 115200 vt100 2292 pts/0 S+ 0:00 grep getty $

This lets you connect to the serial port and login. Very convenient, but in this case we don’t want to log in, we want to take over control of this serial port for talking to the JeeNode. So we have to disable getty on ttyAMA0:

  1. edit the file /etc/inittab as root (I used “sudo vi /etc/inittab”)
  2. change this line: T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100 to #T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100. I.e. comment it out, and save these changes.
  3. run the command “sudo kill -1 1″ to pick up these inittab changes

And that’s it. There is no longer a process trying to respond to our serial port.

> Note: again, this may not be needed if you don’t see “ttyAMA0″ listed in the ps output.

You also have to make sure that the kernel doesn’t log its console output to this serial port. Look in the file “/boot/cmdline.txt” and remove the text console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 if present. Then reboot.

Now we’re ready for a quick loopback test:

DSC 4143

Connect a single jumper as indicated (a little jumper block would also work), connecting RXD with TXD. This means that everything sent out serially will be sent back and received serially as well. A very convenient test that we’ve got all the Linux stuff set up properly.

Oh, wait – first let’s get the utility installed which lets us type to the serial port:

sudo apt-get install screen

Now we can test the serial port, at last:

$ screen /dev/ttyAMA0 57600 …

You should see a blank screen, and whatever you type in should show up on the screen. If this is indeed the case, then there is data going out and back into the serial port. To really make sure, disconnect the jumper and the echoing will stop. Excellent. Almost there.

Screen is a very convenient utility, but you need to remember how to get back out of it. The key sequence is CTRL+A followed by “\” (the backslash key).

For now, you can leave it running, or start it up again later. The last step is to hook up the JeeNode. This requires 4 wires:

DSC 4144

Note carefully the order of these female-to-female jumper wires, top to bottom:

  • on the RPi: green, white, black, gap, blue
  • on the JeeNode: gap, green, white, blue, gap, black

I used a JeeNode, pre-loaded with the standard RFM12B sketch, and set to receive packets from my main home monitoring setup here at JeeLabs. I also enabled “collect mode (“1c”) so that it wouldn’t try to acknowledge packets, just lurking and reporting what comes in. And sure enough, it works:

Screen Shot 2012 09 16 at 17 17 17

Easy! (once you know how to overcome all the software and hardware hurdles, that is…)

Update – additional contributed notes.

Laser cutter electronics

In Hardware, Software on Sep 19, 2012 at 00:01

The last part of this mini series about a low-cost semi-DIY laser cutter describes the electronics and firmware:

DSC 3506

In the middle is an MBED microcontroller based on an ARM Cortex M3 chip (NXP’s LPC1768). It runs at 96 MHz, has 512 KB flash, 32 KB RAM, USB, and an Ethernet controller on board (but not the magjack).

The whole thing sits on the custom LaOS board, which includes an SD card socket, an I2C bus, some opto-isolators, power-supply interface (+5V and +24V), and two Pololu stepper drivers (or nearly compatible StepSticks).

There’s room for 1 or 2 more stepper drivers, a CAN bus interface, and more connectors for extra opto-isolated inputs and outputs. The on-board steppers can be omitted with the step/direction pins brought out if you need to drive more powerful motors.

The MBED was briefly mentioned in a previous post, and can also be replaced by a suitably modded LPCXpresso 1769 board, at less than half the price.

The software is open source and has just been moved from the MBED site to GitHub. Note that at this point in time, the software is still based on the “mbed.ar” runtime support library, which is unforunately not open source. Work is in progress to move to a fully open source “stack”, but that’s not the case today – the Ethernet library in particular hasn’t been successfully detached from its MBED context yet.

Ethernet connectivity is based on the lwIP code, which in turn is the big brother of uIP. Big in the sense that this supports a far more capable set of TCP/IP features than would be possible with an 8-bit microcontroller and its limited memory. Having 512 KB flash and 32 KB RAM in this context, means that you don’t have to fight the constraints of the platform and can simply focus on getting all the functionality you want in there.

Right now, the LaOS firmware drives the steppers, using a Gcode interpreter adapted from gbrl, and includes support for Ethernet (TFTP, I believe) and the SD card. It also requires the I2C control panel. As a result, you can send a “job” to this thing via VisiCut, and it’ll save it on the SD card. The I2C-based control panel then lets you pick a job and start it. Quite a good workflow already, although there are still a fair number of rough edges.

(Note that if you listen very carefully, you can hear all the pioneers on this project scream for more volunteers and more help, on all sorts of levels and domains of expertise :)

What excites me about all this, apart from those über-cool laser cutting capabilities of course, is the potential to take this further since all the essential bits are now open source – and it’s not even really tied to a specific brand of laser.

So there you have it. It cuts, it burns, it smells, it’s yearning to be taken to the next level :)

What’s in a laser cutter

In Hardware on Sep 18, 2012 at 00:01

Let me describe this thing I ended up with:

  • mechanics: the main part is a solid bright red metal box with a few compartments:
    1. left = X-Y table
    2. right = electronics
    3. back = laser tube
  • electronics: the LaOS main board and an ATmega168 as I2C-connected control panel
  • water reservoir + circulation pump, for cooling, must be on when the laser is on
  • air pump (noisy aquarium type) – for “air assist”, keeps the fumes away from the lens
  • exhaust ventilator, mounted on the back, pushes the smelly & smoky air out

The pumps and ventilator are manually turned on from the front panel with separate switches. Not perfect, since this leaves room or operator error, but hey – it works.

Here’s a peek inside, with some packaging plastic still in place:

DSC 3512

The shiny plate height can be adjusted using 4 connected screws turning in tandem.

You can see a little fluorescent light in the top center, and the air exhaust underneath it.

A 35 Watt infrared laser is serious stuff (it actually requires a few hundred Watt to generate that sort of power). Once focused, that beam can do major harm – cutting through stuff is what it’s supposed to do, after all.

Safety comes in the form of a reed relay which triggers when the lid of this thing is lifted (top right above), another one when the lid of the laser on the back is open, and a mains power switch with a key. The lid for the electronics is locked (from the X-Y compartment). The transparent viewing area is of a special type which blocks laser light, and the whole thing is made of fairly solid steel.

The beam is invisible (scary, eh?), but a tiny red “pointer” laser is mounted inside, showing roughly where the beam will hit. Extremely useful while doing dry runs – which in turn is very easy to do: just start the laser with the lid open, and you can see where it’s going to cut. Given that the cutting area is only about 20×30 cm, that’s not a luxury – you really have to check whether the material is properly placed. Here’s that last mirror, deflecting the beam down into the final focusing lens:

DSC 3489

(Note: that’s not smoke, but the red panel’s reflection on the aluminium work surface)

The hollow tube is the “air assist”, blowing air to push the smoke away from the beam.

All the mirrors come pre-aligned and secured with a bit of hot glue. No need to tweak.

On the side is that little pointer laser. Since it’s tilted, the position of the spot is not exactly where the laser will hit, depending on how far into the material you place the focus spot. Focusing is actually quite simple: the laser comes with a little (lasered) acrylic piece, the side of which has a specific length. To focus, you place that on the work piece, and then lower or raise the object until the plastic spacer aligns with this metal mirror mount.

Raising / lowering the work piece is done manually. The whole thing sits on a (fixed size) “honeycomb” bed, which in turns sits on a manually adjustable metal “table”. Adjustment is done with a screw sticking through the bottom of the laser – and in fact the very first thing you need to cut is a piece of wood to act as large adjustment ring, which can then be grabbed from the front of the laser. Bit hard to explain, but then again this isn’t meant as assembly instruction – I just want to give you an impression of what sort of issues you have to deal with in such a setup. On the plus side: pioneering is fun! – with lots of opportunities to come up with clever improvements :)

Tomorrow, I’ll describe the electronics. This board (and the software developed for it) replaces the original board, which I’m told was hard to use, came with crude Windows-specific software, and was impossible to hack on and improve. The LaOS board has a microntroller, two stepper motor drivers, an Ethernet port, and various other bits and bobs needed to deal with everything in the HPC laser. It’s actually quite general-purpose.

Hello, Laser Cutter!

In Hardware, News on Sep 17, 2012 at 00:01

Yep, it has finally happened… it all started in July, when I got this (without the electronics board) and this (called the LaOS board).

The laser arrived like this:

DSC0025

This summer, a couple of early adopters in the Netherlands got together to figure out all the pesky little details that come up when you’re really just in pioneering mode. Make no mistake: this thing is far from ready for mainstream use. The laser itself is quite nice and ready to go, and definitely workable as far as all the mechanics go. But the electronics and software are still work-in-progress (I’m using the VisiCut software – which includes a driver that talks directly to the laser’s firmware over Ethernet).

Nevertheless – early as it may be, the total cost is less than €1,500 and you end up with an A4-sized laserable workspace which can cut up to 5 mm wood panels and 6 mm acrylic (engraving is more involved, but getting there). One of the first things we tried was this:

Image 1

Sure enough, the circle is a snug fit and turns perfectly. Excellent alignment!

I’ll describe a few more details of this setup in the coming weblog posts, but also want to point out that you too can end up with such a laser cutter (just make sure to arrange for ventilation – you’ll quickly get very tired of the burning smell and fumes).

There’s a project by the designers of the replacement electronics, called LaOS (Laser Open Source) – and it’s definitely the best place to go right now if you want to find out what’s going on. Warning: the site is currently undergoing a messy transition to a new wiki – I’ve helped out a bit and am sure they’d love to see more people join in the effort of making this thing more practical for the non-hacker crowd.

One little gotcha: these 35 W laser cutters are produced in China and then tested/resold by a company in the UK, and they are really large and heavy. Having one shipped from the UK to you is fairly expensive, because of the delicate glass laser tube (several hundred Euro, most likely). We got around that by getting organised and doing a “group buy”, with one person actually volunteering to go to the UK, load his car up with a bunch of laser cutters, and driving back (!). Still pricey, but less so, and I think the UK vendor is in fact willing to make arrangements when enough units are being purchased and shipped at the same time. Anyway – it’s an aspect to keep in mind.

But oy, oy, oy, this personal fabbing is fun :)

One million packets

In AVR, Hardware, Software on Sep 15, 2012 at 00:01

Minutes after this weblog post goes live will be a new milestone for one of the JeeNodes.

This thing has been running for over two years, sending out nearly one million test packets:

Here are the entries from the data logged to file on my central server, minutes ago:

1:40   RF12-868.5.3 radioBlip age       740
1:40   RF12-868.5.3 radioBlip ping      999970

The counter is about to reach 1,000,000 – just after midnight today, in fact.

These log entries come from a JeeNode with a radioBlip sketch which just sends out a counter, roughly every 64 seconds, and goes into maximum low-power mode in between each transmission. That’s the whole trick to achieving very long battery lifetimes: do what ya’ gotta do as quickly as possible, then go go bck to ultra-low power as deeply as possible.

The battery is a 1300 mAh LiPo battery, made for some Fujitsu camera. I picked it because of the nice match with the JeeNode footprint.

Bit the big news is that this battery has not been recharged since August 21st, 2010!

Which goes to show that:

  • lithium batteries can hold a lot of charge, for a long time
  • JeeNodes can survive a long time, when programmed in the right way
  • sending out a quick packet does not really take much energy – on average!
  • all of this can easily be replicated, the design and the code are fully open source

And it also clearly shows that this sort of lifetime testing is really not very practical – you have to wait over two years before being sure that the design is as ultra-low power as it wast intended to be!

If we (somewhat arbitrarily) assume that the battery is nearly empty now, then running for 740 days (i.e. 17,760 hours) means that the average current draw is about 73 µA, including the battery’s self-discharge. Which – come to think of it – isn’t even that low. I suspect that with today’s knowledge, I could probably set up a node which runs at least 5 years on this kind of battery. Oh well, there’s not much point trying to actually prove it in real time…

One of the omissions in the original radioBlip code was that only a counter is being sent out, but no indication at all of the remaining battery charge. So right now I have no idea how much longer this setup will last.

As you may recall, I implemented a more elaborate radioBlip2 sketch a while ago. It reports two additional values: the voltage just before and after sending out a packet over wireless. This gives an indication of the remaining charge and also gives some idea how much effect all those brief transmission power blips have on the battery voltage. This matters, because in the end a node is very likely to die during a packet transmission, while the radio module drains the battery to such a point that the circuit ceases to work properly.

Next time, as a more practical way of testing, I’ll probably increase the packet rate to once every second – reducing the test period by a factor of 60 over real-world use.

Waiting a couple of years for the outcome is a bit silly, after all…

Another embedded ecosystem

In Hardware on Sep 14, 2012 at 00:01

(This post follows up on Reinhard’s clearvoyant comment yesterday..)

The ARM microcontrollers described in the past few days are a big step up from a “simple” ATmega328, but that’s only if you consider hundreds of kilobytes of flash storage and tens of kilobytes of RAM as being “a lot”.

Compared to notebooks and workstations, it’s still virtually nothing, of course.

But there’s another trend going on, with bang-for-the-buck going off the charts nowadays: small embedded Linux systems with integrated wired and/or wireless Ethernet. These are often based on Broadcom and Atheros chipsets – the same as found in just about every network router and gateway nowadays.

One particularly nice and low-cost example of this is the Carambola by 8devices:

Main image 3 40

It has 8 MB flash + 32 MB RAM (megabytes!), on-board WiFi, and runs OpenWrt Linux.

There are I2C and SPI interfaces, which can also be used as general-purpose I/O pins, so this thing will interface to a range of things right out of the box.

One gotcha is that the 2×20 pins are on a 2mm grid, not 0.1″. Small size has its trade-offs!

The board will draw up to 1.5 W @ 3.3V (i.e. roughly 500 mA), but that can easily be reduced to about 0.4 W for a blank board with no wired Ethernet attached.

Here are some more specs, obtained from within Linux on the Carambola itself:

Screen Shot 2012 09 13 at 21 02 59

As you can see, this unit (like many routers) is based on a MIPS architecture. And it’s actually quite a bit faster that the Bifferboard I described a while back.

Like most low-end ARM chips, these systems often lack hardware floating point (its all implemented in software, just like an Arduino does for the ATmega’s). Don’t expect any number-crunching performance from these little boards, but again it’s good to point out that boards like these are priced about the same as an Arduino Uno.

One of the benefits of Linux is that it’s a full-fledged operating system, with numerous tools and utilities (though you often still need to cross-compile) and with solid full-featured networking built in. The amount of open source software available for Linux (on a wide range of hardware) is absolutely staggering.

Among the drawbacks of Linux in the context of Physical Computing, is that it’s not strictly real time, so programming for it follows a different approach (busy loops for timing are not done, for example). Don’t expect to accurately pulse an I/O pin at a few hundred Hz or more, for example. Linux was also definitely not made for ultra-low power use, such as in remote wireless nodes which you’d like to keep up and running for months or years on a single battery – there’s simply too much going on in a complete operating system.

The other thing about Linux is that it can be somewhat intimidating if you’ve never used it before. Part of this comes from its strong heritage from the “Unix world”. But given the current trends, I strongly recommend trying it out and getting familiar with it – Linux is very mature: it has been around for a while and will remain so for a long time to come. With boards such as the Carambola illustrating just how cheap it can be to have a go at it.

Interesting times. Now if only new software developments would keep up with all this!

The ARM ecosystem

In Hardware, Software on Sep 13, 2012 at 00:01

Yesterday’s post presented an example of a simple yet quite powerful platform for “The Internet Of Things” (let’s just call it simple and practical interfacing, ok?). Lots of uses for that in and around the house, especially in the low-cost end of ATmega’s, basic Ethernet, and basic wireless communication.

What I wanted to point out with yesterday’s example, is that there is quite a bit of missed potential when we stay in the 8-bit AVR / Arduino world. There are ARM chips which are a least as powerful, at least as energy-efficient, and at least as low-cost as the ATmega328. Which is not surprising when you consider that ARM is a design, licensed to numerous vendors, who all differentiate their products in numerous interesting ways.

In theory, the beauty of this is that they all speak the same machine language, and that code is therefore extremely portable between different chips and vendors (apart from the inevitable hardware/driver differences). You only need one compiler to generate code for any of these ARM processor families:

arm2 arm250 arm3 arm6 arm60 arm600 arm610 arm620 arm7 arm7m arm7d arm7dm arm7di arm7dmi arm70 arm700 arm700i arm710 arm710c arm7100 arm720 arm7500 arm7500fe arm7tdmi arm7tdmi-s arm710t arm720t arm740t strongarm strongarm110 strongarm1100 strongarm1110 arm8 arm810 arm9 arm9e arm920 arm920t arm922t arm946e-s arm966e-s arm968e-s arm926ej-s arm940t arm9tdmi arm10tdmi arm1020t arm1026ej-s arm10e arm1020e arm1022e arm1136j-s arm1136jf-s mpcore mpcorenovfp arm1156t2-s arm1156t2f-s arm1176jz-s arm1176jzf-s cortex-a5 cortex-a7 cortex-a8 cortex-a9 cortex-a15 cortex-r4 cortex-r4f cortex-r5 cortex-m4 cortex-m3 cortex-m1 cortex-m0 cortex-m0plus xscale iwmmxt iwmmxt2 ep9312 fa526 fa626 fa606te fa626te fmp626 fa726te

In practice, things are a bit trickier, if we insist on a compiler “toolchain” which is open source, with stable releases for Windows, Mac, and Linux. Note that a toolchain is a lot more than a C/C++ compiler + linker. It’s also a calling convention, a run-time library choice, a mechanism to upload code, and a mechanism to debug that code (even if that means merely seeing printf output).

In the MBED world, the toolchain is in the cloud. It’s not open source, and neither is the run-time library. Practical, yes – introspectable, not all the way. Got a problem with the compiler (or more likely the runtime)? You’re hosed. But even if it works perfectly – ya can’t peek under the hood and learn everything, which in my view is at least as important in a tinkering / hacking / repurposing world.

Outside the MBED world, I have found my brief exploration a grim one: commercial compiler toolchains with “limited free” options, and proprietary run-time libraries everywhere. Not my cup of tea – and besides, in my view gcc/g++ is really the only game in town nowadays. It’s mature, it’s well supported, it’s progressing, and it runs everywhere. Want a cross compiler which runs on platform A to generate code for platform B? Can do, for just about any A and B – though building such a beast is not necessarily easy!

As an experiment, I wanted to try out a much lower-cost yet pin-compatible alternative for the MBED, called the LCPXpresso (who comes up with names like that?):

MFG EA XPR 003

Same cost as an Arduino, but… 512 KB flash, 64 KB RAM, USB, Ethernet, and tons of digital + analog I/O features.

Except: half of that board is dedicated to acting as an upload/debug interface, and it’s all proprietary. You have to use their IDE, with “lock-in” written on every page. Amazing, considering that the ARM chip can do serial uploading via built-in ROM! (i.e. it doesn’t even have to be pre-flashed with a boot loader)

As an experiment, I decided to break free from that straight-jacket:

DSC 3832

Yes, that’s right: you can basically throw away half the board, and then add a few wires and buttons to create a standard FTDI interface, ready to use with a BUB or other 3.3V serial interface.

(there’s also a small regulator mod, because the on-board 3.3V regulator seems to have died on me)

The result is a board which is pin-compatible with the MBED, and will run more or less the same code (it has only 1 user-controllable LED instead of 4, but that’s about it, I think). Oh, and serial upload, not USB anymore.

Does this make sense? Not really, if that means having to manually patch such boards each time you need one. But again, keep in mind that the boards cost the same as an Arduino Uno, yet offers far more than even the Arduino Mega in features and performance.

The other thing about this is that you’re completely on your own w.r.t. compiling and debugging code. Well, not quite: there’s a gcc4mbed by Adam Green, with pre-built x86 binaries for Windows, Mac, and Linux. But out of the box, I haven’t found anything like the Arduino IDE, with GUI buttons to push, lots of code examples, a reference website, and a community to connect with.

For me, personally, that’s not a show stopper (“real programmers prefer the command line”, as they say). But getting a LED to blink from scratch was quite a steep entry point into this ARM world. Did I miss something?

Two more notes:

  • Yes, I know there’s the Maple IDE by LeafLabs, but I couldn’t get it to upload on my MacBook Air notebook, nor get a response to questions about this on the forum.

  • No, I’m not “abandoning” the Atmel ATmega/ATtiny world. For many projects, simple ways to get wireless and battery-operated nodes going, I still vastly prefer the JeeNode over any other option out there (in fact, I’m currently re-working the JeeNode Micro, to add a bit more functionality to it).

But its good to stray outside the familiar path once in a while, so I’ll continue to sniff around in that big ARM Cortex world out there. Even if the software exploration side is acting surprisingly hostile to me right now.

Interesting gateway

In Hardware on Sep 12, 2012 at 00:01

A while back, I came across this product, called the “mbed Internet of Things Gateway”:

Gateway

It’s an ARM microcontroller with an Ethernet port, a µSD storage slot, and an RFM12B wireless transceiver. Very nicely packaged in an extruded-aluminium case with laser-cut front and back panels. Here’s what’s inside:

DSC 3833

Not that much circuitry, as you can see – because all the heavy-lifting is done by the MBED board on the left.

That’s a 32-bit microcontroller, with built-in Ethernet and USB, plenty of I/O pins, and lots of features to connect to SPI, I2C, CAN, and other types of devices. Not to mention the 512 KB flash and 32 KB RAM memory – plenty to implement some serious functionality.

MBED comes with an intriguing “cloud-based” compiler and build environment, which is surprisingly effective. Here’s how it works, out of the box:

  1. plug the MBED into USB and it’ll present itself as a memory disk with one HTML file on it
  2. double-click that file to go to the MBED web site
  3. you get a web-based equivalent of a standard Windows IDE, plus a large code sharing community
  4. create your project online, enter your own code, and hit the compile button
  5. if the code compiles successfully, you end up with a file in your download folder
  6. copy that file to the MBED’s USB drive
  7. press on the MBED’s reset button, and that’s it … uploaded and running!

This is a very elegant workflow. No need to install any software to develop for MBED. And you can continue work wherever you are, as long as internet works and you have your MBED with you. You do need to sign up and register a (free) account on that MBED site – in return, they’ll do all the compiles for you.

This board is an exciting development. The cost is higher than with just a JeeNode + EtherCard, but there is also a lot more possible when you don’t have to fight the ATmega328’s strict flash and RAM memory constraints.

I’ll have more to say about this hardware and software tomorrow – stay tuned…

Delayed power-up with P-MOSFETs

In Hardware on Sep 11, 2012 at 00:01

This is a follow-up to the Delayed power-up post, this time using some P-MOSFETs (in SOT-23 SMD form, i.e. tiny). The way I’m testing these, is by using a 1 kΩ resistor as simulated load, and hooking things up as follows:

JC s Grid page 32

These components were not selected for this purpose, in fact, I picked units with a very low switching threshold voltage, so that they can reliably be switched on from an I/O pin, even if we were to run at just 1.8V.

Here are the characteristics of the Philips BSH203 P-MOSFET:

Screen Shot 2012 09 10 at 13 06 34

Just over 1 Ω resistance when driven low by 1.8V, so with a 50 mA load, the voltage drop over this MOSFET will be just over 50 mV.

When placed in the Component Tester, and zooming in on the interesting bit, we get:

SCR11

Each major horizontal division is 2V, so this thing switches on at about 0.5V.

For comparison, the characteristics of the Vishay SI2333 P-MOSFET:

Screen Shot 2012 09 10 at 13 13 27

And in this case, the Component Tester shows this (sorry, can’t zoom in with this setup):

SCR12

A slightly higher turn-on voltage, but note that the ON resistance is considerably lower at 1.8V: only 0.05 Ω. Not surprising, when you consider that this MOSFET can probably switch over 5 A (without self-destructing from the heat dissipation).

Here’s what these tiny components look like, with wires soldered on for “debugging”:

DSC 3828

Looks like either of these will do the trick, when switched from an I/O pin anyway.

Function generator weirdness

In Hardware on Sep 10, 2012 at 00:01

Fighting my lab instruments… not good :(

The TG2511 Arbitrary Waveform Generator in my lab is very flexible, and does all the usual things one would expect of a modern signal generator, i.e. setting the shape, frequency, and amplitude of its output signal.

But there’s some weirdness w.r.t. the amplitude. The built-in impedance is quoted as being 50 Ω, no doubt the reasoning being that if you terminate the cable with 50 Ω as well, then a standard coax cable will have the least possible signal degradation (ringing, reflections, and such).

There is a setting to adjust for the assumed load, so that the instrument can adjust its amplitude accordingly. The default is to assume a 50 Ω load at the end of the cable:

DSC 3826

But this is where I get mightily confused. Here’s what I see with the scope set in high impedance mode:

SCR07

That in itself is actually correct: the output amplitude is twice the expected value, since there is no 50 Ω terminating resistor. So let’s add it in (it’s an option inside the scope):

SCR08

Huh? – Why isn’t the amplitude 3 Vpp, and ends up being only half that value?

But there’s something even stranger, and far more inconvenient about the TG2511. After a few minutes, I often get a message about the output signal being overloaded:

DSC 3827

Doesn’t make sense. I’m never loading the output with more than 50 Ω, i.e. well within specs. Sometimes this happens even when I completely disconnect the load. Even more suspect: the green “OUTPUT” doesn’t always match what’s happening. Sometimes the light is off, yet the output signal is still present!

In fact, I get this screen in the most unexpected situations. Maybe the TG2511’s output stage is broken? Yuck.

I have contacted the supplier for advice.

Delayed power-up

In AVR, Hardware on Sep 9, 2012 at 00:01

To recall yesterday’s reasoning, I’m looking for a way to keep the RFM12B from starting up too soon and drawing 0.6 mA before the microcontroller gets a chance to enable it’s ultra-low power sleep mode.

The solutions so far require an extra I/O pin, allowing the microntroller to turn power on and off as needed, with the extra detail that power stays off until told otherwise.

But all I’m really interested in, is to keep that RFM12B from powering up too soon. After that, I never need to power it down again (and lose its settings) – at 0.3 µA, the RFM12B’s sleep mode will be just fine.

One solution is to use a dedicated chip for this, which can reliably send out a trigger when a fixed voltage threshold has been exceeded. That would still need a MOSFET, though, so this increases the cost (and footprint) of such a solution.

The other way would be to create a low-speed RC network, gradually charging a cap until a threshold is reached and turns on the MOSFET switch. Lower cost, no doubt, but in fact not flexible enough in case of a very slow power-on voltage ramp, as in the case of a solar cell charging a supercap or small battery. There is just no way to determine how long the delay needs to be – it might take days for the power rail to reach a usable level!

Yet another option is this little gem (thanks for the initial suggestion, Martyn!):

JC s Grid page 32

No I/O pin, no pull-up, nothing!

This trick takes advantage of what was originally considered a drawback of MOSFET switching: the fact that the gate voltage has to reach a certain level before the MOSFET will switch. Assuming that voltage is say 1.5V, then the MOSFET will be turned off as long as the power rail has not yet reached 1.5V, and once it rises above that value, it’ll automatically switch on. Magic!

Does it work? Well, I’m still waiting for some P-MOSFETs to arrive, but I’ve done a little test with an N-MOSFET, connected the other way around and using a 1 kΩ resistor as load. We can look at that combination as a component which has only two pins: a power rail and ground.

If the circuit works as expected, then when applying an increasing voltage, no current will flow until the threshold has been reached, and then it’ll switch on and start drawing current.

As it turns out, this is very easily observable using a Component Tester – like the one built into my scope:

SCR06

The horizontal scale is the applied voltage (from about -5V to +5V), the vertical scale is the current through that component (from about -5 mA to +5 mA). The straight slanted line is characteristic of a 1 kΩ resistor.

But the interesting bit is that little dent: from under 0V to about 1.5V, the circuit draws no current at all. Once 1.5V or more are applied, the circuit starts conducting, and behaving like a plain 1 kΩ resistor again.

Woohoo, this might actually work: just a single P-MOSFET would be all that’s needed!

Switching with a P-MOSFET

In AVR, Hardware on Sep 8, 2012 at 00:01

One reason for yesterday’s exploration, is to figure out a way around a flaw of the RFM12B wireless radio module.

Let me explain – the RFM12B module has a clock output, which can be used to drive a microcontroller. The idea being that you can save a crystal that way. Trouble is that this clock signal has to be present on power-up, even though it can be configured over SPI in software, because otherwise the microcontroller would never start running and hence never get a chance to re-configure the radio. A nasty case of Catch 22 (or a design error?).

In short: the radio always powers up with the crystal oscillator enabled. Even when not using that clock signal!

The problem is that an RFM12B draws about 0.6 mA in this mode, even though it can be put to sleep to draw only 0.3 µA (once running and listening to SPI commands). In the case of energy harvesting, where you normally get very tiny amounts of energy to run off, this startup hurdle can be a major stumbling block.

See my low-power supply weblog post about how hard that can be, and may need extra hardware to get fixed.

So I’m trying to find a way to keep that radio powered down until the microcontroller is running, allowing it to be put to sleep right away.

For ultra-low power use, yesterday’s PNP transistor approach is not really good enough.

This is where an interesting aspect of MOSFETs comes in: they make great power switches, because all they need is a gate voltage to turn them on or off. When on, their resistance (and hence voltage drop) is near zero, and the voltage on the gate doesn’t draw any current. Just like a water faucet doesn’t consume energy to keep water running or blocked, only to change the state – so do MOSFETs.

But many MOSFETs typically require several volts to turn them on, which we may or may not have when running at the lower limit of 1.8V of an ATmega or ATtiny. So the choice of MOSFET matters.

Just like yesterday, we’ll need a P-channel MOSFET to let us switch the power supply rail:

JC s Grid page 32

Note the subtly different placement of the resistor. With a PNP transistor, it was needed to limit the current through the base (which then got wasted, but that current is needed to make the transistor switch). With a MOSFET there is no current, but now we need to make sure that the MOSFET stays off until a low voltage is applied.

Except that now R can be very large. It’s basically a pull-up, and can be extremely weak, say 10 MΩ. That means that when pulled low, the leakage current will be only 0.3 µA.

The trick is to find a P-MOSFET type which can switch using a very low gate voltage, so that it can still be fully switched on. I’ve ordered a couple of types to test this out, and will report once they arrive and measurements can be made.

All in all, this is a very nice solution, though – just 2 very simple components. The main drawback is that we still need to reserve an I/O pin for this.

Tomorrow, I’ll explore a refinement which does not even need an extra I/O pin.

Switching with a PNP transistor

In Hardware on Sep 7, 2012 at 00:01

This is an exploration to find out what circuit can be used to switch small electronic loads using a digital I/O pin.

The simplest solution by far, is to use the I/O pin to directly drive the circuit. This works great for low currents, such as an LED with series resistor. But there are limits to how much current you can draw:

Screen Shot 2012 09 06 at 22 49 12

As you can see, from the datasheet, drawing 5 mA will already cause a voltage drop of about 0.2V, so the load will not get the full supply voltage. With larger loads, the drop becomes even more pronounced.

Another approach is to use a PNP transistor, as follows:

PNP drop

Here’s how it works, in case you’re not familiar with them PNP transistor thingies:

  • pulling the input pin down towards 0V, will turn the PNP transistor on
  • when on, the transistor will conduct and supply power to the load
  • leaving the pin floating or pulling it up, will cause the PNP transistor to turn off

In my setup, I’m using a very light load for now. The following measurements will be different as the load increases, but not as substantially as with the raw I/O pin drive. A circuit like this could easily drive a 100..250 mA load, if the base resistor has the right value – as we’ll see.

Time to try this out. I am quite interested in how the voltage drop over the transistor depends on the exact voltage placed on the base junction. Or rather: how much current I’ll need (since the resistor passes a known current once we know the voltage drop.

So as input, I’m using a 10 Hz sawtooth signal, which varies from 0 to 3V. Due to the way things are hooked up, it starts at 3V below the 3.3V power rail, i.e. 0.3V, and then rises to the level of the power rail.

Here are the results with a 10 kΩ resistor – both signals have been inverted, as I’m measuring relative to +3.3V:

SCR01

(oops, ignore the yellow trigger point baseline)

At the start, the transistor is turned on strongly, and then the input voltage falls to zero (yellow trace). As you can see, the voltage drop over the transistor increases non-linearly as it gradually turns off. With only 1V driving it, the voltage drop increases from about 40 mV to 100 mV, i.e. 0.1V. With even less, it starts to switch off and gets the full power supply voltage (so nothing reaches the load).

Now let’s do some math. I used my transistor tester to determine that this particular BC557 PNP transistor had 0.8V drop over its base-to-emitter junction, and that its current amplification factor (hFE) is about 220x.

In other words: with 1.0V on the input, there is 1.0-0.8 = 0.2V on the 10 kΩ resistor. Ohm’s law (E = I x R, or I = E / R) implies that the current through the resistor will be 0.2V / 10kΩ = 20 µA. This current is essentially “wasted”, but given the 220 factor, it will allow the transistor to drive up to 20 µA x 220 = 4.4 mA. Not so great…

Update – not sure what I was smoking at the time I wrote the above paragraph. That’s 1.0V below VCC, roughly the switching threshold of this transistor when used with a 1 kΩ load. I’m not sure what point I was trying to make here, other than that a 20 µA base current is not enough to switch an RFM12B.

But if we pull the input to almost ground level, as would be the case with a digital I/O pin, then the base current increases to (3.3 – 0.8) / 10,000 = 250 µA, supporting a load of up to 250 µA x 220 = 55 mA.

If power waste is not an issue, we could reduce the base resistor to 1 kΩ, and get over 500 mA load switching capability (assuming the transistor is powerful enough). The base current will then be around 2.5 mA, a value which an ATmega I/O pin can still easily supply.

But what if power use is important, i.e. if we can’t afford to waste those 20 µA or more?

Here’s the same circuit, with a 100 kΩ resistor instead:

SCR03

Note how the emitter-to-collector voltage drop (blue line) rises. With 3V input differential, i.e. almost pulled to ground, the drop over the transistor is still under 0.15V, but we’ll need to keep the input voltage at least 1.5V below the power supply voltage to make this work. So in very low-voltage / low-power scenario’s (i.e. running off two almost-depleted AA cells), this might become tricky.

The current losses are now only 1/10th, i.e. 25 µA when the power supply is 3.3V and the input is tied to ground. Then again, in the ultra-low power world that wasted 25 µA is not really such an impressive figure.

Still, for switching loads which draw up to a few hundred milliamps, this circuit using just a PNP transistor and a resistor is really quite practical. If you use a 1 kΩ resistor, the base current will be well with the I/O pin’s capabilities, and the transistor will usually have enough drive to switch its load.

The only other drawback is that the transistor will always add a small voltage drop of perhaps 50 .. 200 mV.

There is a third solution using MOSFETs, with its own set of trade-offs. To be continued…

Current clamp

In Hardware on Sep 5, 2012 at 00:01

To continue where I left off before the summer, let’s examine what a current clamp like this one does:

DSC 3354

You put it around a single wire in your AC mains cabling and it’ll generate a voltage proportional with the current going through it. This unit has a built-in burden resistor, which means you get a ± 1V (AC!) output when the current through the wire is 30 A. So let’s have some fun and look at a couple of different loads, eh?

Let’s start off with an old-fashioned 25W incandescent light-bulb, which is a resistive load:

SCR28

Note the vertical scale – these voltage levels are tiny. The scope caclulates the Root Mean Square (RMS) voltage as being 3.52 mV in this case. That’s the voltage you’d need to draw as direct current to dissipate the same amount of power as this alternating current (let’s ignore phase shift and “reactive” vs “true” power for now).

Sure enough, a 75W light bulb draws three times as much power (note the different vertical scale):

SCR29

Here’s a 2W LED light bulb, which uses an electronic circuit to pulse small amounts of energy from AC mains:

SCR30

Again, note how this minute RMS reading corresponds quite accurately to the specified wattage.

Now let’s take a vacuum cleaner, which is an inductive load, and quite a lot beefier too:

SCR31

The “blips” are switching artifacts from the TRIAC control included in this unit. From the RMS value, my estimate would be that it draws about 1500W. Here’s the same vacuum cleaner, with its power throttled back to minimum:

SCR32

As with the LED light, you can see the electronics kicking in and pulsing AC mains to throttle power back to around 500W.

Conclusion: a current clamp is a safe way to measure current in an AC mains wire, and it more or less reproduces the measured current as a small output voltage. Very small in fact, for light loads. To accurately determine the RMS value of a load as small as our 2W LED light, we’re going to have to read out this signal in the sub-millivolt range, and do so at perhaps 1000 HZ to collect enough readings per 50 Hz cycle.

Tizio LED transplant

In Hardware on Sep 4, 2012 at 00:01

For some time now, there have been two of these Tizio lamps in the house. A gorgeous design and very practical:

DSC 3517

As so many lamps from last century, they come with a halogen incandescent light bulb:

DSC 3507

Lifetimes are great (I don’t think I ever replaced one), but efficiency less so. So I decided to replace them anyway:

DSC 3509

These are simple 1.2W warm-white LED lights with built-in rectifier and current limiting resistors. Here’s the result:

DSC 3508

The transplant ended up being very simple, the UV filter glass is no longer needed, the power consumption has dropped from 50W 35W to 12W 5W, and – if all is well – these LEDs will never need to be replaced again.

Easy peasy! Now if only all our incandescent lights had equally simple alternatives…

New HYT131 sensor

In Hardware, Software on Jun 30, 2012 at 00:01

The SHT11 sensor used on the room board is a bit pricey, and the bulk source I used in the past no longer offers them. The good news is that there’s a HYT131 sensor with the same accuracy and range. And the same pinout:

DSC 3353

This sensor will be included in all Room Board kits from now on.

It requires a different bit of software to read out, but the good news is that this is now standard I2C and that the code no longer needs to do all sorts of floating point calculations. Here’s a test sketch I wrote to access it:

Screen Shot 2012 06 30 at 00 23 28

And here’s some sample output (measurements increase when I touch the sensor):

Screen Shot 2012 06 28 at 15 39 55

As you can see, this reports both temperature and humidity with 0.1 resolution. The output gets converted to a float for display purposes, but apart from that no floating point code is needed to use this sensor. This means that the HYT131 sensor is also much better suited for use with the memory-limited JeeNode Micro.

It’ll take a little extra work to integrate this into the roomNode sketch, but as far as I’m concerned that’ll have to wait until after the summer break. Which – as far as this weblog goes – will start tomorrow.

One more post tomorrow, and then we “Northern Hemispherians” all get to play outside for a change :)

Update – I’ve uploaded the datasheet here.

Assembling the EmonTX

In Hardware on Jun 29, 2012 at 00:01

The guys at OpenEnergyMonitorhi Glyn and Trystan! – have been working on a number of open source energy monitoring kits for some time now. With solar panels coming here soon, I thought it’d be nice to try out their EmonTX unit – which is partly derived from a bunch of stuff here at JeeLabs. Here’s the kit I got recently:

DSC 3351

Following these excellent instructions, assembly was a snap (I added the 868 MHz RFM12B wireless module):

DSC 3352

Whee, assembling kits is fun! :)

I had some 30A current clamps from SeeedStudio lying around anyway, so that’s what I’ll be using.

The transformer is a 9 VAC type, to help the system detect zero crossings, so that real power factors can be calculated. Unfortunately, this transformer doesn’t (yet) power the system (but it now looks like it might in a future version), so this thing also needs either FTDI or USB to power it.

Here are my first updated measurement results, using the voltage_and_current.ino sample sketch in EmonLib:

    0.27 4.17 260.39 0.02 0.06 
    -0.02 0.71 260.77 0.00 -0.03 
    0.03 0.71 260.74 0.00 0.04 
    -0.02 0.71 260.56 0.00 -0.03 
    0.02 0.71 260.63 0.00 0.03 
    -100.93 105.81 260.88 0.41 -0.95 
    -97.68 102.16 260.94 0.39 -0.96 
    -99.07 104.42 260.98 0.40 -0.95 
    -97.15 102.57 260.74 0.39 -0.95 
    -97.69 102.29 260.91 0.39 -0.95 

The values printed out are:

  • realPower
  • apparentPower
  • Vrms
  • Irms
  • powerFactor

These readings were made with a clamp on one wire of a 25W lightbulb load – first off, then on. The mains voltage estimated from the 9V transformer is a bit high – it’s usually about 230V around here. My plan is to measure and report two independent power consumers and one producer (the solar panel inverter), so I’ll dive into this in more detail anyway. But that’ll have to wait until after the summer break.

Speaking of which: the June discount ends tomorrow, just so you know…

Update – I have disconnected the burden resistors, since the SCT-013-030 has one built in. See comments.

TK – Measuring milli-ohms

In Hardware on Jun 28, 2012 at 00:01

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

Today, I’d like to present a nifty new arrival here at JeeLabs, called the Half Ohm:

DSC 3348

It’s a brilliant little tool (with a cute name). What it does is convert milliohm to millivolt, and it works roughly in the range 0 .. 500 mΩ. Hence the name. On the back is a coin cell, and there’s a tiny on-off switch. Luckily, it’s hard to forget to turn the thing off because there’s a bright red LED while it’s powered up.

Milliohms are tricky. Fortunately, Jaanus Kalde, who created this tool has it all explained on his website.

So what can you do with a milliohm meter? Well, measure the resistance of your test leads, for one:

DSC 3349

That’s 22.8 mΩ, i.e. 0.0228 Ω. Not surprising, because (almost) every conductor has some resistance.

Being able to measure such low resistances can be extremely useful to find shorts. For example, when using longer test leads, I can see that their own resistance is 74 mΩ. And with that knowledge, we can measure PCB traces:

DSC 3350

Turns out that in this case I got about 112 mΩ, which means that this little 5 cm stretch of copper on the PCB has 37 mΩ resistance. And sure enough, the other ground pins have less resistance when when the path is shorter, and more when the path is longer. This is very logical – note also that between the GND pins I’ll be measuring relatively low values because of the relatively “fat” ground plane, which reduces overall DC resistance.

To find shorts, we simply measure the resistance between any two points (with no power connected, of course). If the measured value is close to 75 mΩ, then it’s a short. If it’s well above say 150 mΩ, then it’s definitely not a short.

To locate a short circuit, we can now simply move probes towards the direction of lowest resistance.

Looks like the Half Ohm will be a great help for this type of hard-to-isolate problems!

PS. No need to do the subtraction in your head if you have a multimeter which supports relative measurements.

Edge interrupts

In AVR, Hardware, Software on Jun 27, 2012 at 00:01

To continue yesterday’s discussion about level interrupts, the other variant is “edge-triggered” interrupts:

JC s Grid page 22

In this case, each change of the input signal will trigger an interrupt.

One problem with this is that it’s possible to miss input signal changes. Imagine applying a 1 MHz signal, for example: there is no way for an ATmega to keep up with such a rate of interrupts – each one will take several µs.

The underlying problem is a different one: with level interrupts, there is sort of a handshake taking place: the external device generates an interrupt and “latches” that state. The ISR then “somehow” informs the device that it has seen the interrupt, at which point the device releases the interrupt signal. The effect of this is that things always happen in lock step, even if it takes a lot longer before the ISR gets called (as with interrupts disabled), or if the ISR itself takes some time to process the information.

With edge-triggered interrupts, there’s no handshake. All we know is that at least one edge triggered an interrupt.

With “pin-change interrupts” in microcontrollers such as the ATmega and the ATtiny, things get even more complicated, because several pins can all generate the same interrupt (any of the PD0..PD7 pins, for example). And we also don’t get told whether the pin changed from 0 -> 1 or from 1 -> 0.

The ATmega328 datasheet has this to say about interrupt handling (page 14):

Screen Shot 2012 06 26 at 23 08 46

(note that the “Global Interrupt Enable” is what’s being controlled by the cli() and sei() instructions)

Here are some details about pin-change interrupts (from page 74 of the datasheet):

Screen Shot 2012 06 26 at 23 13 01

The way I read all the above, is that a pin change interrupt gets cleared the moment its associated ISR is called.

What is not clear, however, is what happens when another pin change occurs before the ISR returns. Does this get latched and generate a second interrupt later on, or is the whole thing lost? (that would seem to be a design flaw)

For the RF12 driver, to be able to use pin-change interrupts instead of the standard “INT0″ interrupt (used as level interrupt), the following is needed:

  • every 1 -> 0 pin change needs to generate an interrupt so the RFM12B can be serviced
  • every 0 -> 1 pin change can be ignored

The current code in the RF12 library is as follows:

Screen Shot 2012 06 26 at 23 19 59

I made that change from an “if” to a “while” recently, but I’m not convinced it is correct (or that it even matters here). The reasoning is that servicing the RFM12B will clear the interrupt, and hence immediately cause the pin to go back high. This happens even before rf12_interrupt() returns, so the while loop will not run a second time.

The above code is definitely flawed in the general case when more I/O pins could generate the same pin change interrupt, but for now I’ve ruled that out (I think), by initializing the pin change interrupts as follows:

Screen Shot 2012 06 26 at 23 23 28

In prose:

  • make the RFM12B interrupt pin an input
  • enable the pull-up resistor
  • allow only that pin to trigger pin-change interrupts
  • as last step, enable that pin change interrupt

Anyway – I haven’t yet figured out why the RF12 driver doesn’t work reliably with pin-change interrupts. It’s a bit odd, because things do seem to work most of the time, at least in the setup I tried here. But that’s the whole thing with interrupts: they may well work exactly as intended 99.999% of the time. Until the interrupt happens in some particular spot where the code cannot safely be interrupted and things get messed up … very tricky stuff!

Level interrupts

In Hardware, Software on Jun 26, 2012 at 00:01

The ATmega’s pin-change interrupt has been nagging at me for some time. It’s a tricky beast, and I’d like to understand it well to try and figure out an issue I’m having with it in the RF12 library.

Interrupts are the interface between real world events and software. The idea is simple: instead of constantly having to poll whether an input signal changes, or some other real-world event occurs (such as a hardware count-down timer reaching zero), we want the processor to “somehow” detect that event and run some code for us.

Such code is called an Interrupt Service Routine (ISR).

The mechanism is very useful, because this is an effective way to reduce power consumption: go to sleep, and let an interrupt wake up the processor again. And because we don’t have to keep checking for the event all the time.

It’s also extremely hard to do these things right, because – again – the ISR can be triggered any time. Sometimes, we really don’t want interrupts to get in our way – think of timing loops, based on the execution of a carefully chosen number of instructions. Or when we’re messing with data which is also used by the ISR – for example: if the ISR adds an element to a software queue, and we want to remove that element later on.

The solution is to “disable” interrupts, briefly. This is what “cli()” and “sei()” do: clear the “interrupt enable” and set it again – note the double negation: cli() prevents interrupts from being serviced, i.e. an ISR from being run.

But this is where it starts to get hairy. Usually we just want to prevent an interrupt to happen now – but we still want it to happen. And this is where level-interrupts and edge-interrupts differ.

A level-interrupt triggers as long a an I/O signal has a certain level (0 or 1) and works as follows:

JC s Grid page 22

Here’s what happens at each of those 4 points in time:

  1. an external event triggers the interrupt by changing a signal (it’s usually pulled low, by convention)
  2. the processor detects this and starts the ISR, as soon as its last instruction finishes
  3. the ISR must clear the source of the interrupt in some way, which causes the signal to go high again
  4. finally, the ISR returns, after which the processor resumes what it had been doing before

The delay from (1) to (3) is called the interrupt latency. This value can be extremely important, because the worst case determines how quickly our system responds to external interrupts. In the case of the RFM12B wireless module, for example, and the way it is normally set up by the RF12 code, we need to make sure that the latency remains under 160 µs. The ISR must be called within 160 µs – always! – else we lose data being sent or received.

The beauty of level interrupts, is that they can deal with occasional cli() .. sei() interrupt disabling intervals. If interrupts are disabled when (1) happens, then (2) will not be started. Instead, (2) will be started the moment we call sei() to enable interrupts again. It’s quite normal to see interrupts being serviced right after they are enabled!

The thing about these external events is that they can happen at the most awkward time. In fact, take it from me that such events will happen at the worst possible time – occasionally. It’s essential to think all the cases through.

For example: what happens if an interrupt were to occur while an ISR is currently running?

There are many tricky details. For one, an ISR tends to require quite a bit of stack space, because that’s where it saves the state of the running system when it starts, and then restores that state from when it returns. If we supported nested interrupts, then stack space would at least double and could easily grow beyond the limited amount available in a microcontroller with limited RAM, such as an ATmega or ATtiny.

This is one reason why the processor logic which starts an ISR also disables further interrupts. And re-enables interrupts after returning. So normally, during an ISR no other ISRs can run: no nested interrupt handling.

Tomorrow I’ll describe how multiple triggers can mess things up for the other type of hardware interrupt, called an edge interrupt – this is the type used by the ATmega’s (and ATtiny’s) “pin-change interrupt” mechanism.

… and pies

In Hardware on Jun 25, 2012 at 00:01

This post follows up on yesterday’s first dive into the Raspberry Pi computer.

I switched to a beta of the next Debian release, called Wheezy. Full screen detect out of the box now:

DSC 3343

Those stripes are artifacts – that’s Moiré kicking in when using CCD pixels to take a picture of TFT LCD pixels.

The idea is to turn this thing into a permanent fixture on the back of this panel – right above my workbench:

DSC 3346

This is using a separate 5V and a 12V supply for now, but I’d like to explore a range of other options:

  • no keyboard or mouse normally attached
  • using a USB WiFi dongle instead of wired Ethernet
  • powered from a single 12V @ 2A DC power brick
  • add a step-down switching regulator to generate 5V
  • maybe: relays to control power to display and computer
  • a PIR motion sensor plus light sensor to detect presence?
  • a JeeNode USB, perhaps used as central node or as OOK relay
  • and maybe also a rechargeable 6V or 12V battery as UPS

The latter depends on whether this setup will become part of the permanent home automation system at JeeLabs.

As switcher I’ll use a no-name brand from eBay – it delivers 5V at over 1 A and draws about 8 mA without load:

DSC 3345

Lots of pesky little details need to be worked out, such as how to get a Sitecom WLA-1000 USB WiFi dongle working, how to set up what is essentially “kiosk mode”, and how to control the display backlight. I’d also like to hook up an RFM12B directly to the main board, to see how convenient this is and what can be done with it.

There’s a nice article at next.kolumbus.no about setting up something quite similar. Long live the sharing culture!

Total system cost should be roughly €100..150, since I recovered the screen from an old Dell laptop.

Onwards!

Raspberries …

In Hardware on Jun 24, 2012 at 00:01

Recently got a Raspberry Pi here. Add keyboard, mouse, display, and USB power adapter and there it goes:

DSC 3341

Oh yes, I did have to put Debian 6 (Squeeze) on a 2 GB SD memory card first, using these instructions.

Note that my 1280×720 screen size isn’t auto-detected, but it’s good enough for now. This is the whole system:

DSC 3342

Next step – switch over to Ethernet:

  • plug in an Ethernet cable, it automatically registers via DHCP
  • log in via SSH, get rid of the greeting (simply create ~/.hushlogin)
  • set up password-less SSH access, yada, yada, yada

Done. Now I can unplug the keyboard and mouse, and insert a JeeLink. It’s recognized right out of the box:

Screen Shot 2012 06 23 at 15 13 48

Does it work? Let’s check with JeeMon (using a runtime built for ARM, of course):

Here’s a quick look at some stats and then a check that JeeMon works:

Screen Shot 2012 06 23 at 15 09 54

Looks good. Now let’s see if the JeeLink is accessible:

Screen Shot 2012 06 23 at 15 15 54

Yup. Done. Total setup time: 5 minutes (plus another 10 for the SD card). Well done, Raspberry Pi!

This draws 14 W in total, including 11 W for the display (when on) and 0.4 W when Ethernet is plugged in.

Low power – µA’s in perspective

In AVR, Hardware on Jun 23, 2012 at 00:01

Ultra-low power computing is a recurring topic on this weblog. Hey – it’s useful, it’s non-trivial, and it’s fun!

So far all the experiments, projects, and products have been with the ATmega from Atmel. It all started with the ATmega168, but since some time it’s now all centered around the ATmega328P, where “P” stands for pico power.

There’s a good reason to use the ATmega, of course: it’s compatible with the Arduino and with the Arduino IDE.

With an ATmega328 powered by 3.3V, the lowest practical current consumption is about 4 µA – that’s with the watchdog enabled to get us back out of sleep mode. Without the internal watchdog, i.e. if we were to rely on the RFM12B’s wake-up timer, that power-down current consumption would drop considerably – to about 0.1 µA:

Screen Shot 2012 06 22 at 22 03 30

Whoa, that’s a factor 40 less! Looks like a major battery-life improvement could be achieved that way!

Ahem… not so fast, please.

As always, the answer is a resounding “that depends” – because there are other power consumers involved, and you have to look at the whole picture to understand the impact of all these specs and behaviors.

First of all, let’s assume that this is a transmit-only sensor node, and that it needs to transmit once a minute. Let’s also assume that sending a packet takes at most 6 ms. The transmitter power consumption is 25 mA, so we have a 10,000:1 sleep/send ratio, meaning that the average current consumption of the transmitter will be 2.5 µA.

Then there’s the voltage regulator. In some scenarios, it could be omitted – but the MCP1702 and MCP1703 used on JeeNodes were selected specifically for their extremely low quiescent current draw of 2 µA.

The RFM12B wireless radio module itself will draw between 0.3 µA and 2.3 µA when powered down, depending on whether the wake-up timer and/or the low-battery detector are enabled.

That’s about 5 to 7 µA so far. So you can see that a 0.1 µA vs 4 µA difference does matter, but not dramatically.

I’ve been looking at some other chips, such as ATXmega, PIC, MSP430, and Energy Micro’s ARM. It’s undeniable that those ATmega328’s are really not the lowest power option out there. The 8-bit PIC18LF25K22 can keep its watchdog running with only 0.3 µA, and the 16-bit MSP430G2453 can do the same at 0.5 µA. Even the 32-bit ARM EFM32TG110 only needs 1 µA to keep an RTC going. And they add lots of other really neat extra features.

In terms of low power there are at two more considerations: other peripherals and battery size / self-discharge.

In a Room Node, there’s normally a PIR sensor to detect and report motion. By its very nature, such a sensor cannot be shut off. It cannot even be pulsed, because a PIR needs a substantial amount of time to stabilize (half a minute or more). So there’s really no other option than to keep it powered on at all times. Well, perhaps you could turn it off at night, but only if you really don’t care what happens then :)

Trouble is: most PIR sensors draw a “lot” of current. Some over 1 mA, but the most common ones draw more like 150..200 µA. The PIR sensor I’ve found for JeeLabs is particularly economical, but it still draws 50..60 µA.

This means that the power consumption of the ATmega really becomes almost irrelevant. Even in watchdog mode.

The other variable in the equation is battery self-discharge. A modern rechargeable Eneloop cell is quoted as retaining 85% of its charge over 2 years. Let’s assume its full charge is 2000 mAh, then that’s 300 mAh loss over 2 years, which is equivalent to about 17 µA of continuous self-discharge.

Again, the 0.1 µA vs 4 µA won’t really make such a dramatic difference, given this figure. Definitely not 40-fold!

As you can see, every microamp saved will make a difference, but in the grand scheme of things, it won’t double a battery’s lifetime. There’s no silver bullet, and that Atmel ATmega328 remains a neat Arduino-compatible option.

That doesn’t mean I’m not peeking at other processors – even those that don’t have a multi-platform IDE :)

Disk storage

In Hardware on Jun 19, 2012 at 00:01

I recently stumbled across this ad in Byte Magazine of August 1980:

What a bargain! – Now compare it to this one at NewEgg (yeah, no enclosure or power supply, I know):

Screen Shot 2012 06 17 at 02 23 12

(note how this drive has more RAM included as cache even than the total storage on that 1980’s disk!)

Let’s ignore inflation and try to compare storage prices across this 32-year stretch:

  • $4995 for 26 MB is $192 per megabyte
  • $170 for 3 TB is $57 per terabyte – six extra zero’s
  • in other words: storage has become ≈ 3.37 million times cheaper

Then again, hard drives are so passé … it’s all SSD and cloud storage, nowadays.

The amazing bit is not merely the staggering size increase and price reduction, but the fact that this happened within less than a lifetime. Bill’s, Steve’s – anyone over 50 will have witnessed this, basically.

Might be useful to think about this when putting our work in context of… a few years down the road from now.

Simple digital oscillator

In Hardware on Jun 18, 2012 at 00:01

As described in this recent post, it should be possible to create a simple fixed frequency oscillator using just a few low-cost components. This could then be used as interrupt source to wake up an ATmega every millisecond or so.

Here’s a first attempt, based on a widely-used circuit, as described in Fairchild’s Application Note 118:

Screen Shot 2012 06 16 at 13 08 02

I used a CD4049 hex inverter, since I had them within easy reach:

DSC 3336

The two resistors are 10 kΩ, the capacitor is 0.1 µF – and here’s what it does:

SCR27

The yellow trace is VOUT, the blue trace is V1. Pretty stable oscillation at 456 Hz.

Unfortunately, the current draw is a bit high with these components: 140 µA idle, and 450 µA when oscillating! There would be no point, yesterday’s approach will take half as much current using just a single 0.1 µF cap.

If someone has a tip for a simple 0.5 .. 1 KHz oscillator which consumes much less power, please let me know…

Low-power waiting – interrupts

In AVR, Hardware on Jun 17, 2012 at 00:01

Following yesterday’s trial, here is the code which uses the pin-change interrupt to run in a continuous cycle:

Screen Shot 2012 06 15 at 17 57 02

The main loop is empty, since everything now runs on interrupts. The output signal is the same, so it’s working.

Could we somehow increase the cycle frequency, to get a higher time resolution? Sure we can!

The above code discharges the cap to 0V, but if we were to discharge it a bit less, it’d reach that 1.66V “1” level more quickly. And sure enough, changing the “50” loop constant to “10” increase the rate to 500 Hz, a 2 ms cycle:

SCR24

As you can see, the cap is no longer being discharged all the way to 0V. A shorter discharge cycle than this is not practical however, since the voltage does need to drop to a definite “0” level for this whole “cap trick” to work.

So how do we make this consume less power? Piece of cake: turn the radio off and go to sleep in the main loop!

Screen Shot 2012 06 15 at 19 50 10

The reason this works, is that the whole setup continuously generates (and processes) pin-change interrupts. As a result, this JeeNode SMD now draws about 0.23 mA and wakes up every 2 ms using nothing more than a single 0.1 µF cap tied to an I/O pin. Mission accomplished – let’s declare (a small) victory!

PS. Exercise for the reader: you could also use this trick to create a simple capacitance meter :)

Low-power waiting

In AVR, Hardware on Jun 16, 2012 at 00:01

This continues where yesterday left off, trying to wait less than 16 milliseconds using as little power as possible.

First off, I’m seeing a lot of variation, which I can’t explain yet. I decided to use a standard JeeNode SMD, including regulator and RFM12B radio, since that will be closer to the most common configuration anyway.

Strangely enough, this sketch now generates a 704 µS toggle time instead of 224 µs, i.e. 44 processor cycles per loop() iteration. I don’t know what changed since yesterday, and that alone is a bit worrying…

The other surprise is that power consumption varies quite a bit between different units. On one JN SMD, I see 1.35 mA, on another it’s only 0.86 mA. Again: I have no idea (yet) what causes this fairly substantial variation.

How do we reduce power consumption further? The watchdog timer is not an option for sleep times under 16 ms.

The key point is to find some suitable interrupt source, and then go into a low-power mode with all the clock/timing circuitry turned off (in CMOS chips, most of the energy is consumed during signal transitions!).

Couple of options:

  1. run the ATmega off its internal 8 MHz RC clock and add a 32 KHz crystal
  2. add extra circuitry to generate a low-frequency pulse and use pin-change interrupts
  3. connect the RFM12B’s clock pin to the IRQ pin and use Timer 2 as divider
  4. add a simple RC to an I/O pins and interrupt on it’s charge cycle
  5. use the RFM12B’s built-in wake-up timer – to be explored in a separate weblog post

Option 1) has as drawback that you can’t run with standard fuse settings anymore: the clock will have to be the not-so-accurate 8 MHz RC clock and the crystal oscillator needs to be set appropriately. It does seem like this would allow short-duration low-power waiting with a granularity of ≈ 30 µs.

Option 2) needs some external components, such as perhaps a low-power 7555 CMOS timer. This would probably still consume about 0.1 mA – pretty low, but not super-low. Or maybe a 74HC4060, for perhaps 0.01 mA (10 µA) power consumption.

Option 3) may sound like a good idea, since Timer 2 can run while the rest of the ATmega’s clock circuits are switch off. But now you have to keep the RFM12B’s 10 MHz crystal running, which draws 0.6 mA … not a great improvement.

Option 4) seems like an option worth trying. The idea is to connect these components to a spare I/O pin:

JC s Grid page 17

By pulling the I/O pin low as an output, the capacitor gets discharged. When turning the pin into a high-impedance input, the cap starts charging until it triggers a transition from a “0” to a “1” input, which could be used as pin-change interrupts. The resistor value R needs to be chosen such that the charge time is near to what we’re after for our sleep time, say 1 millisecond. Longer times can then be achieved by repeating the process.

It might seem odd to do all this for what is just one thousandths of a second, but keep in mind that during this time the ATmega can be placed in deep-sleep mode, consuming only a few µA’s. It will wake up quickly, and can then either restart another sleep cycle or resume its work. This is basically the same as a watchdog interrupt.

Let’s first try this using the internal pull-up resistor instead, and find out what sort of time delays we get:

Screen Shot 2012 06 15 at 17 22 53

(several typo’s: the “80 µs” comment in the above screen shot should be “15 µs” – see explanation below)

This code continuously discharges the 0.1 µF capacitor connected to DIO1, then waits until it charges up again:

SCR23

With the internal pull-up we get a 3.4 ms cycle time. By adding an extra external resistor, this could be shortened. The benefit of using only the internal pull-up, is that it also allows us to completely switch off this circuit.

We can see that this ATmega switches to “1” when the voltage rises to 1.66V, and that its internal pull-up resistor turns out to be about 49 kΩ (I determined this the lazy way, by tweaking values on this RC calculator page).

Note that discharge also takes a certain amount of time, i.e. when the output pin is set to “0”, we have to keep it there a bit. Looks like discharge takes about 15 µs, so I adjusted the asm volatile (“nop”) loop to cycle 50 times:

SCR22

In other words, this sketch is pulling the IO pin low for ≈ 15 µs, then releases it and waits until the internal pull-up resistor charges the 0.1 µF capacitor back to a “1” level. Then this cycle starts all over again. Easy Peasy!

So there you have it: a single 0.1 µF capacitor is all it takes to measure time in 3.4 µs ms increments, roughly. Current consumption should be somewhat under 67 µA, i.e. the current flowing through a 49 kΩ resistor @ 3.3V.

Tomorrow, I’ll rewrite the sketch to use pin-change interrupts and go into low-power mode… stay tuned!

Waiting without the watchdog

In AVR, Hardware on Jun 15, 2012 at 00:01

The watchdog timer in the ATmega has as shortest interval about 16..18 milliseconds. Using the watchdog is one of the best ways to “wait” without consuming much power: a fully powered ATmega running at 16 MHz (and 3.3V) draws about 7 mA, whereas it drops thousandfold when put to sleep, waiting for the watchdog to wake it up again.

The trouble is: you can’t wait less than that minimum watchdog timer cycle.

What if we wanted to wait say 3 ms between transmitting a packet and turning on the receiver to pick up an ACK?

Short time delays may also be needed when doing time-controlled transmissions. If low power consumption is essential, then it becomes important to turn the transmitter and receiver on at exactly the right time, since these are the major power consumers. And to wait with minimal power consumption in between…

One approach is to slow down the clock by enabling the built-in pre-scaler, but this has only a limited effect:

Screen Shot 2012 06 14 at 16 39 58

The loop toggles an I/O bit to allow verification of the reduced clock rate. The above code draws about 1.6 mA, whereas the same code running at full speed (16 MHz) draws about 8.8 mA. Note that these measurements ended up a bit lower, but that was as 3.3V – I’m running from a battery pack in these tests, i.e. at about 4.0V.

The I/O pin toggles at 2.23 KHz in slow mode, vs 573 KHz at full speed, which indicates that the system clock was indeed running 256 times slower. A 2.23 KHz rate is equivalent to a 224 µs toggle cycle, which means the system needs 14 processor cycles (16 µs each) to run through this loop() code. Most of it is the call/return stack overhead.

So basically, we could now wait a multiple of 16 µs while consuming about 1.6 mA – that’s still a “lot” of current!

Tomorrow, I’ll explore ways to reduce this power consumption further…

Code vs. power consumption

In AVR, Hardware on Jun 13, 2012 at 00:01

I’ve been wondering for some time whether the power consumption of an ATmega varies depending on the code it is running. Obviously, sleep modes and clock rate changes have a major impact – but how about plain loops?

To test this, I uploaded the following sketch into a JeeNode:

Screen Shot 2012 06 12 at 21 34 50

Interrupts were turned off to prevent the normal 1024 µs timer tick from firing and running in between. And I’m using “volatile” variables to make sure the compiler doesn’t optimize these calculations away (as they’re not used).

The result is that the code pattern does indeed show up in the chip’s total current consumption:

SCR20

The value displayed is the voltage measured over a 10 Ω resistor in series with VCC (the JeeNode I used had no regulator, and was running directly off a 3x AA battery pack @ 3.95V).

What you can see is that the power consumption cycles between about 8.4 mA and 8.8 mA, just by being in different parts of the code. Surprising perhaps, but it’s clearly visible!

The shifts in the second loop are very slow – due to the fact that the ATmega has no barrel shifter. It has to use a little loop to shift by N bits. To get a nice picture, those shifts are performed only 5,000 times instead of 50,000.

The high power consumption is during the multiplication loop, the low consumption is during the shift loop.

In the end, I had to use a lot of tricks to create the above oscilloscope capture, because there was a substantial amount of 50 Hz hum on the measured input signal. Since the repetition rate of the signal I was interested in was not locked to that 50 Hz AC mains signal, most of the “noise” went away by averaging the signal over 128 triggers.

The other trick was to use the scope’s “DC offset” facility to lower the signal by 80 mV. This allows bumping the input sensitivity all the way up to 2 mV/div without the trace running off the screen. An alternative would be to use AC coupling on the input, but then I’d lose the information about the actual DC levels being measured.

What else can we deduce from the above screen shot?

  • loop 1 takes 93.48 ms for 50,000 iterations, so one cycle runs in ≈ 1.8 µs
  • loop 2 takes 108.52 ms for 5,000 iterations, so one cycle runs in ≈ 21.8 µs

As you can see, shifts by a variable number of bits do take quite a lot of time on an ATmega, relatively speaking!

Update – As noted in the comments, a shift by “321” ends up being done modulo 256, i.e. 65 times. If I change the shift to 3, the run times drop to being comparable to a multiply. The power consumption effect remains.

Jumping to conclusions

In Hardware on Jun 12, 2012 at 00:01

Yesterday, I made an effort to remove some glitches which I thought were due to the switching regulator used inside the ±15V DC-DC converter. To be honest: it didn’t really make any sense when I saw this on the scope…

It’s always easy to draw some conclusion – it’s a bit harder to avoid uttering complete nonsense…

Here’s the signal with the power supply turned off, and only the ground cable still connected:

SCR19

Clearly the same signal – it appears even when the 1 meter ground cable isn’t tied to anything: it’s an antenna!

In other words: I’m probably just picking up one of the FM transmitters in this region. I should of course have turned on the scope’s built-in 20 MHz bandwidth filter. There was no reason to look for frequencies that high with a switcher in the 60..100 KHz region. And the fact that neither a bypass capacitor nor various inductors made much difference should have been a clue. How embarrassing.

Onwards, quickly!

Switching glitches

In Hardware on Jun 11, 2012 at 00:01

The dual power supply described yesterday had a nasty spike every 5 µs. I tried damping them with one of these:

Varkensneus

(they are called “varkensneus” – pigs nose – in Dutch, ’cause that’s what they look like, seen from the end)

But the results were not very substantial when adding one to the supply output. When I added one on both the input and the output of the 7812 regulator, things did improve a bit further:

SCR15

The yellow trace is the output with ferrite core between the DC-DC converter output and the 7812 linear regulator input, and the blue trace is from a second ferrite core added at the end, i.e. the linear regulator’s output pin.

Note the scale of this oscilloscope capture: 10 nsec/div, so this is a 100 MHz high frequency signal of about ± 200 mV. The second ferrite core almost halves these spike’s amplitudes.

In conclusion: these are very brief ± 100 mV glitches, super-imposed on the +12V supply output voltage – i.e. about ±1% of the regulated supply output voltage. The glitches don’t change much with a 1 kΩ load, i.e. 12 mA.

It’s an artifact of the switching inside the DC-DC converter – looks like there’s not much more I can do about it!

Dual power supply

In Hardware on Jun 10, 2012 at 00:01

To generate a sine wave of ±10V for the Component Tester project, I’m going to need a suitable power supply.

The first option would be to take a dual-windings 12 VAC transformer, add a bridge rectifier, two beefy electrolytic capacitors, and violá: ±12V, right?

Not so fast… this is called an unregulated supply. It has a couple of drawbacks: 1) the voltages will actually be considerably larger than ±12V, 2) the voltages will change depending on the current drawn, and 3) the voltages can have a lot of residual ripple voltage. Let’s go through each of these:

  1. Voltage levels – a 12 VAC transformer generates a 50 Hz alternating current (60 Hz in the US) with an RMS voltage of about 12 VAC. For a sine wave, this corresponds to a peak voltage which is 1.414 times as high, i.e. 17 Volts peak to peak. With a bridge rectifier, you end up topping each of the two caps to 17V DC.
  2. Regulation – or rather: lack thereof. Since the input is a sine wave which only peaks at 17V, the caps will be charged up to this value only a couple of dozen times per second. In between, current drawn will simply discharge them, causing the voltage to drop. Large current = much lower voltage.
  3. Ripple voltage – this variation on the power supply is called ripple. It’ll be either the same frequency of AC mains, or double that value – depending on the rectification circuit used. So that’s a 50..120 Hz signal on top of what was supposed to be a fixed supply voltage (that’s why bad audio amplifiers can “hum”).

There’s a very simple solution to all these issues: add 2 linear regulators to generate a far more stable supply voltage (one for the positive and one for the negative supply). The most widely used regulator chips are the 78xx series (+) and the 79xx series (-). You give them a few more Volts than what they are designed to deliver, add a few caps for electrical stability, and that’s it. In this case, we need one 7812 and one 7912 to get ±12V.

But I’m not so fond of power line transformers in my circuits, because you have to hook them up to AC mains on one side – that’s 230 VAC, needing lots of care to prevent accidents. Besides, we only need a few dozen milliamps for this Component Tester anyway.

So instead, I decided to use a DC-to-DC converter – a nifty little device which takes DC in and transforms it to another level of DC. The nice thing is that there are “dual” variants which can automate both positive and negative voltages at the same time.

I picked the Traco TMA0515D, which generates up to 30 mA @ ±15V, using just 5V as input. Its efficiency is specified as about 80%, so the 900 mW it supplies will need about 1.125W of input power. At 5V, that translates to 225 mA, well within range of a USB port – how convenient!

Here is the circuit I’ve built up:

JC s Grid page 20

As you can see, it uses very few components. And the output is galvanically isolated from the input supply – nice!

Such DC-DC converters are surprisingly small, at least for low-power units like this one (black block on the left):

DSC 3304

With a bit of forethought, almost everything can be connected together with its own wires:

DSC 3305

It worked as expected (caveat: the 78xx and 79xx pinouts are different!), but there were two small surprises:

  • the unloaded DC-DC converter output was about ±25V, these units are clearly not internally regulated!
  • the outputs from this assembled unit are indeed + and – 12V, but with some residual switching noise:

SCR13

That DC-DC converter appears to be based on a 100 KHz switching regulator (5 µs between on and off transitions), and these spikes are making it all the way to the output pins, straight through those linear regulators!

It probably won’t matter for a component tester operating at 50..1000 Hz, but this too should be fairly easy to fix – by inserting a couple of ferrite beads for example: small inductors which filter out such high frequency “spikes”.

With analog circuitry, stable and smooth power supplies tend to be a lot more important!

Solar top-up, full sun

In Hardware on Jun 9, 2012 at 00:01

Yesterday’s setup described a circuit with the JeeNode running on an AA Power Board and a little solar cell to top up the charge when there was sufficient light.

Since today was a warm day here with lots of sunlight, I thought it’d be nice to establish an outdoor baseline:

DSC 3302

From left to right (see how useful it is to have a whole bunch of multimeters?):

  • the voltage of the solar cell is 2.7V right now
  • the current supplied by it is 0.76 mA
  • the current drawn from the AA cell is 20 µA
  • IOW: less than an hour of sunlight is enough for a day

This is running the radioBlip2 sketch (including the recent survival tweaks), with the same modified JeeNode (no regulator, 100 µF cap) as used in many recent experiments here at JeeLabs.

Note that these values add up reasonably well:

  • the 2.7V from the solar cell ends up being distributed as follows: 0.65V forward drop over the 1N4148 diode, 0.75V voltage drop over the 1 kΩ resistor, and 1.3V over the (almost fully-charged) Eneloop
  • battery draw is 20 µA, and I’ve independently measured about 4.8 µA idle current draw from the JeeNode (i.e. w/o the MCP1702 regulator), so losses and efficiencies are actually quite good

Here’s the same setup in the shade (still bright sunlight outside) – sorry for the bad readouts:

DSC 3303

The cell voltage now drops to 2.0V and the current it supplies is down to ≈ 0.14 mA.

For comparison, some indoor charge currents from the solar cell:

  • near the white LED strips at my workbench: 60 µA
  • behind the window, but not in the sun: 80 µA
  • behind the window, in (modest) sunlight: 400 µA

With a Room Board attached and a permanent indoor setup, these figures will change, but it all looks promising!

Eneloop with solar top-up

In Hardware on Jun 8, 2012 at 00:01

Here’s another idea in the continuing search for long autonomous JeeNode run times:

JC s Grid page 19

The basic circuit is an Eneloop AA(A) cell, driving the AA Power Board to boost its voltage to 3.3V. There’s a 1 kΩ in series with the battery, as well as a Schottky diode to limit the voltage drop to about 0.3V during times “high” current consumption. I’ll explain why later on.

On the input side is a really simple circuit: a solar cell with a series diode, simply feeding the Eneloop battery when there is solar energy available.

The solar cell I’m using is that same 4.5V @ 1 mA cell I’ve been using all the time in my recent experiments. It is surprisingly good at generating some electricity indoor, even behind the coated double-glazing we have here.

The 1 kΩ resistor in series will let me measure the actual current flowing across it – 1 µA will read out as a 1 mV drop (that Ohm’s law again, of course!). So with a charging current of up to say 200 µA, this conveniently matches the 200 mV lowest range of most multimeters. And 0.2V is not a dramatic voltage drop, so the circuit should continue to work – almost the same as without those measurement resistors included.

A similar 1 kΩ resistor has also been inserted between the battery and the AA Power Board, but in this case we have to be more careful: a JeeNode will briefly pull 25 mA while in transmit mode, and the 1 kΩ resistor would effectively shut off input power with such currents. So I added a diode with minimal forward drop in parallel – it’ll interfere with my readings, but I’m really only interested in the ultra-low power consumption phases.

Here’s my “flying circus” concoction:

DSC 3301

I’ve added some wires to easily allow clipping various meters on.

Now, clearly, 4V is way over the 1.3V nominal of an Eneloop battery. But here’s why this setup should still work:

  • this solar cell is so feeble that its voltage will collapse when drawing more than a fraction of a milliamp
  • solar cells may be shorted out – doing so switches them from constant-voltage to constant current mode

As for the Eneloop, my assumption is that it doesn’t really care much about being overcharged at these very low power levels. In the worst case of continuous sunshine for days on end, it’ll be fed at most 1 mA, even when full. That will probably just lead to a tiny amount of internal heating.

So let’s try and predict how this will work out, in terms of battery lifetimes…

I’ll take a JeeNode + Room Board as reference point, which draws about 60 µA continuous, on average (50 µA for the PIR, which needs to remain always-on). That’s on the 3.3V side of the AA Power board. So with a (somewhat depleted) AA battery @ 1.1V, than means the battery would have to supply 180 µA with a perfect boost regulator.

Unfortunately, perfect boost regulators are a bit hard to get. The chip on the AA Power Board does reasonably well, with about 20 µA idle and about 60..70% conversion efficiency. Let’s just batch those together as 50% efficiency, then the continuous power draw for a Room Node would be about 360 µA. Let’s round that up to 400 µA.

An Eneloop AA battery has about 1900 mAh capacity, but it loses some energy due to self-discharge. The claim is that it retains 85% over 2 years, so this battery can effectively give us about 1600 mAh of power.

The outcome of this little exercise, is that we ought to get some 4000 hours run-time out of one fully-charged AA cell, i.e. 166 days, almost six months. Not bad, but a little lower than I would have liked to see.

If the solar cell were to generate 4 hours per day @ 0.5 mA, when averaged over an entire year (that might be optimistic), then that’s 4 x 365 x 0.5 = 730 mAh. That comes down to an average current of 83 µA.

IOW, roughly one fifth of the total power needs could be supplied by the solar cell. Not enough for total autonomy, but still, it’s a start. Note that most of these last figures were pulled out of thin air at this stage: I don’t know yet!

Yet another idea would be to add an extra diode from the solar cell straight to the JeeNode +3V pin. IOW, when there is sufficient sunlight, we off-load the boost circuit altogether and charge up a capacitor of say 100..1000 µF on the JeeNode itself. No more losses, other than the AA Power Board’s quiescent current consumption.

TK – Cheap power supply

In Hardware on Jun 7, 2012 at 00:01

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

(I won’t call this a “lab power supply, for reasons explained below)

In a weblog post a while ago, I took apart a standard computer power supply unit (PSU). Now, instead, let’s do the opposite and turn it into a useful tool for experimentation with electrical circuits:

DSC 3330

What you see here is a neat little way to repurpose any standard ATX power supply. Just snip off most of the wires, except for that 20-pin connector, and assemble this neat little ATX adapter board by Benjamin Jordan:

DSC 3331

It’s available as a simple kit with a few basic components and all the connectors and binding posts.

The reason this is convenient is that it makes it somewhat easier to work with an ATX power supply (especially if it gets mounted on or near that power supply). There are push-buttons to toggle the supply on and off (except for the 5V standby voltage on the rightmost blue post, which is always on). There’s a LED to indicate whether the power supply is on (red) or in standby mode (green), and there’s an orange LED to indicate that power is OK.

All the main voltages are nicely arranged on binding posts, with matching ground return posts (all tied together internally), and there are holes to get to those same voltages via alligator clips – this is clearly for experimentation!

The is no high voltage anywhere, so the stuff is completely safe in terms of voltage. But there is still a risk:

DSC 3332

The currents available in most PC power supplies are phenomenal: 25 and 35 Amps on the 3.3V and 5V voltage rails, respectively. That’s what modern CPU’s and memory chips and all the supporting logic need, nowadays. The +12V supply is also pretty powerful, and normally used for all those terabyte disk drives people seem to be using.

This means that no matter how we touch it, it wont hurt us – anything under 40V is considered safe since our skin resistance prevents any serious amount of current flowing. But an electrical short circuit can (and will!) still easily vaporize thin copper traces on a low-power PCB. In other words: this is totally safe in terms of voltage, but the currents caused by shorts can generate sparks and enough heat to destroy components, wires, and PCB’s.

The above PCB itself is ok – its wide and thick gold-plated copper traces were designed to carry heavy currents.

What this means is that this setup is indeed a very cheap way to get lots of useful voltages for experimentation, but that it’s not the same thing as a “laboratory power supply” which also needs to have adjustable current limits.

Here are the voltages I measured coming out of this thing:

  • +5V standby, actual value, unloaded: 5.16 V
  • +3.3V, actual value, unloaded: 3.39 V
  • +5V, actual value, unloaded: 5.19 V
  • +12V, actual value, unloaded: 12.01 V
  • -12V, actual value, unloaded: -11.35 V

Close enough, and more importantly: most are slightly high. That means we could add very precise low-dropout regulators to get the voltages exactly right or we could add a current sensing circuit and limiter, to get that extra feature needed to turn this into a cheap yet beefy lab power supply.

TD – New Solid State Disk

In Hardware on Jun 5, 2012 at 00:01

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

After the recent server troubles (scroll down a bit), I had to replace one of the 500 GB Hitachi drives in the Mini.

I decided to switch to a 128 GB SSD for the system disk, with up to 6x faster transfer rates:

DSC 3233

It came with an interesting USB-to-SATA adapter included. Which looks like this inside:

DSC 3231

And on the bottom:

DSC 3232

(sorry: no teardown of the SSD, it’s probably just a bunch of black squares anyway!)

The scary part was replacing the disk in the Mac Mini’s “unibody” Aluminium case – as explained on YouTube.

But I definitely wanted to keep the server setup in a single enclosure. First lots of disk formatting, re-shuffling, and copying and then I just went ahead and did it. The good news: it worked. The system disk is now solid state!

DSC 3235

I had hoped that the most accessible drive would have to be replaced, but unfortunately it was the top one (when the Mini is placed on it feet) – so a full dismantling was required – look at all those custom-shaped parts:

DSC 3236

The other thing I did was to add an external 2 TB 2.5″ USB drive, to hold all Time Machine backups for both these server disks as well as two other Macs here at JeeLabs. This drive wil spin up once an hour, as TM does its thing.

Summary: the JeeLabs server now maintains a good up to date image of the entire system disk at all times, ready to switch to, and everything gets backed up to an external USB drive once an hour (these backups usually only take a minute or so, due to the way Time Machine works). All four VM’s get daily backups to the cloud, as well as now being included in Time Machine (Parallels takes care to avoid huge amounts of disk file copying).

That means all the essentials will be stored in at least three places. I think I can go back to the real work, at last.

There’s plenty of room for growth: 8 GB of RAM and less than half of the system disk space used so far.

Onwards!

Boost revisited

In Hardware on Jun 4, 2012 at 00:01

The AS1323 boost converter mentioned a while back claims an extra-ordinarily low 1.65 µA idle current when unloaded. At the time, I wasn’s able to actually verify that, so I’ve decided to dive in again:

Screen Shot 2012 05 17 at 15 28 15

A very simple circuit, but still quite awkard to test, due to its size:

DSC 3224

Bottom right is incoming power, bottom left is boosted 3.3V output voltage. Input voltage is 1.65V for easy math.

The good news is that it works, and it shows me an average current draw of 4.29 µA:

SCR03

The yellow line is the output voltags, with its characteristic boost-decay cycle. For reference: the top of the graph is at 3.45V, so the output voltage is roughly between 3.30 and 3.36V (it rises a bit with rising supply voltage).

The blue line is the voltage over a resistor inserted between supply ground and booster ground. I’m using 10 Ω, 100Ω, or 1 kΩ, depending on expected current draw (to avoid a large burden voltage). So this is the input current.

The red line is the accumulated current, but it’s not so important, since the scope also calculates the mean value.

Note that there’s some 50 Hz hum in the current measurement, and hence also in its integral (red line).

Aha! – and here’s the dirty little secret: the idle current is specified in terms of the output voltage, not the input voltage! So in case of a 1.65V -> 3.3V idle setup, you need to double the current (since we’re generating it from an input half as large as the 3.3V out), and you need to account for conversion losses!

IOW, for 100% efficiency, you’d expect 1.6 µA * (3.3V / 1.65V) = 3.2 µA idle current. Since the above shows an average current draw of 4.29 µA, this is about 75% efficient.

Not bad. But not that much better than the LTC3525 used on the AA Power Board, which was ≈ 20 µA, IIRC.

More worrying is the current draw when loaded with 10 µA, which is more similar to what a sleeping JeeNode would draw, with its wireless radio and some sensors attached:

SCR07

Couple of points to note, before we jump to conclusions: the boost regulator is now cycling at a bit higher frequency of 50 Hz. Also, I’ve dropped the incoming voltage to a more realistic 1.1V, i.e. 1/3rd of the output.

With a perfect circuit, this means the input current should be around 30 µA, but it ends up being about 52 µA, i.e. 57% efficiency. I have no idea why the efficiency is so low, would have expected about 70% from the datasheet.

Further tests with 1.65V in show that 1 µA out draws 6.72 µA, 10 µA out draws 29.6 µA, 100 µA out draws 261 µA, 1 mA out draws 2.51 mA, and 10 mA out draws 30.9 mA. Not quite the 80..90% efficiency from the datasheet.

My hunch is that the construction is affecting optimal operation, and that better component choices may need to be made – I just grabbed some SMD caps and a 10 µH SMD inductor I had lying around. More testing needed…

For maximum battery life, the one thing which really matters is the current draw while the JeeNode is asleep, since this is the state it spends most of its time in. So minimal consumption with 5..10 µA out is what I’m after.

To keep things in perspective: 50 µA average current drawn from one 2000 mAh AA cell should last over 4 years. A JeeNode with Room Board & PIR (drawing 50 µA, i.e. 200 µA from the battery) should still last almost a year.

Update – when revisiting the AA Power Board, I now see that it uses 25 µA from 1.1V with no load, and 59 µA with 10 µA load (down to 44 µA @ 1.5V in). The above circuit works (but does not start) down to 0.4V, whereas the AA Power Board works down to 0.7V – low voltages are not really that useful, since they increase the current draw and die quickly thereafter. Another difference is that the above circuit will work up to 2.3V (officially only 2.0V), and the AA Power Board up to at least 6V (which is out of spec), switching into step-down mode in this case.

Component Tester quality

In Hardware on Jun 3, 2012 at 00:01

Will all this effort to create a good sine wave for use as Component Tester, and all the testing on it, I might as well put the CT to the test which started it all, i.e. the one built into my Hameg HMO2024 oscilloscope.

Nothing easier than that – just hook up a probe to the signal it generates on the front panel, and do an FFT on it:

SCR89

(yeah, a green trace for a change – the other channels were tied up for another experiment…)

Ok, but not stellar: 1.6% harmonic distortion on the 3rd harmonic – more than with the Phase Shift Oscillator.

The frequency is also about 10% high, although that’s usually not so important for a Component Tester.

PS. The ∆L units should be “dB”, not “dBm” – Hameg says they’ll fix this oversight in the next firmware update.

TK – Multimeter accuracy

In Hardware on May 31, 2012 at 00:01

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

Once you get into calibration stuff, it’s hard to stop. I recently bought this DMMCheck from voltagestandard.com:

DSC 3314

The nice thing about this unit is that it’s fully self-contained (with a 9V battery on the back) and that it has all the bits and pieces on board to check a multimeter’s (DC) voltage, (DC) current, and resistance measurements.

It comes with a calibration report – the voltage has been trimmed to exactly 5V, but the rest will have slightly different values due to component and temperature tolerances. Also, it was calibrated at 70°F (21.1°C):

DSC 3315

Here are my HP 34401A measurements, with only 15 minutes warm-up (it’s now about 23.5°C here at JeeLabs):

DSC 3316

DSC 3317

DSC 3319

DSC 3318

Very close – more than close enough to start checking the VC170 multimeter I described recently, for example:

DSC 3323

DSC 3322

DSC 3320

Easily within spec. Note that a VC170 only has 400 µA + 400 mA ranges, and 1 mA only shows 2 decimal points.

Here’s a higher-spec VC940, which I find unconvincing – I use it rarely anyway, due to its slow refresh rate:

DSC 3324

Here’s a very low end Extech MN15 – it performs worse than the VC170 and can only display values up to 1999:

DSC 3328 DSC 3325 DSC 3327

And finally, as flash from the past, a cheap analog multimeter – this one is probably over 30 years old:

DSC 3329

We’ve sure come a long way, from trying to guess the value while not mixing up all those scales!

This reaffirms my choice of using the VC170 for day-to-day use, with the high-end HP 34401A used for top accuracy and for long-running experiments (handheld multimeters always auto-shutdown much too quickly).

As you can see, the DMMCheck is an superb little tool to quickly do a sanity check of your multimeter(s). There’s now also a DMMCheck Plus with extra signals to check AC voltage + current, and even frequency + duty cycle.

If you take lots of measurements over the years, it’s well worth getting something like this to verify your DMM.

This all relates to a discipline called metrology (no, not “meteo”, but “metrics”) – i.e. the science of measurement.

Zero voltage diode

In Hardware on May 30, 2012 at 00:01

Two weeks ago, user @tmk commented on the weblog post about diodes with a pointer to a Zero Volt Diode.

Here’s the circuit, by Wilf Rigter:

200px NsmailCA

I couldn’t quite wrap my head around it, so I re-drew it in a different way – it’s still the same circuit:

JC s Grid page 15 copy

The key is that a MOSFET can switch a voltage with nearly no voltage drop, i.e. a signal on its gate can turn it from near-infinite to near-zero resistance. There’s no “bipolar junction” involved, therefore no 0.6V .. 0.8V threshold.

I’m not going to explain the circuit, but I’ve built it up and did some measurements to show its behavior:

DSC 3223

Since a supercap has all sorts of odd behavior w.r.t. deep discharge and such, I replaced it with a 6800 µF electrolytic cap for this experiment, in parallel with a 1 kΩ resistor to simulate a load of a few mA.

Instead of the solar panel, I’m using a 2.9V power supply, limited to supply at most 10 mA. In other words, when connected to the capacitor, it will reduce its voltage a bit while the charging current is high, and then end up as 2.9V once the capacitor has been fully charged up. This makes it similar to a solar cell with limited capacity.

Enough talking. Let’s see how this thing behaves, while tracking a number of voltage levels at the same time:

SCR70

There’s a lot to describe here:

  • the RED line is the voltage from the power supply, i.e. Vsolar
  • the YELLOW line is the voltage over the capacitor, i.e. Vcc
  • the GREEN line is the voltage between drain and source of the MOSFET
  • the BLUE line is the voltage on the gate of the MOSFET
  • all signals have their zero origin at 2 divisions from the bottom
  • power was turned on after 2 seconds from the left edge of the screen
  • power was turned off again about 5 seconds later

The RED line is actually the YELLOW line minus the GREEN line.

The first thing to note is really the whole point of this circuit: the voltage on the capacitor (YELLOW) rises up to 2.84V, while the input voltage (RED) reaches 2.90V, so there’s only a 0.06V voltage drop over that FET while it conducts. That’s a ten-fold improvement over a silicon diode, and three-fold over a Schottky diode.

I’m using a BC557 for the PNP transistor, a BC549 for the NPN transistor, and a VN2222 as MOSFET, just because I happened to have those lying around. That MOSFET in particular is not a great fit here, really.

The other peculiar thing about this circuit, is that the MOSFET is used for current flowing through it in the wrong direction, from drain to source! But most MOSFETs won’t mind, they really act a bit like (controllable) resistors.

The most interesting bit is the GREEN signal, i.e. the voltage over the MOSFET. At input levels under about 1.5V it does conduct, but with a substantial voltage drop – first from the built-in diode conducting, and then gradually the MOSFET turns on and its low resistance takes over, with a total voltage drop of some 30..60 mV.

When the input voltage is completely switched off, the MOSFET goes into high impedance mode within a fraction of a second, which can be deduced from the fact that the GREEN and YELLOW lines meet up and overlap.

Lastly, once the voltages drop below about 0.4V, the gate voltage on the MOSFET rises a bit, but this is not enough to turn it on, and also not very important since the whole circuit is now essentially “dead”.

Here’s the second event in greater detail, i.e. when the input voltage drops – or in this case, gets switched off:

SCR71

The MOSFET is switched off within milliseconds, with the cap now holding a higher voltage than the input.

The result of it all is that the capacitor soaks up almost all the voltage it can get, with no diode forward voltage drop involved. When the input voltage drops, the circuit disconnects it from the cap so it’ll retain its charge. Brilliant!

Update – Wanted to get a bit more info on-screen, so here’s another scope capture (oops, green is now yellow):

SCR16

It better displays the elegant “swirly” charge ramp, with an odd little 64 mV bump on the MOSFET when the cap is full (maybe that’s the power supply switching to constant voltage mode). Given that the cap voltage reaches 2.82V and is loaded down by a 1 kΩ resistor, we can deduce that the current through the MOSFET must be 2.82 mA at that point, and therefore that its resistance is 23 Ω in this circuit (64.57 mV / 2.82 mA, Ohm’s law again!).

It’s about survival

In AVR, Hardware, Software on May 29, 2012 at 00:01

When running off solar power, ya’ gotta deal with lack of (sun-) light…

As shown in a recent post, a 0.47F supercap appears to have enough energy storage to get through the night, at least when assuming that the day before was sunny and that the nights are not too long.

There are still a couple of issues to solve. One which I won’t go into yet, is that the current approach won’t start up properly when there is only a marginal power budget to begin with. That’s a hard problem – some other time!

But another tactic to alleviate this problem, is to try and sail through a low-power situation by reducing power consumption until (hopefully) more energy becomes available again, later on.

Here’s my first cut at implementing a “survival strategy”, using the radioBlip2 sketch:

Screen Shot 2012 05 15 at 14 00 12

It’s all in the comments, really: when power is low, try to avoid sending packets, since turning on the transmitter is by far the biggest power “hog”. And when power is really low, don’t even measure VCC – just slow down even more in maximally efficient sleep mode – I’ve set the times to 5 and 60 minutes. The 1-hour sleep being a last effort to get through a really rough night…

But I’ve also added some kamikaze logic: when running low, you don’t just want the sketch to go into sleep mode more and more and finally give up without having given any sign of life. So instead, when the sketch is about to decide whether it should send a packet again, it checks whether the voltage is really way too low after what was supposedly a long deep-sleep period. If so, and before power runs out completely, it will try to send out a packet anyway, in the knowledge that this might well be its last good deed. That way, the central node might have a chance to hear this final swan song…

The thresholds are just a first guess. Maybe there are better values, and maybe there is a better way to deal with the final just-about-to-die situation. But for now, I’ll just try this and see how it goes.

One last point worth mentioning: all the nodes running this sketch can use the same group and node ID, because they are transmit-only. There is never a need to address packets sent towards them. So the BLIP_ID inside the payload is a way to still disambiguate incoming packets and understand which exact node each one came from.

Re-using the same node ID is useful in larger setups, since the total number of IDs in a group is limited to 30.

I’ll do some tests with the above logic. Let’s hope this will keep nodes alive in long and dark winter days nights.

Re-thinking solar options

In AVR, Hardware, Musings on May 28, 2012 at 00:01

So will it ever be possible to run a JeeNode or JeeNode Micro off solar power?

Well, that depends on many things, really. First of all, it’s good to keep in mind that all the low-power techniques being refined right now also apply to battery consumption. If a 3x AA pack ends up running 5 or even 10 years without replacement, then one could ask whether far more elaborate schemes to try and get that supercap or mini-lithium cell to work are really worth the effort.

One fairly practical option would be a single rechargeable EneLoop AA battery, plus a really low-power boost circuit (perhaps I need to revisit this one again). The idea would be to just focus on ultra-low power consumption, and move the task of charging to a more central place. After all, once the solar panels on the roof of JeeLabs get installed (probably this summer), I might as well plug the charger into AC mains here and recharge those EneLoop batteries that way!

Another consideration is durability: if supercaps only last a few months before their capacity starts to drop, then what’s the point? Likewise, the 3.4 mAh Lithium cell I’ve been playing with is rated at “1000 cycles, draining no more than 10% of the capacity”. With luck, that would be about three years before the unit needs to be replaced. But again – if some sort of periodic replacement is involved anyway, then why even bother generating energy at the remote node?

I’m not giving up yet. My KS300 weather station (868 MHz OOK, FS20’ish protocol) has been running for over 3 years now, I’ve never replaced the 3x AA batteries it came with – here’s the last readout, a few hours ago:

     :41   KS300 ookRelay2 humi             77
     :41   KS300 ookRelay2 rain             469
     :41   KS300 ookRelay2 rnow             0
     :41   KS300 ookRelay2 temp             18.2
     :41   KS300 ookRelay2 wind             0

And the original radioBlip node is also running just fine after 631 days:

    1:32   RF12-868.5.3 radioBlip age       631
    1:32   RF12-868.5.3 radioBlip ping      852330

Even the JeeNode Micro running on a CR2023 coin cell is still going strong after 4 months:

    1:42   RF12-868.5.18 radioBlip age      139
    1:42   RF12-868.5.18 radioBlip ping     188449

So ultra-low power is definitely doable, even with an Arduino-compatible design.

No worries – I’ll keep pushing this in various directions, even if just for the heck of it…

Reverse diode current

In Hardware on May 27, 2012 at 00:01

After measuring the forward voltage drop over a diode, I should also have measured the reverse leakage current, i.e. how much current the diode lets through when it’s supposed to be blocking. I never did until now, because I couldn’t detect any current in a quick check I did a while back. Time to build a better setup – here’s what I used:

JC s Grid page 17

The voltmeter’s own 10 MΩ or so internal resistance will skew the readings by 10%, but that’s no big deal.

It turns out that the reverse leakage current is pretty small when applying 5V:

  • 1N4004 – a high power diode: 1.3 mV = 1.3 nA
  • 1N4148 – a low power diode: 3.4 mV = 3.4 nA
  • BAT34 – a Schottky diode: 50 mV = 50 nA

That’s nanoamps, i.e. milli-milli-milli-amps. The Schottky diode does indeed leak a tad more than the others. Here are the specs of that BAT34 diode – note that the reverse current could even be used as temperature sensor!

Screen Shot 2012 05 14 at 17 15 55

FWIW, I found a minuscule “RB751S” SMD Schottky diode, about 1 mm long, which does a bit better at 7.0 nA:

DSC 3221

It was quite a challenge to get some wires soldered onto it. I used the core of 30 AWG Kynar “wirewrap” wire:

DSC 3222

Anyway – the BAT34 is good enough: 50 nA leakage is acceptable while dealing with circuits which consume µA’s.

Through the night on a supercap!

In Hardware on May 26, 2012 at 00:01

Yeay! – The JeeNode made it through the night on a 0.47F supercap, for the first time ever at JeeLabs:

Screen Shot 2012 05 15 at 10 59 19

Sorry for the awkward / missing scale, here’s some context:

  • vertical is voltage: 50 = 2V, 100 = 3V, 150 = 4V, 200 = 5V
  • blue is VCC before sending, green is VCC after sending
  • graph runs from 11:45 yesterday to 10:45 the next morning, i.e. 23 hours
  • that’s two VCC measurements and one packet transmission every minute

The supercap had been charged by the solar cell for 3 days, no load. When connecting the JeeNode (BOD set to 1.8V, on-board 100 µF i.s.o. regulator, already running), I placed it in a cardboard box to block out the light:

  • the first upward blip is at 12:45, during 5 minutes of exposure to sunlight
  • then back into the box until 18:30, depleting the supercap for a few hours
  • after that, the node was kept in the light to try and charge up enough for the night
  • at 20:00, the charge had gone up to 4.42V and 3.86V, respectively
  • at around 6:30 the next morning, the lowest point was reached: 3.44V and 2.88V
  • from then on, the cell started charging again from the morning light (no direct sunlight yet)
  • looks like about 10% of the packets never arrived (probably mostly due to collisions)

At noon, the cap voltage had risen to 4.9V (note that the RFM12B is now operating above its official 3.8V max).

So there you have it: one packet per minute powered by solar energy, harvested indoor near a window.

Update – FWIW, this setup lasted a second day, but then it died again… we’re not done yet!

Different op-amps

In Hardware on May 25, 2012 at 00:01

One last experiment I wanted to do after the recent sine wave circuits, was to compare a few different op-amps.

I’m including the original one here as well – the LM358, running at ±13.6V:

SCR64

Here’s the LT1413, running at ±14.4V:

SCR65

And here’s the NE5532ANG, running at ±15.3V:

SCR66

In each case, the supply voltage was adjusted until the output sine wave was ±10 V, with all other components identical. Note the slight difference in oscillation frequency.

What’s also interesting, is the mean output voltage: it should be 0V with an ideal circuit. Looks like the NE5532ANG performs best – within 1%. It’s described as being an “Internally Compensated Dual Low Noise Operational Amplifier”. Second harmonic is at -51 dBm, i.e. 0.28% harmonic distortion – an excellent signal!

As a quick test with that last op-amp, I reduced the supply voltage to ±2.5V – the effect was a slightly higher frequency of 522 Hz, a much lower output of 2.14 Vpp, i.e. ±1.07V, but relatively far off-center: 240 mV. Harmonic distortion rises to 3.5% in this case. But that’s not surprising: the NE5532ANG is only specified down to ±3V, and it’s not a “rail-to-rail” op-amp, which means it cannot generate an output voltage too close to its supply voltage (with a ±5V supply, distortion drops back to 1.25%).

Lots of op-amps. Lots of trade-offs.

Ok enough op-amp chit-chat for now, I’ll stop :)

TK – Frequency Meter

In Hardware on May 24, 2012 at 00:01

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

Another post about frequencies – this time I’ve assembled a DFD4A from Almost All Digital Electronics:

DSC 3124

It’s a low-cost frequency counter which goes all the way up to 3 GHz. Here it’s measuring a 10 MHz signal from my Frequency Generator, while synchronized to the Rubidium frequency standard.

As you can see, it’s spot on – the last digit flips between 0 and 1 every so often, that’s all.

As with the Capacitance Meter I assembled recently, this kit comes with detailed build instructions. Except that this time I didn’t really want to build it, so I got the pre-built version instead, including the connectors and (fully) plastic enclosure. The front plate already has all the right cutouts, and a printed piece of paper (!) glued to the front. Works ok, but I suspect that it’ll get dirty over time.

The unit came with all the parts, I just had to solder a few components and wires in place after inserting all the switches and BNC connectors.

One thing missing was the 9V battery clip – but not to worry, I have a couple of those lying around anyway.

The reason to get this particular unit was its high frequency range of well over the 868 MHz and 2.4 GHz frequencies I may want to measure here at JeeLabs. The main difference with a professional unit is probably the fact that it doesn’t have many input signal options:

  • HF measures from 0 to 30 MHz, with 5 Vpp max into a high impedance input
  • UHF measures from 10 to 3000 MHz over a 50 Ω input (max 15 dBm)

No way to directly measure the 868 MHz output from an RFM12B, I suspect – i.e. it probably won’t be sensitive enough to measure 0 dBm.

The slow measurement mode continuously collects data for one second, so you get 1 Hz resolution on the HF range and 100 Hz resolution on the UHF range (since that’s essentially just a ÷ 100 prescaler).

The fast measurement mode runs 10 times per second, i.e. a gate time of 0.1s – so this gives 10 Hz resolution on HF and 1000 Hz (1 KHz) resolution on UHF.

It’s a bit odd that the display shows more significant digits than are being measured in all but FAST + HF mode, but no big deal – the current mode is clearly visible from the switch settings.

Knowing that the counter is very accurate (for now – it’ll no doubt gradually drift slightly), it’s time to find out how accurate the TG2511 AWG’s frequency is when not synchronized to the Rubidium standard:

DSC 3125

That’s only 0.4 ppm off and well within spec – excellent!

TD – LED flashlight

In Hardware, News on May 22, 2012 at 00:01

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

Today’s episode will be a short one, it’ll become clear why halfway down this page…

This is a little bargain LED flashlight, nothing to it really:

DSC 3228

Three AAA (not AA) cells, a toggle button, 24 + 4 white LEDs, and that’s it. Press the button once, and the 4 LEDs on the side turn on, press again to light the 24 on the top, and again to turn it off.

Quite a bright light BTW. The 4 LEDs draw 190 mA, with 16 it rises to 270 mA. That’s perhaps 4 hours of use with 16 LEDs before the batteries run out.

The circuit is as ridiculously simple as can be – one 4.7 Ω resistor and a switch:

DSC 3229

That “metal” reflector is actually plastic with a chrome finish. The PCB is one-sided, no doubt to lower the cost:

DSC 3230

(it won’t take much bending to create a short with that top wire!)

Using Ohm’s law (V = I x R), we can deduce that the LED’s forward voltage is 4.5 – X = 0.190 x 4.7 – in other words, X = 4.5 – 0.190 x 4.7 = 3.6V. Note that the light intensity will vary considerably with battery voltage and that this lamp won’t work at all with 3 AAA EneLoop batteries which only supply 1.2V to 1.3V when fully charged.

The reason I’m opening up this trivial little gadget is not to marvel at the deep electronic engineering that went into it, but to show how custom plastics and a custom case makes something quite practical and nice to the touch. The top and bottom have a rubbery feel to them. The bottom has a little plastic hook in it, which can be folded out.

The bigger news today is a bit of a mess, unfortunately.

Last night I decided to upgrade the JeeLabs server from Mac OSX 10.7.3 to 10.7.4 – that update had been out for a few days, worked fine on two other machines here, so it seemed safe to apply the update to the server as well.

It failed.

This server is connected via wired Ethernet, and I usually only look at the GUI via a VNC-like “Screen Sharing” mechanism built into Mac OSX. It works well, because that connection is re-established even when the machine is in an exclusive “Updating…” mode, so you get to track progress even while the system is busy replacing some of its own bits and pieces. No screen needed, even though part of admin interface sometimes uses the GUI.

Last night, the server failed to come back online. Which is a major hassle, because then I have to move it to another spot to hook up a mouse, keyboard, and monitor to see what’s going on. Never happened before.

Trouble is (probably), that I turned the darn thing off forcefully. I knew that all the VM’s had been properly shut down, and I heard the characteristic reboot “pling”, so I thought it was waiting for a GUI response… or something.

Then the trouble started. Hooked it up, did a restart: no go. So I restarted it in recovery mode, and did a disk check/repair of all the disks. Guess what: the startup disk with all VM’s could not be repaired… whoops!

Time to kick my backup strategy in gear. I have two in place: local hourly Time Machine backups to a second drive, and daily backups for all VM’s to the cloud.

To make a very long night story short: the local hourly backups are fine, but they do not include the VM’s (whole-file backups of a VM disk every hour is not really practical). And the daily backups? Well, they are indeed all there – I can get any day in the past 3 months back, for any of the 4 VM’s. Awesome.

But Turnkey Linux does things a bit differently. Very clever in fact: it only backs up the minimum. The Linux Debian packages for example: these are not backed up, but re-installed from some other source. The rest is a well thought-out mix of full and incremental backups, and it all works just as expected.

Except that my VM’s are about two years old now, and no longer the latest base images used by Turnkey Linux. No problem, they say: you can get the latest, and then recover your own stuff on top of that.

So I spent about 6 hours trying to work out how to get my VM’s back up from the Amazon S3 storage. No joy. I can see all the files being restored, but the result is not a working VM. At some point, package installs & updates hang, with either udev restart problems or bootdisk image generation problems.

And now the crazy bit: the JeeLabs weblog + forum + café sites are all back up again (phew!). I restored from Time Machine to a freshly freed disk partition, and restarted the Mac – it’s alive! Right now, the server is running from the new disk partition, but with the 4 VM disk images still on the damaged partition. So apparently they did not get any damage, although the Mac file system structure on that disk seems to be hosed.

I’ll spend some time thinking about how to clean up this mess, and how to avoid it in the future. The good news is that I lost no data – just a lot of time and some hair. Yikes … this really was uncomfortably close to the edge!

The moral: test the backup strategy regularly. It can still break, even when not changing anything!

Update – All systems are “go” again.

Update 2 – Final diagnosis: one of the 2 internal disks was getting too hot, leading to intermittent failure, so it was hardware after all – unrelated to the 10.7.4 software. And it was probably all my fault, because I placed a (fairly warm) router on top of the Mac Mini. I’m going to replace the failed system drive with with an SSD.

Producing a beefier signal

In Hardware on May 21, 2012 at 00:01

Let’s move on, now that we have a clean sine wave. The goal is to produce a ±10V sine wave to use for constructing a Component Tester. The sine wave produced so far was merely ±65 mV.

I re-used the same circuit as yesterday, but with slightly different settings. First of all, I replaced the op-amp by an LM358, which can handle higher voltages. Next, I halved all the R’s to 5 kΩ and doubled all the C’s to 0.2 µF. This reduces the loading of the feedback loop – it shouldn’t really affect the frequency.

To increase the output voltage, I connected the oscillator output signal to a non-inverting op-amp circuit:

Screen Shot 2012 05 13 at 18 04 33

In a nutshell: this circuit tries to keep Ve as close to zero as possible at all times. IOW, the op-amp will constantly adjust its output so that the tap on the Rf:Rg voltage divider tracks the Vin voltage on the “+” input pin.

Using Rf = 10 kΩ, and Rg = 470 Ω, its gain will be about 22x. The nice property of this circuit is that it has a very high input impedance, so there is virtually no current draw from the oscillator.

And sure enough, the output of this op-amp is a sine wave with many volts of output swing. Now it’s simply a matter of cranking up the supply voltages to ±13.6V and bingo, a ±10V sine wave:

SCR64

Very clean. Better even than the original circuit – the 2nd harmonic is now -49 dB w.r.t. to the base frequency. That’s just 0.35% of harmonic distortion – excellent!

That second op-amp came for free, since an LM358 DIP-8 package has two of them anyway. So the first op-amp is oscillating (at about 470 Hz) and the second op-amp brings the output level to ±10V.

It’s quite a mess on the mini-breadboard I used, but who cares – that’s what prototypes are for:

DSC 3215

One last check is needed to make sure that the LM358 is suitable. A component tester measures the effects of an unknown component in series with a 1 kΩ resistor. So in the worst case, with a simple wire as “unknown component”, the maximum current through that resistor will be ±10 mA. Luckily, according to the specs, an LM358 can supply at least 10 mA, and typically up to 20 mA on its output.

So that’s it: our Component Tester will need a ±13.6V supply, an LM358, and a few R’s and C’s. That supply voltage is not critical, as long as it’s stable – the output level could be adjusted to ±10V via a trimpot.

Welcome to the world of analog electronics!

A better sine wave

In Hardware on May 20, 2012 at 00:01

After the pretty bad sine wave trial of the last two days, it’s time to try another circuit:

Screen Shot 2012 05 13 at 15 55 30

This is a “Phase Shift Oscillator” from the same op-amp book as the other one. I used half a TLV2472.

This one is actually a bit simpler to explain: the op-amp is set up with 25..50x amplification, i.e almost a comparator (with 50x amplification, a 50 mV input above or below the 2.5V will drive the output to its limit). And indeed, the output signal of the op-amp looks somewhat like a heavily clipped sine wave:

SCR59

The 3 resistors and 3 capacitors create 3 RC “low-pass” filters in series, removing all the higher frequencies, i.e. harmonics. A fairly clean sine wave comes out at the end, as you can see here:

SCR58

The only problem is that the signal level has been reduced from a ±2.5 V level to ≈ ±65 mV, a 40-fold reduction!

So the op-amp itself has to amplify that level back up to produce the clipped ±2.5V signal again.

The frequency is determined by “phase shifts”. Each RC filter changes the phase of its input signal, and it will be by 60° at a certain frequency, so that 3 of them in series will then shift it by 180°. Since the signal is fed back to the “-” pin of the op-amp, that’s exactly the proper signal to generate the opposite output, i.e. shifted 180° out of 360°. This analog stuff gets complicated – don’t worry too much about it: just pick R and C values to get the right frequency, and make all of them the same.

I used 0.1 µF caps i.s.o. 10 nF caps, i.e. 10x larger than the original circuit. With these values, the oscillation in my setup turned out to occur at just about 440 Hz, i.e. a pure musical “A” tone!

I did have to increase the gain (1.5 MΩ / 55.2 kΩ = 27 in the above setup) to force oscillation. I changed RF to 1 MΩ and RG to 22 kΩ, for a gain of 47. This RG value is a bit low, it loads down the last RC section quite a bit.

What you’re seeing here is a classical example of a negative feedback loop, which ends up in a very stable state of oscillation. It oscillates because we’re delaying the feedback signal by about 2.27 ms through the RC chain. So the op-amp constantly overshoots around its mid-point (the 2.5V applied to the “+” input), but does so in a very controlled way. The amplitude can’t increase any further, since the op-amp is clipping at its limits already, and the amplification factor is large enough to keep boosting the swing up to that limit. You can see the startup ramp and stabilization when powering up:

SCR61

Here’s the FFT spectrum analysis of the generated sine wave:

SCR60

A clean signal compared to the previous experiment. The 2nd harmonic is ≈ 42 dB below the fundamental wave, the rest is even lower. Using this calculator, we can see that this represents about 0.8% harmonic distortion.

The only issue is that the signal is much weaker than the ±10V needed for a standard Component Tester.

But hey, let’s declare success for now – we’ve got a clean sine wave!

Generating a sine wave – part 2

In Hardware on May 19, 2012 at 00:01

After yesterday’s failed attempt to generate a clean since wave, I started experimenting a bit further. How could the Op-amp book be so wrong about the quadrature oscillator circuit?

The nice thing about op-amps in DIP-8 packages, is that most of them use the same pinout, so it’s very easy to swap them out and test different brands and types. The TLV2472 only supports up to 6V as power supply, most of the other ones go much higher – usually above 30V, i.e. ±15V.

Here’s the list of op-amp chips I tried (yeah, got quite a bunch of them in my lab, for various reasons):

  • TLV2474
  • LM358N
  • LM833N
  • NE5532ANG
  • OP2340
  • NJM14558D
  • MCP6023
  • LT1413

All of them had similar behavior, i.e. clipping at both limits of the voltage range, except for the LT1413:

SCR56

Still nowhere near a sine wave, BTW. But what’s more interesting, is the the voltage swing of this signal was just 4.5 Vpp, while the op-amp was being driven from a ±15V power supply in this particular case. So for some reason, it was “oscillating” at 1.25 KHz (about 8x higher than the other mode).

I have no idea what was going on. When trying to reproduce this a second time, I couldn’t get this behavior back. I suspect a loose connection, or perhaps some odd interaction due to the breadboard.

I’m not really interested in tracking down this issue, since it looks like this quadrature oscillator circuit is not suitable for a Component Tester – not without some sort of amplitude regulation anyway.

So there you have it – analog circuits also need to be debugged, as you can see!

Update – this issue has now been resolved, see the comments on yesterday’s weblog post.

Generating a sine wave

In Hardware on May 18, 2012 at 00:01

After the recent pretty disappointing results with a transformer-based Component Tester, I’d like to try and generate a ± 10 V sine wave at approximately 50 Hz in some other way. Using as few components as possible.

This is where we enter, eh, squarely into the analog electronics domain. Yes, we could generate it with an ATmega, but frankly that sounds like a bit of overkill, would require a fair amount of filtering to remove residual switching effects, and besides we’d still have to amplify it up to 10 Vpp.

Time to introduce some new circuitry!

One of the most incredible electronic building blocks invented in the second world-war era was the Operational Amplifier, or “op-amp” in short.

There’s way too much to say about this amazingly universal circuit, which even has its own schematic symbol:

180px Op amp symbol svg

A positive and negative power supply pin, a positive and a negative input, and an output pin. That’s it.

I’ve only just started exploring op-amps, really – one superb resource on the web comes in the form of a free eBook from 2002 on the Texas Instruments site, titled “Op Amps For Everyone”, by Ron Mancini.

In his chapter on Sine Wave Oscillator, he mentions a “Quadrature Oscillator” built from two op-amps:

Screen Shot 2012 04 18 at 01 08 17

It uses very few components. This one was dimensioned for about 1.6 KHz, so I started with capacitors ten times as large, i.e. 0.1 µF, to lower the oscillation frequency. Here’s the result, using a TLV2472 dual op-amp:

DSC 3056

Powered by a supply of ±2.5V (i.e. 0 / 2.5V / 5V), I see this result on the scope, when attached to the sine output:

SCR53

Yeah, right. Clipping like crazy, i.e. overshooting into the limiting 0V and 5V power lines. The FFT shows it’s not anywhere near a pure sine wave, even though the shape vaguely resembles one:

SCR54

A pure sine wave would have a single peak at the oscillating frequency.

Here’s the cosine output, again showing that it’s running way outside its linear range:

SCR52

So yeah, we’re generating a 160 Hz signal, but it’s no sine wave and it would be useless as Component Tester.

Oh well, it was still an interesting first trial!

TK – Frequency accuracy

In Hardware on May 17, 2012 at 00:01

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

(this is again a bit of a side excursion, about checking the quality of a measuring instrument)

I recently visited a friend who had to get his frequency meter’s calibration verified to a fairly high precision. Thinking of the Rubidium clock I got from eBay, he came up with the idea of using a transfer standard.

The thing with accuracy, is that you have to have an absolute reference to compare against. One option is to go to a “calibration lab” and have them test, adjust, and certify that your instrument has a certain accuracy. Awkward, expensive, and usually a bit over the top for “simple” hobby uses.

So the other way to do things, is to “transfer” the calibration in some way. Buy or build a device which can keep the desired property stable, calibrate it to some standard, move it to where the instrument needing calibration is located, and compare the two. Or vice versa: match to instrument, then compare with a standard.

The latter is exactly what we ended up doing. First we created a little Arduino daughter board with a “VC-TCXO” on it: that’s a “Temperature Compensated Xtal Oscillator” which can be fine-tuned through a voltage. Here’s the setup, created and built by Rohan Judd:

DSC 3082

On the left, an SPI-controlled digital potmeter, on the right a VC-TCXO running at 10 MHz.

Via a sketch, the VC-TCXO was fine-tuned to produce exactly 10.000,000 MHz readout on the frequency counter we wanted to verify. This was done at about 18°C, but a quick test showed that this VC-TCXO was indeed accurately keeping its frequency, even when cooled down by more than 10°C.

I took this device back home with me, and set up my frequency generator to use the Rubidium clock as reference. So now I had two devices on my workbench at JeeLabs, both claiming to run at 10 MHz …

Evidently, they are bound to differ to some degree – the question was simply: by how much?

Remember Lissajous? By hooking up both signals to the oscilloscope, you can compare them in X-Y mode:

SCR26

Channel 1 (yellow) is the VC-TCXO signal, some sort of odd square wave – I didn’t pay any attention to proper HF wiring. Channel 2 (blue) is the sine wave generated by the frequency generator.

The resulting image is a bit messy, but the key is that when both frequencies match up exactly, then that image will stay the same. If they differ, then it will appear to rotate in 3D. It’s very easy to observe.

The last trick needed to make this work is simply to adjust the frequency generator until the image does indeed stop rotating. This is extra-ordinarily sensitive – the hard part is actually first finding the approximate setting!

After a bit of searching and tweaking, and after having let everything warm up for over an hour, I got this:

DSC 3080

IOW, the frequency I transferred back to JeeLabs with me was 9.999,999,963 MHz. We’re done!

To put it all into perspective: that highlighted digit is 0.1 ppb (billion!). So the frequency counter appears to be 3.7 ppb slow. Assuming that the transfer standard did not lose accuracy during the trip, and that my Rubidium clock is 100% accurate. Which it isn’t of course, but since its frequency is based on atomic resonance properties, I’m pretty confident that it’s indeed accurate to more than 0.1 ppb.

The real story here, though, is that such breath-taking accuracy is now within reach of any hobbyist!

First solar results

In AVR, Hardware on May 16, 2012 at 00:01

Some first results from trying to run a JeeNode off a 24 x 32 mm indoor solar cell…

In each of the cases described below, I’m using a JeeNode without regulator and with 100 µF cap hooked up, with fuses and settings as described in this post. The cap should have enough energy to cushion the dip from a small packet transmission. I’m using the latest radioBlip2 sketch, which now sends out the following 7-byte payload:

Screen Shot 2012 05 14 at 13 33 17

The benefit of this version, is that the sketch reports not just the battery level but also how far the battery level drops after sending out a packet once a minute. That value is sent out in the next packet, so it always lags.

To get started, I connect the JeeNode to a BUB, which charges the 100 µF cap to 5V (and runs the RFM12B slightly above spec). Then I disconnect and hook it up to the solar setup. This way I don’t have to deal with startup problems yet – which is an entirely different (and tricky) problem.

Yesterday’s elaborate setup didn’t get very far, unfortunately. Two different runs gave me just a few packets:

    L 09:16:01.571 usb-A600dVPp OK 17 1 0 0 0 1 209 0
    L 09:18:07.445 usb-A600dVPp OK 17 3 0 0 0 1 86 51
    L 09:19:10.308 usb-A600dVPp OK 17 4 0 0 0 1 86 50

    L 09:24:12.477 usb-A600dVPp OK 17 1 0 0 0 1 206 0
    L 09:25:15.707 usb-A600dVPp OK 17 2 0 0 0 1 86 210

Values are 20 mV steps, offset by 1V – the actual battery voltage is: 1 + 0.02 * X (where X is the reported value).

In the above runs, the battery is 86 (2.72V) before sending, and 50 (2.00V) after. That’s pretty close to the edge, I’m not sure why the drop is so large.

Another test with a 0.47 Farad supercap, charged for about 3 days to get the charge “deep” into the supercap, seems to fare a little better:

    L 09:43:06.943 usb-A600dVPp OK 17 19 0 0 0 1 210 52
    L 09:44:10.771 usb-A600dVPp OK 17 20 0 0 0 1 175 210
    L 09:45:14.549 usb-A600dVPp OK 17 21 0 0 0 1 175 146
    L 09:46:18.339 usb-A600dVPp OK 17 22 0 0 0 1 175 147
    L 09:47:22.100 usb-A600dVPp OK 17 23 0 0 0 1 175 147
    ...

That’s 4.50V and 3.94V before and after transmission, respectively. But a 0.47F supercap has a lot less energy in it than that 3.4 mAh Lithium cell used in the first tests above, so it’ll probably run down a lot faster.

After one hour, voltages drop to 4.28V and 3.72V. Two hours: 4.14V and 3.60V. Five hours: 3.92V and 3.36V. I’m not sure this will work, unless the node sends less at night perhaps or always restarts reliably the next day.

To be continued…

New solar setup

In Hardware on May 15, 2012 at 00:01

Time for another experiment, this time combining my small solar panel with the 3.4 mAh Lithium battery which seems to work so well. The circuit I’m going to try is as follows:

JC s Grid page 16

Here’s the construction, cozily attached to the back of the solar cell:

DSC 3128

Same solar cell, I think it can supply up to 4.5V @ 1 mA in full sunlight.

The tricky bit is that the rechargable lithium cell needs to be treated with care. For maximum life, it needs to be hooked up to a voltage source between 2.8V and 3.2V, and the charge current has to be limited.

Note that the 1 kΩ resistor is put in series with the battery not only to charge it, but also when taking charge out of it. Seems odd, but that’s the way the datasheet and examples show it. Then again, with a 10 µA current draw the voltage drop and losses are only about 10 mV. A diode bypass could be added later, if necessary.

The diode after the regulator has the nice effect of dropping the 3.3V output to an appropriate value, as well as blocking all reverse current flow. There is no further circuitry for the regulator, since I don’t really care what it does when there is too much or too little power coming from the solar cell. Let’s assume it’s stable without caps.

It all looks a bit wasteful, i.e. linearly regulating the incoming voltage straight down to 3.3V regardless of PV output levels and discarding the excess. But given that this little 3V @ 3.4 mAH battery has already supported a few days of running time when fully charged, maybe it’s still ok.

I’ll let this charge for a day or two.

Forward voltage drop on a diode

In Hardware on May 14, 2012 at 00:01

With all this tinkering with solar panels, little batteries, supercaps, etc, you often need to prevent current from leaking away. The usual approach is to insert a diode into the circuit.

Diodes conduct current in one direction and block the current in the opposite direction.

Well, that’s the theory anaway. In real life, diodes only conduct current once the voltage is above a certain level, and they tend to leak minute amounts of current when blocking the reverse voltage.

For ultra-low power use and the low voltage levels involved, you need to be careful about the type of diode used. A regular 1N4148 silicon diode has a forward drop of about 0.65V, quite a bit when supplies are 2..3V!

The Schottky diode has a much lower voltage drop. It’s usually specified as 0.3..0.4V, but it really depends on the amount of current passed through it.

To see the properties of the BAT43 Schottky diode I’ve been using, I created this simple test setup:

JC s Grid page 18

A 10 Hz “sawtooth” voltage is used to create a signal rising from -3V to +3V in a linear fashion, 10 times a second. This means that the current through the 100 kΩ resistor will go from -30 µA to +30 µA. We can then watch the voltage over the diode, and how it goes from a blocking to a conducting state:

SCR45

The yellow trace is the sawtooth signal applied to the circuit. The blue trace is the voltage over the diode. Note the difference in vertical scale.

You can see that with negative voltages, the diode just blocks. As it should. With positive voltages up to 1.2V, i.e. a current up to 12 µA, the voltage drop over the diode is under 0.15V, rising slowly to about 0.175V at 30 µA.

Changing the resistor to 10 kΩ to increase the current by a factor of 10, we get this:

SCR49

Same picture, different scale. At 300 µA, the voltage drop is now about 0.23V, and it’s fairly flat at that point.

For comparison, here’s a run-off-the-mill 1N4148 “standard” silicon diode:

SCR50

Again: different vertical scale. About 0.53V at 300 µA. More importantly, it’s already 0.4V at 60 µA.

So when losses matter at low voltages and low currents, it’s better to use Schottky diodes.

Watching it go down

In AVR, Hardware, Software on May 13, 2012 at 00:01

Now that there’s low-power vccRead() code to measure the current power supply voltage, we can finally get a bit more valuable info from the radioBlip sketch, which sends out one packet per minute.

So here’s a new radioBlip2 sketch which combines both functions. To support more test nodes, I’m adding a byte to the payload for a unique node ID, as well as a byte with the measured voltage level:

Screen Shot 2012 05 09 at 18 28 02

As a quick test I used a JeeNode without regulator, running off an electrolytic 1000 µF cap, charged to 5V via a USB BUB, and then disconnected (this is running the RFM12B module beyond its 3.8V max specs, BTW):

DSC 3127

Here’s a dump of the received packets:

    L 16:56:32.032 usb-A600dVPp OK 17 1 0 0 0 1 209
    L 16:57:35.859 usb-A600dVPp OK 17 2 0 0 0 1 181
    L 16:58:39.543 usb-A600dVPp OK 17 3 0 0 0 1 155
    L 16:59:43.029 usb-A600dVPp OK 17 4 0 0 0 1 134
    L 17:00:46.323 usb-A600dVPp OK 17 5 0 0 0 1 115
    L 17:01:49.431 usb-A600dVPp OK 17 6 0 0 0 1 98
    L 17:02:52.314 usb-A600dVPp OK 17 7 0 0 0 1 82
    L 17:03:55.016 usb-A600dVPp OK 17 8 0 0 0 1 66
    L 17:04:57.526 usb-A600dVPp OK 17 9 0 0 0 1 50

Or, more graphically, as voltage – showing 8 minutes before the sketch runs out of juice:

Screen Shot 2012 05 09 at 19 06 19

This consumes only marginally more power than without the VCC measurements: the original radioBlip sketch lasted 1 minute longer under similar conditions, i.e. one extra packet transmission.

TK – Voltage accuracy

In Hardware on May 10, 2012 at 00:01

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

(this is a bit of a side excursion, about checking the quality of a measuring instrument)

“Ah, but is it any good?” – that’s the inevitable question to ask when getting a precise instrument, right?

I’m referring to the 6.5 digit 34401A HP (now Agilent) multimeter I got my hands on, recently. This translates to: better than 1 ppm (part per million), i.e. 10,000 times more accurate than one percent!

This is the sort of thing the members of the volt-nuts mailing list ponder about, I would imagine.

In my case, with now over half a dozen ways to measure voltage here (numerous hand-held multimeters, mostly), I just wanted to know which one to trust most and to what extent.

The solution comes in the form of a transfer voltage standard – an item you can order, gets shipped to you, and which then gives a certain level of confidence that it will provide a fixed voltage reference. As it turns out, Geller Labs offer just such a thing at low cost – it’s called the SVR 2.0:

DSC 3078

Put 15V on its input (left), wait 30 min, and the output pins (right) will produce exactly 10.00000 Volt – magic!

Each board is “burned in” (kept turned on) for 200 hours and calibrated at the temperature you specify (I asked for 21°C). You even get the measured temperature coefficient at that spot (mine is 1.7 ppm/°C), so you can in fact predict the voltage it will generate at a slightly different temperature. Now that’s serious calibration!

My bench-top multimeter will indeed go down to 1 ppm in 6-digit mode, i.e. steps of 10 µV when measuring 10 V:

DSC 3079

And guess what – after a 30-minute warm-up (both the 34401A and the SVR), it’s spot on.

No last-digit jitter, nothing. A constant 10.000,00 readout. The current room temperature is 21.1°C, heh.

Think about it for a second: as hobbyist, you can order a precision second-hand instrument from eBay, Google around a bit to find a little voltage standard, have ‘em shipped from different parts of the planet, get them here within two weeks, hook up some wires, wait 30 minutes, and they match to 0.000,1 % precision.

Given that this instrument is from the 90’s, I’m massively impressed. This 34401A HP thing rocks!

Voltage? Current? Resistance? Game over – for me, this is more than enough precision for serious use.

Not long enough

In Hardware on May 9, 2012 at 00:01

My second solar setup did not fare well:

DSC 3086

Started during the day, with the supercap charged up in bright daylight behind a window, it was able to power the JeeNode for about 16 hours – and then in the middle of the night it gave up:

    L 02:36:44.743 usb-A600dVPp OK 17 30 4 0 0
    L 02:37:48.074 usb-A600dVPp OK 17 31 4 0 0
    L 02:38:51.402 usb-A600dVPp OK 17 32 4 0 0
    L 02:39:54.725 usb-A600dVPp OK 17 33 4 0 0

Times are in UTC and we’re in the CEST time zone, so this was two hours later – i.e. around 4:30 AM.

I left it there for another few days, but unfortunately once dead this setup never recovers. The main reason for this is probably that the RFM12B starts up in a very power hungry mode (well, relatively speaking anyway) with a 0.6 mA current consumption – because it starts with the crystal oscillator enabled.

Maybe the self-leakage of the supercap was still too high, and would be (much) lower after a few days in the mostly-charged state, so I’m not ruling out using supercaps just yet. But as it stands, not getting through even a single night is not good enough – let alone being used in darker spots or on very dark winter days.

More experimentation needed!

TD – Soldering iron

In Hardware on May 8, 2012 at 00:01

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

Today, I’m going to take a quick peek inside the soldering iron from Conrad, which was suggested as low-end soldering option for a first toes-in-the-water electronics toolkit:

Opening up the base is trivial, just remove 4 screws after taking off a couple of rubber caps:

DSC 3123

On the right: the AC mains feed, with 2 live/neutral wires and the green/yellow ground.

On the bottom: again 2 wires plus the green/yellow ground (as crucial safety feature).

First thing to remark is that there is no temperature sensor in the soldering iron. In other words, this is an adjustable unit, but it’s not temperature-controlled – the 150..450°C scale around the rotating knob is bogus.

Just removing the knob and a washer around the potmeter is enough to examine the board up close:

DSC 3121

A couple of resistors, caps, an inductor, and a little transformer – that’s all. Oh, and a little TRIAC in a TO-92 housing (just beneath the transformer). Here’s the other side:

DSC 3122

A plain single-sided low-cost PCB. No surprises here – this is a very low-cost unit, after all.

So how does it work? Well, it’s basically a simple dimmer. But instead of dimming an incandescent lightbulb, it dims the heater coil inside the iron. The way this works is that the start of each AC mains cycle gets switched off – and then only after a specific time does the TRIAC start conducting. The whole circuit is essentially an adjustable delayed pulse generator, synchronized to the AC mains zero crossings.

Here’s what it looks like on the scope (as measured via a differential probe for isolation):

SCR33

The entire AC mains cycle is 20 ms (50 Hz), half a cycle is therefore 10 ms, and in this mid-range setting, each half of the sine wave is switched on after about 5 ms, i.e. halfway into the sine, at the peak voltage in this case.

Does it work? Sure, turning the knob will definitely adjust the tip temperature – but not very directly. Instead of a feedback loop, we merely control the amount of power going into the iron, and assuming a fairly steady heat dissipation, the iron will then stabilize more or less around a specific temperature. Just like a lightbulb, such a circuit will “dim” a soldering iron just fine this way.

The only drawback is that it’s not tightly controlled. When using the iron and pushing it against a thick copper wire or a big copper surface, the iron will cool off. Real temperature control requires a feedback loop which senses this change and counteracts the effect by pushing more power in when needed.

For simple uses, the crude approach is fine, but if you plan to solder under lots of different conditions (through-hole, SMD’s, PCB ground planes, thick copper wires) then a more expensive type might be more convenient.

How low can it go?

In AVR, Hardware on May 7, 2012 at 00:01

While experimenting with various alternate power sources for a JeeNode, I was curious as to just how low it could go in terms of voltage and still function as a simple wireless transmit node.

Made the following mods to push things a bit more than usual:

  • adjusted the fuses to set the brownout level to 1.8V iso 2.7V (efuse: 0x06)
  • changed the RFM12B’s low-battery level to 2.2V iso 3.1V (rf12_control: 0xC040)
  • removed the voltage regulator from a JeeNode, and keep just the electrolytic cap
  • changed the radioBlip sketch to run at 8 MHz, i.e. 16 MHz clock % 2

This is the same setup as with the Tiny Lithium discharge setup described a few days ago, BTW.

Here’s the JeeNode-under-test (JUT?) – the cap I used here is again 100 µF:

DSC 3070

One pair of wires is from the power supply, the other from the multimeter.

And then it’s just a matter of hooking it up to a power supply and gradually lowering the supply voltage.

And the result is … 3.0, 2.9, 2.8, 2.7, 2.6, 2.5, 2.4, 2.3, 2.2, 2.1, 2.0, 1.9, 1.85 Volt still works!

Anything lower than that and the sketch stops sending out packets once a minute – but then again, that’s probably just the brownout detector of the ATmega kicking in!

To get it back up, I re-connected the power supply at 2.1 V and the node started its blips again… lower didn’t work, my hunch is that the RFM12B’s clock circuit needs that slightly higher voltage level to start oscillating.

Measuring capacitance

In Hardware on May 6, 2012 at 00:01

Capacitors are all about storing and releasing charge. The main difference with batteries is that this charge is stored directly as electrical energy, whereas a battery converts to / from chemical energy in some form.

In an ideal capacitor, charge and discharge follow an exponential curve. Charging takes place when connected to a fixed supply via a resistor, discharging is a matter of placing a resistor across the capacitor:

Rc circuit 07

(image copied from www.technologyuk.net)

The “time constant” is the level when the discharge reaches 36.8% or the charge reaches 63.2% of the original voltage. It can be calculated using the formula: T (seconds) = R (ohm) x C (farad).

This property makes it easy to measure the value of a capacitor: charge it up to a known voltage, then discharge it through a known resistor and measure the time it takes for the voltage to drop to 36.8% of the original voltage.

This is the approach taken by this capacitance meter kit by Radio Hobby Store:

DSC 3084

There is excellent documentation including very detailed assembly instructions, leading to this:

DSC 3085

And sure enough, it works as expected – measuring a 10 µF cap in this case.

The only two drawbacks I found is that it doesn’t measure caps larger than 50 µF, and that there is no on-off switch. With a tool like this, you tend to want to use it from time to time and put it away after use. Without the switch, you have to disconnect the battery each time – a bit awkward and inconvenient.

This meter is based on a pre-flashed PIC controller. There’s one button to calibrate its zero value, and a convenient “auto-zero” mechanism, which keeps adjusting for exactly 0 pF when no capacitor is connected.

Measuring VCC via the bandgap

In AVR, Hardware, Software on May 4, 2012 at 00:01

The ATmega’s (and ATtiny’s for that matter) all have a 10-bit ADC which can be used measure analog voltages. These ADC’s are ratiometric, meaning they measure relative to the analog reference voltage (usually VCC).

On a 5V Arduino, that means you can measure 0..5V as 0..1023, or roughly 5 mV per step.

On a 3.3V JeeNode, the measurements are from 0 to 3.3V, or roughly 3.3 mV per step.

There’s no point connecting VCC to an analog input and trying to measure it that way, because no matter what you do, the ADC readout will be 1023.

So can we figure out what voltage we’re running at? This would be very useful when running off batteries.

Well, there is also a “bandgap reference” in each ATmega/ATtiny, which is essentially a 1.1V voltage reference. If we read out that value relative to our VCC, then a little math will do the trick:

  • suppose we read out an ADC value “x” which represents 1.1V
  • with 5V as VCC, that value would be around 1100 / 5000 * 1023 = 225
  • whereas with 3.3V as VCC, we’d expect a reading of 1100 / 3300 * 1023 = 341
  • more generally, 1100 / VCC * 1023 = x
  • solving for VCC, we get VCC = 1100 / x * 1023

So all we have to do is measure that 1.1V bandgap reference voltage and we can deduce what VCC was!

Unfortunately, the Arduino’s analogRead() doesn’t support this, so I’ve set up this bandgap demo sketch:

Screen Shot 2012 04 22 at 21 44 43

Sample output, when run on a JeeNode SMD in this case:

Screen Shot 2012 04 22 at 21 47 20

There’s a delay in the vccRead() code, which helps stabilize the measurement. Here’s what happens with vccRead(10) – i.e. 10 µs delay instead of the default 250 µs:

Screen Shot 2012 04 22 at 21 51 15

Quite different values as you can see…

And here’s the result on an RBBB with older ATmega168 chip, running at 5V:

Screen Shot 2012 04 22 at 21 53 44

I don’t know whether the 168’s bandgap accuracy is lower, but as you can see these figures are about 10% off (the supply voltage was measured to be 5.12 V on my VC170 multimeter). IOW, the bandgap accuracy is not great – as stated in the datasheet, which specifies 1.0 .. 1.2V @ 25°C when VCC is 2.7V. Note also that the bandgap reference needs 70 µs to start up, so it may not immediately be usable when coming out of a power-down state.

Still, this could be an excellent way to predict low-battery conditions before an ATmega or ATtiny starts to run out of steam.

TK – Equivalent Series Resistance

In Hardware on May 3, 2012 at 00:01

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

Equivalent Series Resistance, or ESR, is the resistance of a capacitor. Huh? Let me explain…

A perfect capacitor has a specific capacitance, no resistance, and no inductance. Think of a capacitor as a set of parallel plates, close to each other, but isolated. When you apply a voltage, electrons flow in on one side and electrons flow out on the other side until the voltage (potential difference) across the plates “pushes back” enough to prevent more electrons from flowing. Then the flow stops.

It’s a bit of a twisted analogy, but that’s basically what happens. A capacitor acts like a teeny weeny battery.

But no real capacitor is perfect, of course. One of the properties of a capacitor is that it has an inner resistance, which can be modeled as a resistor in series with a perfect capacitor. Hence the term “ESR”.

Resistance messes up things. For any current that flows, it eats up some of that energy, creating a voltage potential and more importantly: generating waste heat inside the capacitor.

ESR is something you don’t want in hefty power supplies, where big electrolytic capacitors are used to smooth out the ripple voltage coming from rectified AC, as provided by a transformer for example. With large power supplies, these currents going in and out of the capacitor lead to self-heating. This warms up the electrolyte in the caps, which in turn can dramatically reduce their lifetimes. Caps tend to age over time, and will occasionally break down. So to fix old electronic devices: check the big caps first!

Measuring ESR isn’t trivial. You have to charge and discharge the cap, and watch the effects of the inner resistance. And you have to cover a fairly large capacitance range.

This ESR70 instrument from Peak Instruments does just that, and also measures the capacitance value:

DSC 3055

It’s protected against large voltages, in case the capacitor under test happens to still have a charge in it (a cap is a tiny battery, remember?). The clips are gold-plated to lower the contact resistance – and removable, nice touch!

In this example, I used a 47 µF 25V electrolytic capacitor, and it ended up being slightly less than 47 µF and having an ESR of 0.6 Ω as you can see.

It this cap were used in a 1A power supply to filter the ripple from a transformer, then its ESR could generate up to 0.6 W of heat – which would most likely destroy this little capacitor in no time.

Fortunately, big caps have a much lower ESR. It measured 0 (i.e. < 0.01 Ω) with a 6800 µF unit, for example.

As with last week’s unit, this is not an indispensable instrument. But very convenient for what it does.

Tiny Lithium – packet test

In AVR, Hardware on May 2, 2012 at 00:01

This post continues where the Tiny Lithium discharge post left off…

To summarize: a tiny ML614 rechargable Lithium cell of a mere 3.4 mAh is used to power a JeeNode running the radioBlip sketch, which is going to send out one small packet per minute (the period is actually slightly longer).

I charged the battery overnight from a 3.0V power supply and through a 1 kΩ resistor, as described in the datasheet. As expected, the battery voltage without load is now indeed 2.97V

The test is really simple, but it’s going to take a little while: connect, see packets come in, with a counter being increased for each packet, and then just wait for the whole thing to stop sending. Here we go:

DSC 3072

The range will need to be good, since packets have to cross a reinforced concrete floor to reach my receiver.

Here’s the log of packets I got (the first packet seems to have been missed):

L 12:08:51.628 usb-A600dVPp OK 17 2 0 0 0
L 12:09:54.592 usb-A600dVPp OK 17 3 0 0 0
L 12:10:57.556 usb-A600dVPp OK 17 4 0 0 0
...
L 23:58:57.898 usb-A600dVPp OK 17 167 2 0 0
L 00:00:00.777 usb-A600dVPp OK 17 168 2 0 0
...
L 23:59:32.169 usb-A600dVPp OK 17 6 8 0 0
L 00:00:34.988 usb-A600dVPp OK 17 7 8 0 0
...
L 23:58:57.821 usb-A600dVPp OK 17 101 13 0 0
L 00:00:00.609 usb-A600dVPp OK 17 102 13 0 0
...
L 23:59:01.058 usb-A600dVPp OK 17 197 18 0 0
L 00:00:03.818 usb-A600dVPp OK 17 198 18 0 0
...
L 23:58:45.821 usb-A600dVPp OK 17 37 24 0 0
L 00:00:51.318 usb-A600dVPp OK 17 39 24 0 0
...
L 13:18:55.865 usb-A600dVPp OK 17 34 27 0 0
L 13:19:58.670 usb-A600dVPp OK 17 35 27 0 0
L 13:21:01.474 usb-A600dVPp OK 17 36 27 0 0
L 13:33:35.035 usb-A600dVPp OK 17 48 27 0 0
L 13:37:46.210 usb-A600dVPp OK 17 52 27 0 0
L 13:43:00.171 usb-A600dVPp OK 17 57 27 0 0
L 13:56:36.450 usb-A600dVPp OK 17 70 27 0 0
L 13:57:39.232 usb-A600dVPp OK 17 71 27 0 0
L 14:06:01.520 usb-A600dVPp OK 17 79 27 0 0
L 14:20:40.504 usb-A600dVPp OK 17 93 27 0 0
…silence…

As you can see, this “battery” packs enough energy to send out 27 x 256 + 93 = 7005 packets – of which 398 were not properly received (mostly in the last days). IOW, it was still sending after 5 days!

The node kept going even though several of the last packets were not received – so transmit power probably dropped off quite a bit, but the sketch was still running properly until the very end.

Note: once moved to measure the supply voltage (still about 2.5V), packets started coming in again – perhaps because of improved reception from the new location, or a slight warm-up of the battery.

This little cell just doesn’t want to give up!

Indoor solar energy

In Hardware on May 1, 2012 at 00:01

The amount of solar energy available indoor is very limited… a very small fraction of outside, I’m sure.

Still, this unit has been running in the house here for a few years now, and not near a window either:

DSC 3074

It’s a attractive goal: gadgets which you buy (or build) once and then use essentially forever!

We don’t use the alarm clock mode of this thing, so the beeper never goes off, but it does listen for the DCF77 clock standard transmitter in Germany once a day to stay in sync. It’s also slightly glow-in-the-dark, so this clock remains readable at night.

The fact that this clock works so well tells me that, with proper care, we should be able to run simple nodes inside the house with a solar cell of perhaps a few square centimeters, just like this clock.

And, whether battery- or supercap-powered, that’s precisely what I’d like to get going…

As with the AC-mains connected ultra-low power supply, I suspect that reliable startup will be the hardest part. Such an energy source will have very little spare energy and charge up very slowly, so when the JeeNode comes out of power-up (or brownout) reset, it’ll have to be careful to not cut off the hand that is feeding it, so to speak.

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 :(

Elektro:Camp

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:

SCR20

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

SCR19

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

SCR21

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:

SCR25

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:

SCR14

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):

SCR15

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:

SCR08

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:

SCR10

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:

SCR11

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:

SCR12

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).

Onwards!

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…

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.

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:

SCR03

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:

SCR07

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:

SCR06

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:

Luchtfoto

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:

SCR02

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:

SCR61

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

SCR62

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:

SCR63

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!

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:

Atxps

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.

75 days and counting

In AVR, Hardware on Mar 30, 2012 at 00:01

The JeeNode Micro based on the ATtiny84 is getting more and more use around here. One of the ways it can be powered is via a CR2032 coin cell on its back:

I’ve got one with the radioBlip sketch running here, to see how long it will last on a single coin cell.

Well… today it passed the 75-day mark – celebration time!

Onwards!

TK – Basic tools

In Hardware on Mar 29, 2012 at 00:01

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

Today just some more general notes about stuff which you probably already have: screwdrivers, pliers, tweezers, that sort of stuff. None of this is electronic – but some details do tend to matter in this context.

The toolkit I picked for this series is item 814892 from Conrad, or rather 046027, which is the multimeter plus this set, as a package deal:

814892 BB 02 FB EPS

Don’t expect top-of-the-line professional tools – just stuff which ought to work nicely. The idea is that if any of those tools break, then apparently you’re using it a lot, so maybe now’s a good time to get a better-quality version of that particular tool! – and the rest still comes in handy. By then, you’ll already have some experience, and you’ll be better equipped to pick a good brand which meets your need. It may sound crazy, but by the time you’ve managed to break all of these tools, you’ll have gained plenty of experience with each of them (or you’re handling them too roughly). Either way, it’s still worth the initial expense!

One of the tools you’ll use a lot are side-cutters, to snip off the wires of resistors, caps, etc. after having soldered these components into your circuit or onto your board. The one in this set works, but also illustrates the kind-of-average build quality of these items:

DSC 2948

The jaws will cut just fine, but they are not 100% parallel – it’ll cut better near the end (which is what matters most anyway), than inside where these cutters don’t fully close. But hey – they do work.

Other items in this toolbox are: various types of screwdrivers (flat, philips, and torque), hex spanners, and such. Nothing spectacular, but they come in small sizes – very convenient for electronics use.

There’s a little magnetic LED light (yawn), a loupe (oh so handy, at times, with SMD), and some less common utilities like a magnet on a telescopic pointer and a long “gripper” – useful to get screws accidentally dropped in some hard-to-reach spots, I suppose.

Furthermore there are two types of tweezers in this collection, a straight “reverse-action” type which opens when squeezed, and one bent to the side. Both can be extremely useful, for very different purposes: the straight one acts like a weak clip, since it springs back closed when released. It can be used to gently hold something in place while you’re soldering or measuring it (it does conduct heat, so don’t put it too close to the spot you want to solder).

The standard tweezer is an excellent example of a prolongement du corps – an extension of your body, letting you do more than you’d think possible. I prefer this “angled” type with a bend in it over straight models. It takes very little time to learn to pick up and manipulate tiny SMD components with it. I remember quite well how amazed I was when trying this for the first time with sub-millimeter SMDs – felt a bit like being a neuro-surgeon :)

None of these items are very special. You probably have most of them already. Otherwise, just be sure to get at least the side-cutters, the standard tweezers, and a loupe (or small magnifying glass) … even if you don’t do SMD.

Lissajous is tea for two!

In Hardware on Mar 26, 2012 at 00:01

When you have two nearly identical sine wave signals and you want to compare them, one technique is to plot one against the other, creating what is known as a Lissajous curve.

Lissajous curves make nice images, and even nicer videos because of the phase shifts.

So let’s take two signal generators and try it out, eh?

On the X-axis, I’m going to plot a 10 MHz sine wave from the new AWG, described on this weblog a few days ago. The frequency accuracy and stability of its output signal is within 1 or 2 ppm, according to the TG2511 specs.

On the Y-axis, let’s connect a second 10 MHz sine wave from a cheap DDS, also described on this weblog a few months back. This has a simple crystal so I’d expect 50 to 100 ppm frequency accuracy, i.e. within ≤ 1000 Hz.

When you connect these to an oscilloscope and put it in X-Y mode, you get pictures like these:

SCR40

SCR41

SCR42

The more the two signals are in phase, the more the result will look like a straight line, slanted at 45° (from the bottom left to the top right). When exactly 180° out of phase, it will show a straight line from top left to bottom right. Everything in between create ovals, and when the signals are 90° out of phase (either lagging or leading), the result is a perfect circle.

So the big thing about Lissajous curves is that they let you compare the relative phase of two sine waves.

In practice, signals from different sources will tend to change phase over time, i.e. “drift” as one sine wave is slightly slower or faster than the other. This creates a way to precisely compare two frequency generators: measure how long it takes for the phase to go from 0° to 180° (or 360°, which is 0° again), and you get an idea how long it takes for one signal to catch up (or lag) one full sine wave over the other. Trouble with this approach is that sometimes these cycles are too fast to see, let alone time manually.

With an adjustable frequency source, there’s also another way: adjust a known frequency until the shape stays the same, and you’ll have “measured” the frequency of the other signal in terms of the adjusted one since they must now be equal. It’s very much like tuning a musical instrument by ear and adjusting for a “zero beat”.

That’s what I did, and I ended up with the following result for this test setup:

DSC 2967

IOW, the cheap DDS is running 0.03% slow – i.e. about 300 ppm! And it’s not even very stable, because very soon the DDS starts drifting again: an indication that it’s not holding its frequency really accurately either. This is not really surprising for such a low-cost unit off eBay – it’s still a useful signal source: lots of useful experiments and measurements can be done with such a fairly decent 0.03 % accuracy level, after all.

Ok, this concludes my first exploration into signal-processing – enough signal theory for now!

Noise levels

In Hardware on Mar 25, 2012 at 00:01

Triggered by the recent signal generator checks, and those FM radio stations creeping into the signal yesterday, I wanted to do another test to see how and when this happens, using a series of scope FFT snapshots.

Here’s a 50 Ω coax cable of 2m length hooked up, with 50 Ω termination on both sides but no signal. The scale is 5 dBm per division, and I’ve zoomed into this very low range with a baseline of about -105 dB. The following 200 MHz wide FFT measurements were all done with the scope input set to max sensitivity, i.e. 1 mV/div:

SCR35

Note the slight FM radio station RF signal pickup, even with a fully terminated coax cable!

Same thing, but disconnected on one end, i.e. only one 50 Ω terminator inside the scope:

SCR36

I don’t know why there’s a peak at 25 MHz – the signal generator was completely powered down.

Here’s the spectrum with no coax at all, i.e. nothing connected to the scope, but its 50 Ω shunt still enabled:

SCR37

When also adding an external 50 Ω terminator, the lower frequencies drop ever so slightly further:

SCR38

And here’s what happens when the 2m 50 Ω coax cable is attached back on, without the 50 Ω termination:

SCR39

As you can see, the coax cable now acts as antenna, picking up a few more signals at 38.45 MHz and 46.38 MHz. And FM reception shooting up to 20 dB above the noise floor. Even though it’s shielded!

The slight drop in noise across the screen from 0 to 200 MHz is probably nothing more or less than the scope’s bandwidth: a 200 MHz scope is specified as having a 3 dB drop at 200 MHz, which fits amazingly well with what all the above screen shots are showing.

These tests confirm the superb signal processing specs of the Hameg oscilloscope front end: a -105 dB noise floor @ 1 mV/div maximum sensitivity. For even lower noise levels (and a higher frequency range, as would be needed for 868 MHz and 2.4 GHz RF measurements), probably only a “real” spectrum analyzer will do better.

Whee… with a multi-meter probe wire attached as antenna, I can easily pick up all major AM radio stations:

SCR45

Tomorrow, I’ll close off with one more post about signal processing: accurate frequency measurements.

Update – As with yesterday’s post, these FFT’s were produced with the Rectangle window function. As a bonus, here’s the frequency spectrum produced by the noise generator in my new AWG:

SCR60

Down by 30 dB at 50 MHz, but a pretty good source of white noise at lower frequencies. The AWG can add an adjustable amount of this noise to the generated waveforms – can be useful to see how well a filter, demodulator, or other detector behaves, for example.

RF Shielding

In Hardware on Mar 24, 2012 at 00:01

As shown in yesterday’s post, once you’re looking at signals in the high MHz range, it’s easy to make mistakes. Looking at that screen shot again, you can see a whole bunch of 90..100 MHz spikes:

SCR32

These are in fact local FM radio stations – being picked up by my clunky scope probe hookup to the AWG. In other words it’s an antenna: radiated RF signals are accidentally being received by the probe and mixed in with the conducted 25 MHz signal. The way to get rid of these is to use “shielding” to keep those radio waves out.

Here’s the same signal, using a 50 Ω coax cable all the way between signal generator and oscilloscope:

SCR34

No more weird stuff, just the 25 MHz multiples – indicating that there’s a slight distortion in the generated 25 MHz sine wave. This is normal for any signal generated by a direct digital synthesizer, because the waveform is created through through a digital-to-analog converter, fed at 125 million samples per second in this case. IOW, it’s an approximated sine wave (20 datapoints per sine wave @ 14-bit resolution).

So the big change is that the FM radio stations are gone, and that the signal’s noise level is now in fact a few dB cleaner than before – as you can see from the slightly lower tail towards 200 MHz.

I did have to use a small trick to make these graphs comparable: the second one has the scope’s 50 Ω internal terminator enabled, so that the path from signal source to signal destination is now done by the book: a 50 Ω source (in the AWG), feeding a 50 Ω coax cable, terminated by 50 Ω at the destination (in the scope). This does “attenuate” (i.e. reduce) the signal level by half, so I had to raise the baseline by 3 dB on the second FFT screen shot to make the height of the 25 MHz peak identical in both screens.

One other minor difference is that the second graph is smoothed over 256 samples i.s.o. 64 – cleaning up the resulting line slightly more.

So you see… it’s possible to do RF-type stuff without understanding all the details – which I certainly don’t, yet – and get decent results. The 25 MHz wave coming into the scope is very clean: the first harmonic is some 50 dB below the signal itself, which means that the first harmonic has 100,000 times less energy than the main signal.

Tomorrow, another post about this topic: cables, termination, and noise…

Update – As John Beale pointed out in the comments below, the FFT baseline is caused by the choice of FFT windowing function. Here’s the 50 Ω coax example again, using a Hanning window:

SCR59

Much better for comparing relative dB differences between peaks.

(Tomorrow’s post will also use the default Rectangle window, sorry about that…)

Arbitrary Waveform Generator

In Hardware on Mar 23, 2012 at 00:01

Earlier this week, I described how a fixed frequency can be used to stabilize others.

Well… as part of my continuing drive to set up a more complete workbench here at JeeLabs, I’ve decided to get another piece of equipment which relies on this mechanism, called an “Arbitrary Waveform Generator” (AWG) or “function generator” or “signal generator” – three names for essentially the same instrument, as far as I can tell.

An AWG produces a repetitive electrical signal, such as a sine wave or a square wave. Very roughly speaking, you can think of sine waves as “pure analog” and square waves as “pure digital” frequencies.

The unit I picked is a fairly advanced one, the TG2511 from TTi (Thurlby Thandar Instruments), in the UK:

DSC 2966

(Check out that box underneath – as a reference it now makes a lot more sense, eh?)

It produces sine waves and square waves up to 25 MHz, and has tons of other waveforms built in, including ramp, triangle, pulse, noise, and more. In fact, since it’s an AWG, you can load any waveform shape into it, and it’ll reproduce it at up to 125 Mega-samples per second and 14-bit resolution (it goes up to 6 MHz in this mode).

Two other major capabilities of such a unit are: the ability to “sweep” across a range of frequencies and being able to “modulate” the generated signal with another one in numerous ways: AM, FM, PM, PWM, and FSK.

As with the Hameg HMO2024 oscilloscope and the GW-Instek GPD-2303S power supply, this thing can be remotely controlled over USB. So it can be driven from a computer to perform complex and/or lengthy tests.

This model does more than I need, but there was a good “price burner” offer at Distrelec, so I decided to go for it. Function generators are not the most important instruments for an electronics lab, but they are extremely useful to learn about all sorts of analog electronics, and to illustrate various concepts and effects “for real”. Note that for lower frequencies, you can generate rough arbitrary waveforms with simply an ATmega and a few resistors.

Here’s the FFT spectrum of its 25 MHz sine wave – a few spikes at 25 MHz multiples, as expected, plus a bunch of 90..105 MHz spikes which also appear when the AWG output is off (more about those tomorrow):

SCR32

Such an AWG is not limited to strictly analog uses, by the way. This unit should also be able to generate a serial bit-stream, like an RS232 message, for example. Such patterns can be loaded via USB on the front panel.

I intend to put this instrument to good use here at JeeLabs, not in the least to create good examples for future weblog posts and to illustrate relevant electronics concepts in that huge playground called Physical Computing.

TK – Multimeter

In Hardware on Mar 22, 2012 at 00:01

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

One of the tools you don’t strictly need, but which I very strongly recommend getting, is a multimeter.

A multimeter measures stuff. I picked the Voltcraft VC170, Conrad’s own (re-)brand (item 124403):

DSC 2947

Actually, my suggestion for this series would be to get item 046027, which includes a whole set of additional tools for only €12 extra. It won’t break the bank, and it gets you various screwdrivers, tweezers, a simple loupe, a lamp, and a few more items.

Anyway, back to the multimeter. Trust me – this is one of those lab instruments which will enable you to learn more about electricity than anything else. And this is one of those cases where a small amount of money will go a huge way – this particular unit lets you measure voltage, current, resistance, frequency, and more. The VC170 even does non-contact AC mains sensing, to detect live wires from a short distance.

I’ve got over half a dozen multimeters by now. Low-cost as well as expensive / more accurate ones. My favorite one is this VC170 (or rather, its predecessor, the VC160 which I’ve been using for several years now). Why? Because it’s very small, it’s fast and responsive, and it offers an excellent set of trade-offs.

Some more expensive ones are very sluggish (but also produce considerably more accurate 5-digit readings), some beep very annoyingly all the time, and some don’t have the sensitivity you need. Of all the multimeters I have, I end up using my trusty VC160 most of the time. It does what I need, and it doesn’t fill up my desk.

You can’t really go wrong with this. You’ll want more than one multimeter if you really get into electronics. Here’s a not-too-contrived example: measuring incoming and outgoing voltages of a power regulator at the same time, as well as incoming and outgoing currents – that’s 4 multimeters! So by the time you want a more advanced one, this first unit will still come in handy in certain use cases.

The good news is that one is fine for a huge range of situations. This one will measure up to 230 VAC mains (with a small caveat, see below), and all the way down to fractions of a µA of current (ultra-low power, anyone?).

Learning how to make the most of a multimeter is a story far beyond this initial Thursday Toolkit series. But it’s really easy to get started and learn along the way. Even just fiddling with a resistor, or a capacitor and a resistor, and measuring what happens in various hookups can be a great way to understand Ohm’s law, and all the basics of electronic circuits. Do two resistors in series draw more or less current? What is the resistance of two resistors in parallel? How much voltage are my near-dead batteries giving out, and how are they performing under load? Is that power supply doing what it’s supposed to do? And perhaps most important of all: are the proper voltages being applied to the different parts of my circuit? Trivial stuff with a multimeter – you can simply measure it!

Multimeters are very robust, especially auto-ranging ones like this, which can take any voltage and figure out all by themselves whether it’s over 100 V or in the millivolt range. But there are ways to break things. Big currents always tend to cause trouble, and even the best multimeter won’t be pleased if you push a few amps through it while it’s trying to measure microamps. Which is why the above set of input jacks is actually quite nice: voltage and current are very different quantities, and you have to hook up the measuring cables in specific ways to measure the different types of units. But mess-ups do happen… I’ve blown fuses inside my multimeters a few times – fortunately, they are easy to replace.

All multimeters have trade-offs. This one gets many of them right though, and does auto-ranging.

Then again, this multimeter seems to be at its limit when asked to measure 230 VAC, i.e. AC mains around here. It displays “OL” (overload). But it can measure 230 VAC just fine when using the “Select” button to fix it to the maximum range before doing the measurement.

The other thing is not to get carried away by the 4-digit display. You’ll be able to measure 3999 vs 4000, but that’s not an absolute accuracy, i.e. you shouldn’t expect to be spot on when measuring 3.999 V versus 4.000 V – the accuracy is only about 1.5 %, so it might well be 3.940 V, or 4.060 V. The only purpose this serves, is to show you slight fluctuations – fairly accurately. So it might be off a bit, but you will be able to see small dips and increases in voltage, current, resistance, etc.

And to be honest: 1.5 % accuracy is actually pretty amazing for such a low-cost instrument, if you compare it to the old analog multimeters which you had to read out by estimating the position of their needle!

The VC170 added a function I’ve dearly missed on the VC160: frequency measurements. Its specs says that it works up to 10 MHz, but a quick test here tells me that it’ll work up to at least 25 MHz with a 1 Vpp signal (wait for tomorrow’s post to find out how I tested that). The frequency range is in fact very convenient for microcontroller debugging of timing loops, for example – I’ll go into this in a future post.

So much for the multimeter. If you solder electronic circuits together, all I can say is: get one!

TD – Cost Control

In Hardware on Mar 20, 2012 at 00:01