Computing stuff tied to the physical world

Archive for March 2013

Energy savings…

In News, Musings on Mar 31, 2013 at 00:01

Here’s a view of the solar energy production earlier this week here at JeeLabs:

Screen Shot 2013-03-26 at 18.49.36

Best day so far … 19.3 kWh in one day: that’s some 2.5 x our average daily consumption!

This graph was made with HouseMon, which is still in the early stages but I’m viewing it on a daily basis – the Status and Graphs pages are already quite practical. Then again, it’s a constant reminder that the progress of this project is considerably slower than I had hoped when I started out. One reason for that is that I’m still hesitant to make some major design decisions – mostly because I don’t have enough experience and don’t feel confident enough with Node.js and CoffeeScript yet. So many things still feel awkward :(

Speaking of insufficient progress… it’s time to switch off:

wallpaper power symbol green

(image by TheBigDaveC, as found on this site)

I’m going to take a brief break, and interrupt this daily flow of weblog posts for a while.

It has happened before, and it will happen again: I want to clear my head and focus on some projects which take a bit more concentration than I seem to be finding these days.

But no worries: this daily weblog will resume before JeeDay (April 19 + 20), so there will still be enough time to get the latest info and news out to you.

Soooo… see you then, and more importantly: see you there !

(Pssst… in case you haven’t seen this… let that nano stuff inspire you… pretty amazing!)

Sharing Node ID’s

In Software on Mar 30, 2013 at 00:01

The RF12 driver has a 5-bit slot in its header byte to identify either the sender or the destination of a packet. That translates to 32 distinct values, of which node ID “0” and “31” are special (for OOK and catch-all use, respectively).

So within a netgroup (of which there can be over 250), you get at most 30 different nodes to use. Multiple netgroups are available to extend this, of course, but then you need to set up one central node “listener” for each netgroup, as you can’t listen to multiple netgroups with a single radio.

I’m using JeeNodes all over the place here at JeeLabs, and several of them have been in use for several years now, running on their own node ID. In fact, many have never been reflashed / updated since the day they were put into operation. So node ID’s are starting to become a bit scarce here…

For testing purposes, I use a different netgroup, which nicely keeps the packets out of the central HouseMon setup used for, eh… production. Very convenient.

But with the new JeeNode Micro, I actually would like to get lots more nodes going permanently. Especially if the coin cell version can be made to run for a long time, then it would be great to use them as door sensors, lots more room nodes, and also stuff outside the house, such as the mailbox, humidity sensors, and who knows what else…

Now the nice thing about send-only nodes such as door sensors, is that it is actually possible to re-use the same node ID. All we need is a “secondary ID” inside the packet.

I’ve started doing this with the radioBlip2 nodes I’m using to run my battery lifetime tests:

Screen Shot 2013-03-26 at 10.11.14

(BATT-0 is this unit, BATT-1 is a JNµ w/ coin cell, BATT-2 is a JNµ w/ booster on 1x AA)

This is very easy to do: add the extra unique secondary ID in the payload and have the decoder pick up that byte as a way to name the node as “BATT-<N>”. In this case, it’s even compatible with the original radioBlip node which does not have the ID + battery levels.

Here is the payload structure from radioBlip2, with secondary ID and two battery levels:

struct {
  long ping;      // 32-bit counter
  byte id :7;     // identity, should be different for each node
  byte boost :1;  // whether compiled for boost chip or not
  byte vcc1;      // VCC before transmit, 1.0V = 0 .. 6.0V = 250
  byte vcc2;      // battery voltage (BOOST=1), or VCC after transmit (BOOST=0)
} payload;

And here’s the relevant code snippet from the decoder in HouseMon:

  decode: (raw, cb) ->
    count = raw.readUInt32LE(1)
    result =
      tag: 'BATT-0'
      ping: count
      age: count / (86400 / 64) | 0
    if raw.length >= 8
      result.tag = "BATT-#{raw[5]&0x7F}"
      result.vpre = 50 + raw[6]
      if raw[5] & 0x80
        # if high bit of id is set, this is a boost node reporting its battery
        # this is ratiometric (proportional) w.r.t. the "vpre" just measured
        result.vbatt = result.vpre * raw[7] / 255 | 0
        # in the non-boost case, the second value is vcc after last transmit
        # this is always set, except in the first transmission after power-up
        result.vpost = 50 + raw[7] if raw[7]
    cb result

In case you’re wondering: the battery voltage is encoded as 20 mV steps above 1.0V, allowing a single byte to represent values from 1.0 to 6.1V (drat, it’ll wrap when the boost version drops under 1.0V, oh well…).

Note that this trick works fine for send-only nodes, but it would need some additional logic in nodes which expect an ACK, since the ACK will be addressed to all nodes with the same ID. In many cases, that won’t matter, since presumably all the other nodes will be sound asleep, but for precise single-node ACKs, the reply will also need to include the extra secondary ID, and all the nodes will then have to check and compare it.

So now it’s possible to re-use a node ID for an entire “family” of nodes:

  • over 250 different netgroups are available for use
  • each netgroup can have a maximum of 30 different node ID’s
  • each node ID can be shared with over 250 send-only nodes

That’s over 1.8 million nodes supported by the RF12 driver. More than enough, I’d say :)

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:


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:


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

void loop () {}

Which produces this result:


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:


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!

Software development

In Software, Musings on Mar 28, 2013 at 00:01

As you probably know, I’m now doing all my software development in just two languages – C++ in the embedded world and JavaScript in the rest. Well, sort of, anyway:

  • The C++ conventions I use are very much watered down from where C++ has been going for some time (with all the STL machinery). I am deliberately not using RTTI, exceptions, namespaces, or templates, because they add far too much complexity.
  • Ehm… C++ templates are actually extremely powerful and would in fact be a big help in reducing code overhead on embedded processors, but: 1) they require a very advanced understanding of C++, 2) that would make my code even more impenetrable to others trying to understand it all, and 3) it can be very hard to understand and fix templating-related compiler error messages.
  • I also use C++ virtual functions sparingly, because they tend to generate more code, and what’s worse: VTables use up RAM, a scarce resource on the ATmega / ATtiny!
  • As for programming in JavaScript: I don’t, really. I write code in a dialect called CoffeeScript, which then gets compiled to JavaScript on-the-fly. The main reason is that it fixes some warts in the JavaScript syntax, and keeps the good parts. It’s also delightfully concise, although I admit that you have to learn to read it before you can appreciate the effect it has on making the essence of the logic stand out better.
  • There is an incredible book called CoffeeScript Ristretto by Reginald Braithwaite, which IMO is a must read. There is also a site called which appears to have the entire content of that book online (although I find the PDF version more readable). Written in the same playful style as The Little Schemer, so be prepared to get your mind twisted by the (deep and valuable) concepts presented.
  • To those who dismiss today’s JavaScript, and hence CoffeeScript, on the basis of its syntax or semantics, I can only point to an article by Paul Graham, in which he describes The Blub Paradox. There is (much) more to it than meets the eye.
  • In my opinion, CoffeeScript + Node.js bring together the best ideas from Scheme (functions), Ruby (notation), Python (indentation), and Tcl (events).
  • If you’re craving for more background, check out How I Learned To Enjoy JavaScript and some articles it links to, such as JS: The Right Way and Idiomatic JavaScript.

I’m quite happy with the above choices now, even though I still feel frustratingly inept at writing CoffeeScript and working with the asynchronous nature and libraries of Node.js – but at every turn, the concepts do “click” – this really feels like the right way to do things, staying away from all the silliness of statically compiled languages and datatypes, threads, and blocking system calls. The Node.js community members have taken some very bold steps, adopted what people found worthwhile in Ruby on Rails and other innovations, and lived through the pain of the all-async nature by coming up with libraries such as Async, as well as other great ones like Underscore, Connect cq. Express, Mocha, and Marked.

I just came across a very nice site about JavaScript, called SuperHero, via this weblog post. Will be going through it soon, to try and improve my understanding and (hopefully) skills. If you like video’s, check out PeepCode, i.e. this one on Node.js + Express + CoffeeScript.

As for the client-side JavaScript framework, I’m using AngularJS. There’s a nice little music player example here, with the JavaScript here, illustrating the general style quite well, IMO.

Isn’t it amazing how much knowledge and tools we have at our fingertips nowadays?

It seems to me that for software technologies and languages to gain solid traction and momentum, it will all come down to how “learnable” things are. Because we all start from scratch at some point. And we all only have so many hours in the day to learn things well. There is this never-ending struggle between picking the tools which are instantly obvious (but perhaps limited in the long rung) vs. picking very advanced tools (which may take too much time to become proficient in). Think BASIC vs. Common Lisp, for example. It gets even worse as the world is moving on – how can anyone decide to “dive in” and go for the deep stuff, when it might all be obsolete by the time the paybacks really set in?

In my case, I want to not only build stuff (could have stayed with Tcl + JeeMon for that), but also take advantage of what others are doing, and – with a bit of luck – come up with something which some of you find attractive enough to build upon and extend. Time will tell whether the choices made will lead there…

One other very interesting new development I’d like to mention in this context, is the Markdown-based Literate Programming now possible with CoffeeScript: see this weblog post by Jeremy Ashkenas, the inventor & implementor of CoffeeScript. I’m currently looking into this, alongside more traditional documentation tools such as Docco and Groc.

Would it make sense to write code for HouseMon as a story? I have no idea, yet…

Avrdude in CoffeeScript

In AVR, Software on Mar 27, 2013 at 00:01

Here’s a fun project – rewriting avrdude in CoffeesCript, as I did a while back with Tcl:

{SerialPort} = require 'serialport'

pageBytes = 128

avrUploader = (bytes, tty, cb) ->
  serial = new SerialPort tty, baudrate: 115200

  done = (err) ->
    serial.close ->
      cb err

  timer = null
  state = offset = 0
  reply = ''

  states = [ # Finite State Machine, one function per state
      ['0 ']
      buf = new Buffer(20)
      buf.fill 0
      buf.writeInt16BE pageBytes, 12
      ['B', buf, ' ']
      ['P ']
      state += 1  if offset >= bytes.length
      buf = new Buffer(2)
      buf.writeInt16LE offset >> 1, 0
      ['U', buf, ' ']
      state -= 2
      count = Math.min bytes.length - offset, pageBytes
      buf = new Buffer(2)
      buf.writeInt16BE count, 0
      pos = offset
      offset += count
      ['d', buf, 'F', bytes.slice(pos, offset), ' ']
      ['Q ']

  next = ->
    if state < states.length
      serial.write x  for x in states[state++]()
      reply = ''
      timer = setTimeout (-> done state), 300

  serial.on 'open', next

  serial.on 'error', done

  serial.on 'data', (data) ->
    reply += data
    if reply.slice(-2) is '\x14\x10'
      clearTimeout timer

And here’s a little test which uploads the RF12demo sketch into a JeeNode over serial:

fs = require 'fs'
hex = fs.readFileSync '/Users/jcw/Desktop/RF12demo.cpp.hex', 'ascii'

hexToBin = (code) ->
  data = ''
  for line in code.split '\n'
    count = parseInt line.slice(1, 3), 16
    if count and line.slice(7, 9) is '00'
      data += line.slice 9, 9 + 2 * count
  new Buffer(data, 'hex')

avrUploader hexToBin(hex), '/dev/tty.usbserial-AH01A0GD', (err) ->
  console.error 'err', err  if err
  console.log hexToBin(hex).length

Just copy it all into a file and run it as: coffee

It’s fairly dense code, but as you can see, the stk500v1 protocol requires very little logic!

It’s a software goose (again)

In AVR, Software on Mar 26, 2013 at 00:01

Yesterday’s weblog post documented my attempts to debug a problem while programming the JeeNode Micro with a Flash Board. I really thought it was a hardware bug.

Given that the results where slightly changing as I tried different things, but nevertheless seemed really consistent and repeatable when retrying exactly the same steps over and over again should have caused an alarm bell to ring, but alas it took me quite some time to figure it out: repeatable is a hint that the problem might be a software issue, not hardware.

So the next step was to use the data dump feature from the scope to collect the data written and well as the data being read back. These can be saved as CSV files, and with a bit of scripting, I ended up with this comparison:

Screen Shot 2013-03-19 at 10.47.35

This shows three editor windows super-imposed and lined up with, from left to right:

  • the data read back
  • the data written
  • the hex file with the compiled sketch

As you can see, the writes are exactly what they should be – it’s the read which gives junk. And it’s not even that far off – just a few bits!

Looking closer, it is clear that some bits are “0” where they should have been “1”.

Uh, oh – I think I know what’s going on…

It looks like the chip hasn’t gone through an erase cycle! Flash programming works as follows: you “erase” the memory to set all the bits to “1”, and then you “program” it to set some of them to “0”. Programming can only flip bits from “1” to “0”!

And indeed… that was the problem. The Arduino boot loaders are set up to auto-erase on request, so avrdude is called from the IDE with “bulk erase” disabled. That way, the IDE just sends the pages it wants to program, and the boot loader will make sure the erase is performed just before writing the page.

In this case, however, there is no boot loader: we are using the normal ISP conventions, whereby erasing and programming must be explicitly requested.

It was a matter of dropping the “-d” “-D” flag from the avrdude command in platform.txt:


And now it works, flawlessly! Doh – this “bug” sure has kept me busy for a while…

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:


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


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:


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:


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:


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

JN Micro v3 reference

In AVR on Mar 23, 2013 at 00:01

As promised, here is the reference card for the JeeNode Micro v3:


(Click on the image to see the full-size version)

Note: the definitions in Ports.h were incorrect for the JeeNode Micro. Please make sure you update to the latest version of JeeLib if you intend to use the Port or PortI2C classes with the ATtiny84 on the JeeNode Micro!

The thing with diagrams such as these, is that they are hampered by file format wars, with all full-featured drawing apps going out of their way to lock people in. In this case, the diagrams where created by Marco Bakker in Visio on Windows – which I don’t have – so I imported it into OmniGraffle for Mac – which is in turn useless on other platforms.

Luckily, PNG and PDF have become de-facto standards which every browser knows how to display – so rendering the diagrams at least produces results everyone can use.

Maybe one day, we’ll all be using SVG editors. There’s a web-based one called SVG-edit, but it doesn’t seem to be quite there yet w.r.t. importing the SVG from OmniGraffle. There is also the multi-platform Inkscape, which does import the SVG very nicely (just one minor font size issue, as far as I can tell). But the UI is a bit quirky on the Mac, since it has to conform to the XQuartz conventions of the X.Org X Window System (aka X11).

I’ve updated the Pinouts page on the Hardware wiki to include these new Quick Reference Cards, and have attached the design and output files in different formats.

JeeNode v6 reference

In AVR on Mar 22, 2013 at 00:01

What started out as a great initiative on the forum has now become a complete “Quick Reference Card” for the JeeNode v6. With many many thanks to @mars for working out all the details and tweaks and for sharing his design files:


(Click on the image to see the full-size version)

Here is the legend and the Creative Commons attribution:

legend   attribution

Tomorrow, I’ll post the other reference card for the JeeNode Micro (after a bit more checking), along with links to the final version in several formats on the wiki.

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


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:


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:


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


Bottom side:


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

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

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

void loop() {

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

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


Direct relay switching with a cap

In Hardware on Mar 18, 2013 at 00:01

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

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


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

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

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


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

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


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

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

Direct relay switching – part 2

In Hardware on Mar 17, 2013 at 00:01

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

But first, the code I’ve been using:

void setup() {}

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

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

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

void loop() {

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

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


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

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

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


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

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

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

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


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

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

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


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

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


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

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

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

Direct relay switching

In Hardware on Mar 16, 2013 at 00:01

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

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


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


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


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


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

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

JC's Grid, page 68

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

So to turn the relay on, the actions are:

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

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

More on this tomorrow. Stay tuned…

Unwanted RF

In Hardware on Mar 15, 2013 at 00:01

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

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

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

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

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


Whoa – nice FM antenna!


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


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


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


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


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

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

Heat imaging at JeeLabs

In Musings on Mar 14, 2013 at 00:01

Yesterday’s images were just a diversion from the task of “measuring the house”, of course. Here are some outside thermal images, taken mid-February:



But the really interesting bit comes from sucking air out of the house using the blower door on a cold day, to see where cold air comes leaking back in:



You have to take the measurement scale into account, but some of the (over 200!) images made were absolutely shocking. There are some major air leaks in and around the house!

As final test, smoke was used: you turn the blowers around to create a slight over-pressure, turn on a big smoke generator (of the kind used in shows on-stage), get out of the house, and watch the smoke appear – it was literally everywhere, even in the neighbour’s houses!

This sort of testing needs to be pre-announced to the local fire department…

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



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


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

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

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

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

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

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

Resonator and crystal

In Hardware on Mar 11, 2013 at 00:01

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

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


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


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

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

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

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


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

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

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

It’s no longer a capacitor!

In Hardware on Mar 10, 2013 at 00:01

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

But let’s go back to decoupling…

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


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

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

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

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


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

What’s going on here?

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

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

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


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

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

Frequency sweep

In Hardware on Mar 9, 2013 at 00:01

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

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


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

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


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


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

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

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

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


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

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

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

Decoupling caps

In Hardware on Mar 8, 2013 at 00:01

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

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

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

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



What is decoupling? And decoupling what exactly?

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

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


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

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

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

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

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

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

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

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

Programming the JNµ v3 – part 2

In AVR, Software on Mar 7, 2013 at 00:01

It’s a long and winding road, that path to finding an easy way to program the JeeNode Micro v3, as mentioned two days ago. With emphasis on the “easy” adjective…

Let me at least describe the process details of what I’ve been using so far:

  1. A custom cable to connect the JNµ to an ISP programmer
  2. Installed copy of the “arduino-tiny” project from Google Code
  3. A trick to get the Arduino IDE compile the sketch into a HEX file
  4. Setting up the JeeNode + Flash Board as an ISP programmer
  5. Using avrdude directly, to set the fuses and upload the sketch into the JNµ

It works, in fact it works fine once you’ve set it all up – but easy? Hm…

Let’s go through each of these in turn.

1. Custom cable

This was described a few days ago. Let me just add that it’s very easy to take apart the connectors on the Extension Cable, once you know the trick:


It’s all a matter of gently lifting the plastic tabs, then the wires come sliding out. Note that this is the wrong end of the cable for our case – but the other end works the same.

2. Arduino-tiny

These files on Google Code contain all the necessary code to trick the Arduino IDE into compiling for ATtiny processors, including the ATtiny84 used in the JNµ.

It works with IDE 1.0.x as is, if you follow the instructions, but I’ve been reorganising it to meet the requirements of the new multi-architecture IDE 1.5.x series, which would support this as a straight drop-in. I’m still working on it, but it means you can then just press the “Upload” button – a lot simpler than the process being described in this post!

3. Hex files

Normally, the Arduino IDE takes care of everything: compilation as well as uploading. However, for this setup, we need to get hold of the raw HEX file that gets generated before uploading. There’s a preference in the IDE for that:

Screen Shot 2013-03-06 at 10.22.12

Now the nasty bit: you have to compile (“run” in Arduino IDE terms, go figure!) the sketch to see the output that gets generated, and then copy the full path from the output window:

Screen Shot 2013-03-06 at 10.23.36

In this case, it’s that “/var/folders/…/radioBlip2.cpp.hex” thing.

4. ISP programmer

To turn the JeeNode + Flash Board combo into an ISP programmer, upload the isp_flash.ino to it. Make sure you get the very latest version, which uses 9600 Baud for communication, as that makes it compatible with the “Arduino as ISP” programmer:

Screen Shot 2013-03-06 at 15.36.07

As mentioned before, you don’t really need the Flash Board at this stage – a couple of wires will also work fine (see these posts about all the ways this can be done).

5. Avrdude

The last step is to call the “avrdude” uploader from the command line, specifying all the arguments needed, and pasting in that full file name. In my case, it was something like:

avrdude -v -v -pattiny84 -cstk500v1 -P/dev/tty.usbserial-A600K04C \
  -b9600 -D -Uflash:w:/var/folders/.../radioBlip2.cpp.hex:i

Oh, and if this is the first time you’re programming this ATtiny84 chip, then you also have to first set the fuses properly, as follows:

avrdude -v -v -pattiny84 -cstk500v1 -P/dev/tty.usbserial-A600K04C \
  -b9600 -e -U lfuse:w:0xC2:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:m

That’s the internal RC oscillator with fastest startup, and the brown-out level set to 1.8V.

As I said, this is the messy way to do things. I’ll try to have something simpler soon!

Retro kitsch

In Musings on Mar 6, 2013 at 00:01

Here’s a crazy book for ya’ – one which you can’t quite judge by its cover, in fact:


Well… I fell for it, and decided to get one:


Just think of what this represents: 500 GB of storage in the space of a single book.

Not bad for compression: half a million books in the size of… a book? :)

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…


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:


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:


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:


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:


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:


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


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:


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


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:


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.