Computing stuff tied to the physical world

Posts Tagged ‘Home automation’

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.

Dive Into JeeNodes

In AVR, Hardware, Software, Linux 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.

Remote node discovery – code

In Software on Jan 16, 2013 at 00:01

Ok, time to try out some real code, after yesterday’s proposal for a simple node / sketch / packet format announcement system.

I’m going to use two tricks:

  • First of all, there’s no need for the node itself to actually send out these packets. I’ve written a little “announcer” sketch which masquerades as the real nodes and sends out packets on their behalf. So… fake info to try things out, without even having to update any nodes! This is a transitional state, until all nodes have been updated.

  • And second, I don’t really care about sending these packets out until the receiving end actually knows how to handle this info, so in debug mode, I’ll just report it over serial.

Note that packets get sent to “node 0”, which cannot exist – so sending this out is in fact harmless: today’s RF12 listeners will ignore such packets. Except node 31, which sees these new packets come in with header byte 64 (i.e. 0x40). No RF12 driver change needed!

Here’s the essence of the test sketch:

Screen Shot 2013-01-15 at 15.12.08

With apologies for the size of this screenshot – full code is on GitHub.

Note that this is just for testing. For the actual code, I’d pay far more attention to RAM usage and place the actual descriptive data in flash memory, for example.

And here’s some test output from it on the serial port:

Screen Shot 2013-01-15 at 15.09.51

Yeah, that looks about right. Next step will be to pick this up and do something with it. Please give me a few days for that, as the “HouseMon” server-side code isn’t yet up to it.

To be continued soon…

PS. Another very useful item type would be the maximum expected time between packets. It allows a server to automatically generate a warning when that time is grossly exceeded. Also a nice example of how self-announcement can help improve the entire system.

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

Distractions

In Hardware, Software on May 10, 2011 at 00:01

Sorry, no serious weblog post this time. I’ve been distracted by an iPad which got delivered here today.

Couldn’t resist trying out some stuff…

Portrait

Here’s one in landscape mode:

Landscape

(both screen shots were created via the simulator, but the real thing looks exactly the same)

It’s obviously just a web browser. It’s also totally obvious to me now that touch screens are a natural fit for this sort of stuff. Goodbye double-click, hello swipe and pinch.

Pretty amazing how long we’ve done without ’em!

Another power option

In Hardware on May 9, 2011 at 00:01

Here’s a nice little power supply:

Dsc 2137

It’s one of many LED drivers currently available on the market.

These supplies are designed to provide a fixed current – not voltage. What this means is that if you “overload” them, then they will regulate the voltage down to the point where the current reaches a preset value (700 mA in this case).

In itself, this isn’t really useful for powering anything but power LEDs, but this unit also specifies that as long as the load remains under 650 mA, it will supply a fixed voltage of about 6V. So the other way to interpret these specs, is to see this as a 6V power supply with automatic current limiting to 700 mA.

This means that if we add the optional diode to a JeeNode v5 or v6, then the voltage would be just right to power one or more 5V relays.

The nice thing about these units is that they are fully “potted”, i.e. encased with proper high-voltage isolation.

This might offer a practical way to set up mains-powered JeeNodes, with perhaps a Relay Plug to switch simple AC loads, or a triac for switching / dimming incandescent lights. Another option would be to use a MOSFET to switch 1..3W power LEDs.

PS. Unfortunately, I don’t remember where I got this particular unit (yeah, I know – I feel pretty stupid!)

Web hooks and feeds

In Software on May 8, 2011 at 00:01

I’m starting to look into hooking stuff together via TCP/IP on the PC/Mac host side of things.

One approach is to use Web Hooks. The idea is that the sender initiates a simple HTTP GET or POST request to some web browser, with all the information contained in the URL and/or query arguments.

In JeeRev, I decided to try it out by adding a webfeed feature and a webhook feature.

The webfeed mechanism is absolutely trivial: make a web request to a URL with the name of the parameter and the value of the parameter at the end, and add any other info you want as query args:

http://127.0.0.1:8181/webfeed/abc-def/12345?unit=mV&scale=2

This creates a new reading for parameter “abc-def” with value “123.45” (I used the scaling mechanism in this example, but direct input of “123.45” would have worked too).

That means any process with access to the webserver running in JeeRev can feed values into the system.

The reverse is the webhook: each time one of a specific set of parameters changes, a web request is made to a configurable URL, with the parameter name, its value, and such filled in automatically.

Here’s an example feed to the ThingSpeak web service:

Screen Shot 2011 05 07 at 17.03.54

(hmmm, looks like ThingSpeak only presents information on an hourly basis)

There’s no coding involved with either of these features in JeeRev, it’s all defined in a local config file.

Trivial. There really are tons of ways to do this collecting / storing / graphing stuff, and you can find lots of sites doing similar things all over the web these days. The Pachube website has been around for some time and appears to be used a lot.

To be honest, I would think twice before handing over my home monitoring and automation info to a public website. Sure, it might look cool to show everyone what you’re doing at home, and what you’ve automated – but it’s a privacy risk I can do without. I don’t intend to create a public site for JeeLabs sensor access and control. That’s the whole point of JeeRev: low cost hardware, running a local monitoring and control system, with optional outside access via secure channels, i.e. a password-protected SSL connection. The technology is open, but not our data (not even energy info: I’m more interested in optimizing than in making a statement).

The way I see these web hook/feed mechanisms, is not to create a world wide web of things, but as a way to tie different software systems together within the confinements and privacy of the home. Every device, app, and language has web technologies built-in these days, so it’s only natural to use them as exchange mechanism.

But I’ll leave the “look ma, my front door is open” sensor reports to others ;)

Update – the ThingSpeak web site service does support private channels and more fine-grained access, see the comments below.

Relays at last

In Hardware on May 2, 2011 at 00:01

It has taken months to settle this issue, but I’m happy to report that the supply problems are all over now… the Relay Plug board has been redesigned to accommodate a slightly different model:

Dsc 2488

Still fits, still same size. And still rated 5A @ 250 VAC.

The coil resistance is 125 Ω, which means each of the two relays will draw 40 mA @ 5V when closed. Slightly more than the previous model, but well with the specs of the on-board relay drivers.

The point of it all is that these new relays have a major distinguishing feature: I’ve got them in stock, at last :)

For the record: first an order for the original units was postponed from January to May, then a second order with another supplier was pushed back to June when they told me the stock listed on their website was grabbed by someone else moments before me…

All is well again now. End of story. Well… until the next supply issue pops up, anyway!

Software evolution

In Software on Mar 17, 2011 at 00:01

With all the focus on sensors and embedded hardware, I’ve lost track a bit of the other side of the equation – monitoring all that incoming data, and (later on) using it to control devices. The receiving end – i.e. software running on a central PC (or embedded Linux box) has not kept up with the rest of the Jee world.

One reason was that my setup for collecting sensor data around the house has been running quite smoothly. Producing these graphs, updatable via a browser refresh:

See this, this, and this post for more details about how it was done. The JeeMon 2009 setup has been running almost non-stop on a low-power NAS, called the Bubba II (now replaced by newer models). There were only about half a dozen system restarts in these past two years, some due to power outages, some due to devices needing a reset, but that’s about it.

Trouble is… all development on this has stagnated. I did start on a JeeMon 2010 successor, but that has only been used for newer projects, such as the ookScope. In the end, I didn’t really want to disrupt my working data-collection setup and just kept the old one going. So now I’ve got two years worth of detailed logging and a local web site which is showing its age and not very useful for meeting my new requirements – let alone being able to perform more meaningful stats and controlling devices for home automation.

Last summer a student project was started at the nearby Utrecht University to try and come up with a general infrastructure which would be able to do a lot more than what I had. The result is a new system called “JeeBus” (more details coming soon on this weblog).

While JeeBus does provide a fair set of interesting features, one of the issues that kept bothering me is that normally in software development you have to either run the code or make changes to it. The “conventional” operation mode is to stop the server, edit the code, and then restart it to pick up the changes. With a bit of luck, there may be the option to re-install certain parts – but usually this is limited to “drivers” and “extensions”.

I find this stifling. Having to restart an app just to try out a one-line change is much more disruptive during active development than such a simple stop/re-start would suggest, because each time you also have to get the process back to the state you were working on. And with dynamic scripting languages, it’s a bit silly to have to jump through such hoops – which really stem from the edit-compile-run cycle of statically-bound environments, decades ago.

So I’ve started scratching my itch, and implemented a small core “hub” which starts up functionally empty with just enough capability to accept remote procedure calls (RPC‘s) and to inject plugins into a (local or remote) running process. The last version of each plugin is saved and is automatically loaded again after a restart. The result is a JeeMon process which starts off as a blank slate and evolves into a full-fledged app – web server, gui, hardware interface, background task, anything.

So far, development in a “live” process looks promising. There are less and less situations where I need to restart. I’ve set up a little tool to push all changed plugins to a remote hub, and that really completely changes the landscape of software development for me. No need to take down a real-time system anymore, which is what most of all this is about when it comes to physical computing and devices. Bugs generate stack traces, but the hub continues to function, so re-installing a fix usually solves the problem. And changing code in a working system has never been easier. This matters a lot, because I really really want to be able to “grow” a system over time.

Starting and stopping a process which is designed to run non-stop is odd. Let’s see if this new design will make it unnecessary in most cases – during active development as well as for tweaking a working setup at a later date.

Power consumption

In Software on Mar 12, 2011 at 00:01

I’ve been working on some new software to better handle all the messages flying around the house. Took down the old system, and started collecting stuff with the new framework.

First one that always interests me, is the baseline power consumption. So I grabbed some values from last night:

Power 11 03 2011

That’s about 450 watts when all the lights are out and nothing is happening – shocking!

Uh, oh – 4000 kWh of vampire power on a yearly basis. Either my new calculations are way off, or some serious stuff has crept in here at Jee Labs which is drawing lots of power!

Update – Yeah, I was off by a factor of 4 in the low range. Forgot that I had added some fancy bit packing to get more resolution across in the metering sketch:

Screen Shot 2011 03 12 at 11.58.23

The lows are around 110 W. With the 24h “internet presence” (server + router + fiber modem) taking an estimated 30 W. Now that makes sense again!

OOK relay, revisited

In Software on Feb 3, 2011 at 00:01

With the modded RFM12B receiving 868 MHz signals, and the new OOK 433 Plug doing the same for the 433 MHz band, the new OOK relay is coming in sight.

Just a lousy bit of code. Elementary – I thought…

Except it wasn’t. Software always seems to take a lot more time (and concentration) than hardware. Silly!

Still, I think I managed to collect all the pieces lying around here from earlier experiments in that area, and combine them into a new ookRelay2.pde sketch.

It’s fairly elaborate and too long to show here, but I’ll pick out some pieces:

  • all the decoders live in the decoders.h file
  • since they all share common logic, each is derived from a common “DecodeOOK” class
  • the protocol for each decoder is the same: feed puse widths to nextPulse(), and it will return true whenever a valid packet has been decoded, then call getData() to get a pointer and byte count
  • the ookRelay2 sketch includes a variety of decoders, I hope we can improve/extend/add-more over time
  • there are two pulse sources: the 868 MHz receiver and the 433 MHz receiver
  • for each, a “DecoderInfo” table is defined with decoders to use for them
  • the runPulseDecoders() function does what the name says: evaluate each of the decoders in turn
  • when a decoder succeeds, data is added to an outgoing buffer (and optionally, printed to serial)
  • in this example, I send the accumulated data off to the RF12 wireless network, but Ethernet or any other transport mechanism could be used as well

With this out of the way, you can probably, eh… decode the following lines at the top op the ookrelay2 sketch:

Screen Shot 2011 02 02 at 23.30.36

And here’s the main loop, which is keeping things going:

Screen Shot 2011 02 02 at 23.31.24

The hard part is doing this efficiently with accurate timings, even though a lot of stuff is happening. That’s why there are two interrupt routines, which trigger on changes in 868 MHz and 433 MHz signals, respectively:

Screen Shot 2011 02 02 at 23.33.22

I’m still debugging, and I need to analyze just how much leeway there is to run all the decoders in parallel. Earlier today I had the 433 MHz reception going, but right now it seems this code is only picking up 868 MHz signals:

Screen Shot 2011 02 02 at 23.34.46

Oh well, it’s a start. Feel free to check out the code, which lives as example in the RF12 library.

Update – Bug fixed, now 433 MHz decoding works.

New OOK and DCF relay

In Hardware on Jan 29, 2011 at 00:01

With all the pieces finally in place, and now that I’m getting a little bit more time to hack around again, this seemed like a good time to reconsider the OOKrelay.

So I combined a JeeNode USB, the new OOK 433 Plug, a Carrier Board with box, and half a Carrier Card:

Dsc 2429

In the top left I also added a DCF77 receiver from Conrad, attached to the Carrier Card prototyping board. It’s a bit hard to see, because the little receiver board is actually mounted upright. Here’s a better view:

Dsc 2430

A JeeNode USB was selected, because this thing will be powered permanently, and I chose to hide the connector inside the box to make it more robust. So all this needs is a little USB charger. The LiPo charge option might be useful if I decide to make this thing more autonomous one day (i.e. to record accurate power outage times).

Note that this is a modded JeeNode, as described here, to be able to receive 868 MHz OOK signals.

So what this thing can do – as far as the hardware goes – is listen for both 433 MHz and 868 MHz OOK signals at the same time, as well as pick up the DCF77 atomic clock signals from Frankfurt. Sending out 433/868 MHz OOK is possible too, but since the unit isn’t constantly listening for OOK packets, it’ll have to poll for such commands, which will introduce a small delay.

That’s the hardware, i.e. the easy part…

The software will be a lot more work. I’m going to adapt / re-implement the functionality from the OOKrelay sketch, i.e. this unit will decode and re-transmit all incoming data as RF12 packets, so that they can be picked up by a JeeLink hooked up to my PC/Mac. The clock signal will be useful to accurately time-stamp all receptions, and is really of more general use.

So far, the following I/O pins have been used:

  • one port for the OOK 433 Plug, i.e. one DIO and one AIO pin
  • one input pin for the modded JeeNode, to receive 868 MHz OOK signals
  • one input pin for the DCF77 signal

There is still lots of room left for expansion. A Pressure Plug perhaps, to track barometric pressure. Or a Memory Plug to save up the last data while the central receiver is unavailable. Or both, since these can combined on a single I2C port.

Absent from all this, is a display. First of all, squeezing a 2×16 LCD in there would have been very tight, but more importantly, now that there is a JeePU, there really is no need. I’m already sending the info out by wireless, so a remote graphical display is definitely an option – without PC – or I could use a central server to get this info to the right place(s). This box is intended to be hidden out of sight, somewhere centrally in the house.

Only thing I might consider is a small LED near the USB cable, to indicate that all is well. Maybe… I’m not too fond of blinking LEDs everywhere in the house :)

Meet the OOK 433 Plug

In Hardware on Jan 28, 2011 at 00:01

After yesterday’s post about modding the RFM12B to receive OOK RF data, here’s a new option which goes the other way: add-on hardware for 433 MHz.

Meet the OOK 433 Plug:

This plug can probably be used without antenna, but adding one is bound to increase the maximum reception range (I haven’t done any range tests yet).

The receiver output is tied to the AIO pin, which must be configured as input on the JeeNode. The transmitter is tied to the DIO pin, to be used as output pin.

Both receiver and transmitter can be operated from 3..12V (I’ve only tested with 3.3V and 5V, so far). For the transmitter, I would expect the power output and range to increase with voltage, but even at 3.3V things seem to work quite well in both directions. There is a jumper to select between PWR and +3V as power supply, and there is an optional series resistor for the receiver output, which may be needed at higher voltages (normally, it can be omitted by closing that second jumper).

The reason for creating a separate plug is that it allows a single JeeNode to operate simultaneously on the 433 MHz and 868 MHz frequency bands. As suggested in the comments on yesterday’s post, a modded 868 MHz RFM12B can probably be made to receive 433 MHz OOK signals, but the receiver sensitivity is bound to be fairly low since the RF circuitry is really dimensioned for 868 MHz. Haven’t tried this, though.

There are several sketches which can be used with the OOK 433 Plug. To use the receiver on this board with little or no adjustment, try recv433_test.pde or ookRelay.pde. For tranmission, there is the send433_test.pde sketch.

I expect to combine and integrate code from the different OOK and relaying sketches in the near future, now that this plug has been created, but for now you’ll have to tinker with what’s available.

If you have suggestions (of better still: code or docs) for new protocol handlers to add and implement on a JeeNode, please let me know or share it on the discussion forum. It will interesting to see how many OOK protocols on 433 and 868 MHz we can figure out and implement, to make this all truly versatile for lots of different RF devices out there.

All code and docs are in the Café, with the OOK 433 Plug available from the shop, as usual.

Enjoy!

Note – This server was down on Jan 28, from about 1:00 to 10:00 (CET). I’m investigating what happened.

OOK reception with RFM12B

In Hardware, Software on Jan 27, 2011 at 00:01

A while back, JGJ Veken (Joop on the forum) added a page on the wiki on how the RFM12B can receive OOK.

I never got around to trying it … until now. In short: if you’re not afraid of replacing an SMD capacitor on the RFM12B wireless module, then it’s trivial!

Here’s what needs to be done – the capacitor on the left is 4.7 nF:

Screen Shot 2011 01 25 at 14.16.36

Unsolder it and replace it with a cap in the range 150..330 pF (I used 220 pF).

This cap appears to determine the time constant w.r.t. how fast the RSSI signal adapts to varying RF carrier signal strengths. With 4.7 nF, it’s a bit too sluggish to detect an OOK signal – which is nothing other than a carrier being switched on and off (OOK stands for: On / Off Keying).

The next trick is to connect the FSK/DATA/nFSS pin of the RFM12B via a 100 Ω resistor to AIO1 (a.k.a. analog 0, a.k.a. PC0, a.k.a. ATmega pin 23 – phew!):

Dsc 2427

As far as I can tell, this is a digital signal, so connecting it to AIO0 is really not a requirement. It might be more practical to connect it to one of the B0/B1 pins on the SPI/ISP header. Perhaps I should add a jumper in a future revision of the JeeNode PCB?

And lastly, the RFM12B must be placed in a special mode to get the RSSI signal onto that pin – i.e. compared to the RSSI threshold, also configured into the RFM12B (97 dBm).

All the pieces were there, and all I had to do was to follow the steps mentioned on the wiki page.

I made some changes to the code and added it as RF12MB_OOK.pde example sketch. Here is the main logic:

Screen Shot 2011 01 25 at 16.42.14

As you can see, all incoming data is forwarded using the normal RF12 mode packet driver.

Sample output:

Screen Shot 2011 01 25 at 16.56.39

It’s happily picking up FS20, EM10, S300, and KS300 packets, and the overall sensitivity seems to be excellent. And since it forwards all data as packets into the rest of the JeeNode network, I now have all the data coming in over a single JeeLink.

Sooo… with this “mod”, no separate OOK receiver is needed anymore for the 868 MHz frequency band!

PS. Haven’t done too many tests with this yet. Transmission is unaffected, as far as I can tell. Reception of packets with the RF12 driver still seems to work – it may be more susceptible to RF variations, but then again a “normal” packet uses FSK which is a constant carrier, so in principle this modification should not affect the ability of the RFM12B to receive standard FSK packets.

Touch screen mount

In Hardware on Jan 17, 2011 at 00:01

Electronics design is trivial compared to mechanical design, I tell you!

I’ve been looking at creating a Touch Screen option for the Graphics Board. In theory, it’s simple – just combine these two parts:

Dsc 2413

But how?

What I’d like to end up with of course, is that the touch screen is firmly held in place in front of the GLCD display:

Dsc 2414

The width of this touch panel is perfect. The touch surface is slightly higher than the 128×64 GLCD, but that could actually be used to create a couple of extra “fixed” buttons, perhaps even with some LEDs – right above the display itself (or below, if we turn the whole thing around).

It’s not hard to create a one-off mounting setup: just hot-glue the thing together, with plastic, wood, or foam-board. But that’s hardly a solution for others to replicate. And this really is one of those cases where the end result needs to look sharp, IMO. I’d really like to use this as a small self-contained unit for display and control of a few variables as part of a home-automation setup. So it better be robust. And battery powered, if possible.

The headache is the mechanical part… suggestions would be most welcome!

Gas consumption

In Musings on Dec 24, 2010 at 00:01

The gas consumption at JeeLabs is enormous these days – some 15..20 m3 per day right now. One reason for this is that our house is well-insulated but very open. All the warm air tends to move 2..3 flights up, even though we try to keep all the doors upstairs tightly shut.

The trip to Germany a few days ago provided an interesting opportunity to get a better insight in how all this heating works.

Our thermostat is set up to heat the house from roughly 6:00 (6AM) to 23:00 (11PM). It’s a fairly advanced unit with some predictive logic to attain those settings, which is why it actually starts about an hourly early:

Screen Shot 2010 12 22 at 12.53.21

The above graph shows two superimposed heating cycles, with the current one still in progress (it was around 13:00 when I took that snapshot). As you can see, the heater is almost flat out, with some extra peaks during hot water use.

Here’s the gas consumption over the past 7 days:

Screen Shot 2010 12 22 at 12.51.45

The gray bands are sunset/sunrise, ie. day/night periods.

What I did was turn down the heating on Friday morning, when we left for our trip. The normal setpoint is 19..20°C, but the thermostat has a “vacation mode” which changes that into a permanent 14°C.

As you can see, the house took almost a day to cool off. Not bad, knowing that it was permanently freezing outside at that time.

On Saturday, the heating starts up a bit again, and then stays on at a reduced level most of the time, i.e. day and night, until we got back late Monday evening. Which is when I restored the normal cycle.

The interesting bit is the end effect of getting back to normal. Here are the same readings, now as totals over the entire day:

Screen Shot 2010 12 22 at 13.21.47

Same pattern as before, of course: 17th and 18th almost nothing, then slightly lower consumption rates to keep the house at 14°C, and finally on the 21st a big push to get back to our normal comfy levels.

Here are the same values, numerically:

  • 15th – 15.71 m3
  • 16th – 16.83 m3
  • 17th – 3.52 m3
  • 18th – 5.79 m3
  • 19th – 12.40 m3
  • 20th – 14.02 m3
  • 21st – 28.16 m3

I should add that outside temperatures were a bit lower on the 19th and 20th, so these consumption levels cannot be compared 100% accurately.

But what stands out is that heating up the house back to 19..20° takes almost as much energy as what was saved on the days before. In other words: you can try to save all you like by turning the heater low when leaving the house – if you come back and want to get it back to the original level again, you basically have to add almost as much energy back in as if you hadn’t turned the heater down in the first place!

Heating is not a matter of “on = comfy, off = energy saving”, but one of keeping a whole pile of stones and concrete at a certain temperature. And this holds true even in very cold times. Apparently, the amount of stored energy is substantial compared to the amount of energy loss, and having a slightly cooler house doesn’t affect the rate of energy loss all that much.

This probably also explains why our gas consumption can still be 25% lower than average in this neighbourhood, despite the fact that many people are away and work elsewhere – while I keep the house heated all day long… (just a bit more sparingly than most, I guess).

Popping fuses

In Hardware on Dec 13, 2010 at 00:01

The power-line isolation saga continues…

Danger High Voltage alt 1 md

Ok, so the idea of adding an extra RCD device which trips on differences in current turns out to be a mistake. It adds no extra protection when used in the secondary winding of such a setup. I will leave it out.

Next step was to hook up the circuit as described in the above post. Soldered evertyhing in place, used heat-shrink tubing to isolate the loose ends, lots of hot-glue to fix things, and then:

Dsc 2398

POP, said the 5A “slow” fuse – and the next one too!

That’s not just a molten piece of metal, BTW, that’s a vaporized coating on the left. I suspect that the current was substantially over 5 amps. But no ill effect on the rest of the house, no lights dimming, and no other blown fuses (the main ones downstairs are all 16A).

Uh oh, something is wrong. Well, at least I now know the fuse works!

Here’s the plan again:

Ah, wait, not quite! … I have a transformer with dual secondary windings:

Screen Shot 2010 12 12 at 12.36.53

What I did was wire them up in parallel:

Screen Shot 2010 12 12 at 12.37.03

And that’s where I went wrong. Each winding generates an AC voltage. There are two ways to put them in parallel. Connect them right, and you get twice the power – connect them in reverse, and one will generate an AC voltage which is exactly opposite in phase w.r.t. the other winding. The result is not just a short circuit, but two power sources actively counter-acting each other:

Screen Shot 2010 12 12 at 12.42.00

Hence the blown fuses. I did not expect a 300 VA transformer to blow a 5A fuse, which implies its power draw was over 1100 watt – but that’s exactly what happened.

The solution is simple, once you step back and think about it. Instead of connecting the windings in parallel, I need to connect them in series:

Screen Shot 2010 12 12 at 12.37.11

(and the same on the other up-converting transformer too, of course)

Here’s the key: it’s still possible too hook them up the wrong way. But doing so will simply lead to no ouput, i.e. zero volts, instead of the desired double voltage output. But no blown fuse.

Once I made this change (which required a lot of undoing), I found out that the transformer secundaries were indeed wound the other way than their wires had initially led me to believe.

Problem solved!

I now have a working isolation setup which turns a 230.3V input voltage into a 230.9V output voltage under no load. An 80 watt test load worked fine.

P.S. I also gained more respect for AC “power”: such circuit mistakes are a different ball game from fiddling around with an AA Power board and getting all sorts of microcontroller- and sensor hookups messed up!

RCD finally in

In Hardware on Dec 10, 2010 at 00:01

Remember the weblog post about mains voltage and my plan to work on some circuits involving high voltage?

Well, with fear and trepidation I can announce that the missing link has finally arrived:

Dsc 2397

That’s an “Aardlekschakelaar” in Dutch, i.e. a Residual-current device.

People are probably either very thankful or very afraid of this thing, judging by the number of acronyms under which it is known: RCD, RCCD, RCCB, GFCI, GFI, or ALCI – take your pick!

An RCD continuously compares the current in with the current out, and breaks the circuit once the difference exceeds a certain threshold. I decided to get the most sensitive one I could find, which trips at 10 mA. I’m terrified of electric shock – especially the non-lethal kind… (no idea about the other variant, and I intend to keep it that way).

Ok, so it took over a month from ordering the RCD to getting it delivered – from a mail-order company here in the Netherlands, go figure. I’ll build the RCD into my super-duper isolation jig as soon as I find some time. I sure don’t want to fiddle with 230V while distracted or in a hurry.

Speaking of which…

There are a large number of people waiting for orders from the JeeLabs shop right now, for which I offer my sincere apologies. The reason is not really lack of time (well, maybe a little…), but the fact that stocks have run out on several items. I’ve got just about everything that’s missing on order right now, but in some cases my hands are tied because things don’t always arrive as quickly as promised or expected.

I’ve been refraining from sending out partial shipments, because it doesn’t really make much sense most of the time (sending out a JeeNode without the matching JeeLink, for example), and because it adds substantially to my overhead. Which is of course my own concern, but it also raises the chance of mistakes, something which I really want to avoid.

Not everything is in yet, but I hope to have just about all shipments ready by this weekend. Please get in touch if you’d rather have a partial shipment sent out soon, rather than waiting until next week. There will be no extra charges for such split shipments.

Crazy times around here. And the long-overdue server migration isn’t making it any easier!

P.S. Don’t get me wrong. I’m still working on quite a bit of fun stuff on the side, so let me finish this slightly panicky post with a little smiley anyway :)

Meet the new Room Board v2

In Hardware on Nov 28, 2010 at 00:01

For some time now, the Room Board kit has been outfitted with a new PIR sensor:

It’s nicely low-power, but unfortunately it has a pin-out which differs from the ELV model, even with 3 pins!

So I’ve decided to make a new Room Board v2, which drops support for the 8-pin ePir to allow the new PIR sensor to be mounted in two different ways.

Here’s the board, with a solder drop already applied for the SHT11 (much easier to solder it in that way):

Dsc 2345

Things have been moved around a bit, but the basic setup hasn’t changed. The 3 pins in the top left are still for the ELV PIR, and the 1-wire DS18B20 option is still there (with fixed pinout, yeay!).

Here is the board with SHT11 and LDR soldered on:

Dsc 2348

And here are the two ways to attach the new PIR sensor:

Dsc 2350 Dsc 2349

That second setup is the most compact, but also the most inconvenient one if you ever need to make changes or reach the headers. Note that the PIR pins were soldered in as far out as possible, and that the LDR was bent sideways a bit:

Dsc 2354

I would advise to use the first setup where possible.

Having said that, here’s a complete Room Node with the (relatively) “compact” layout:

Dsc 2355

Bit of a hodge-podge, but that’s what you get when everything is kept modular.

Room Node display

In Software on Nov 17, 2010 at 00:01

Now that there’s a Graphics Board, I thought I’d make a little display with the last few readings from a couple of room nodes around here. Ironically, it’s just a 8×21 character text display for now – no graphics in sight:

Dsc 2281

The information consists of:

  • a packet sequence number (only 4-byte packets are treated as room nodes)
  • the node ID
  • the temperature in °C
  • the relative humidity in %
  • the measured light intensity (0..255)

New readings get added at the bottom, with older readings scrolling upwards.

Unfortunately, the ST7565 library doesn’t have a normal print() & println() API, so the first thing I did was to create a new wrapper class:

Screen Shot 2010 11 16 at 12.42.57

One quirk about this code is that since we’re using a RAM buffer, the ST7565 screen contents needs to be explicitly updated. I solved it by adding a poll() method which you need to call in the main loop. It’ll make sure that the display gets refreshed shortly after anything new has been “printed” (default is within 0.1 s).

Another thing this class does is to scroll the contents of the display one line up when the bottom is reached. It does this in a slightly lazy manner, i.e. the display is not scrolled immediately when a newline is sent to it but when the first character on the next line falls outside the display area – a subtle but important difference, because it lets you use println() calls and the display won’t constantly leave an empty line at the bottom.

Scroll support does require one change to the “ST7565.cpp” source code. This:

    static byte gLCDbuf[1024];

Has to be changed as follows, to make the RAM buffer accessible from other source files:

    byte gLCDbuf[1024];

(should be around line 42 in ST7565.cpp)

With that out of the way, here’s the glcdNode.pde sketch, which has been added to the RF12 library:

Screen Shot 2010 11 16 at 12.53.36

For debugging purposes, the same information shown on the display is also sent to the serial port:

Screen Shot 2010 11 15 at 02.24.28

Note that gldeNode is hard-coded to receive packets from net group 5 @ 868 MHz, as you can see in the call to rf12_initialize().

So now I have a battery-powered wireless gadget which lets me track what our house is trying to tell us!

Update – the ST7565 library needs to be changed a bit more, I now realize. Perhaps the easiest way to do so is to simply insert the following line somewhere near the top of ST7565.c:

    #define buffer gLCDbuf

That way, the buffer will have a more meaningful name when made global by the above-mentioned patch.

Update #2 – no more need for the ST7565 library, use the new GLCDlib instead. The glcdNode demo sketch has been adapted and moved over to it.

Meet the Infrared Plug

In Hardware, Software on Nov 12, 2010 at 00:01

The new Infrared Plug needed a small adjustment to work, but now it’s working properly. Here’s my hand-soldered prototype:

Dsc 2243

Fits on any of the JeeNode ports, of course. The DIO pin controls the IR output, which is pulsed at 38 KHz (38.28 KHz on my unit, more than close enough). The light is generated with one or two IR LEDs. With one LED, the peak current is ≈ 50 mA (a bit high for the AA Power board) – with two LEDs, the current is ≈ 10 mA. That will no doubt have a lower range, but you could tape one of the LEDs onto a specific appliance, while still letting the other one shine into the room (or a second device).

The input is a 38 KHz detector, with its signal available on the AIO pin.

The “InfraredPlug class” in the Ports library makes it easy to interface to this plug, as described in recent posts.

I’ve also added an “ir_repeater.pde” demo sketch, which repeats any NEC command it receives three times, at 1-second intervals. When I press “Forward” on my Apple Remote, it’ll end up skipping 3 extra songs forward. Can’t quite think of a use for that, but it helped me flesh out the bugs:

Screen Shot 2010 11 11 at 18.16.58

There is a bit of logic in there to convert the incoming slot count to a bit pattern.

Sample output:

Screen Shot 2010 11 11 at 18.16.51

The Infrared Plug is now in the café and the shop.

IR packet decoding

In Software on Nov 10, 2010 at 00:01

The InfraredPlug class in the Ports library has been extended with a decoder which tries to recognize the incoming IR pulse trains. Remember that the data is returned as a list of on/off times, returned as multiple of the “slot size” given to the InfraredPort constructor on setup.

I merely added a new “decoder()” member:

Screen Shot 2010 11 09 at 12.16.09

It currently only recognizes the NEC protocol, which is what three of my remotes here use. The NEC packets have 32 bits of payload (or no bits at all in the case of a “repeat” packet).

Here’s is how the ir_recv.pde sketch calls this new decoder:

Screen Shot 2010 11 09 at 12.19.35

Sample output from three different buttons on three different remotes each:

Screen Shot 2010 11 09 at 12.52.03

The first remote (starting with 246) shows a “classical” NEC remote, where each second byte is the 1’s complement of the one before it.

The second remote (starting with 162) uses 1’s complement only on the command bytes at the end.

The third remote (starting with 119) is an Apple Remote which uses the extended NEC format, and presumably another way to check the validity of received packets.

Full details about the NEC and other protocols can be found on San Bergman’s page.

Almost, but not quite

In Hardware on Nov 9, 2010 at 00:01

There’s a new Infrared Plug in the works – it’s almost ready. The IR transmitter uses the venerable 555 chip:

Screen Shot 2010 11 08 at 20.36.42

I used the formulas from the datasheet to calculate the different resistor and capacitor values to arrive at 38 KHz, which is the most common IR frequency (and which most 36 and 40 KHz systems will pick up as well).

To check things out, I hooked the plug up for constant oscillation (DIO to +3V):

Dsc 2235

Despite using 1% parts for all the timing critical components, the output isn’t quite what it should be:

Screen Shot 2010 11 08 at 20.33.12

That’s 35.5 KHz … i.e. almost 10% off target!

(note that I measured the signal across the transistor – the IR current is actually the opposite, i.e. fast rise time)

I’ll have to tweak one of the resistors empirically (16.0 kΩ i.s.o 17.4 kΩ seems to fix it) and order some new SMD values. And then I need to check that the frequency across multiple plug builds will remain within bounds.

Not quite back to the drawing board (the PCB seems to be ok), but still: back to the soldering iron!

Isolation

In Hardware on Nov 7, 2010 at 00:01

There’s no escape… I have to get into mains voltage stuff and try some things out. All 220 volts of ’em!

I want to experiment with power measurement, power control, dimming, an such – but, ehm… preferably in a way which will let me live to tell the story! (how’s that for dedication to this weblog, eh?)

Now the thing about electricity is that it’s not the voltage that kills you, it’s the current – after all, if this weren’t the case, all the birds on high-voltage wires would be dropping dead out of the sky…

Current means: electricity going from A to B. And the problem with us human beings is that we are conductors – which isn’t too surprising, given that we’re mostly made of water anyway (the rest is hot air, I’m told).

So the first thing to do is to isolate myself from AC mains, by not allowing a ground path to carry any current. This can be accomplished with an “isolation transformer”, i.e. a transformer from 220V to 220V which – like any normal transformer – creates a galvanic isolation barrier:

Screen Shot 2010 11 06 at 20.25.22

Trouble is, these transformers are relatively expensive. One reason for this could be that you want to get a fair amount of power across, so these are hefty units with a lot of copper, iron, etc. in them!

Fortunately, there’s a simpler way to accomplish exactly the same using two back-to-back normal transformers:

Screen Shot 2010 11 06 at 20.26.38

The first one is a normal step-down transformer, producing 10.5V – and then we simply take a second one of the same type, and connect it the “wrong” way around.

There will be losses, so the output voltage won’t be exactly 220V, but I’m fine with that. In fact, it’s a nice test to see what a mains circuit will do with a somewhat lower voltage.

I’m going to use a pair of beefy 300W transformers I have lying around here, which will let me test some control and measurement options up to at least 250 Watts or so. Here are the main ingredients, which I’ll put in a wooden box with slots for natural convection. This dual wine bottle unit looks like a good fit:

Dsc 2212

(I told you they were hefty tranformers – each of them weighs several kilo’s!)

What this gives me, is an isolated source of mains-like AC voltage. It is still just as lethal when touching both power lines. The only safety this adds, is that touching a single high-voltage output wire is now harmless.

The other benefit is that an accidental short will limit the amount of current that can flow through this setup, thus also limiting heat and damage somewhat. But 300W of power is still a huge amount, so I have no illusions that things won’t break. It’s mostly to prevent fires and burnt-out cabling.

Evidently, this thing needs a switch with indicator light, and fuses: a 5 Amp fuse on the input, and a 4 Amp resettable fuse on the output (lowest I could find):

Dsc 2213

Scary stuff. I could set up a pair of much lower-amperage transformers for loads up to 25 Watt or so, but it’d still be potentially lethal, so that would only lead to a false sense of security.

The low-voltage / high-amp intermediate circuit does provide an option to insert a fast-acting fuse. A 100 mA fuse @ 10.5 VAC would translate to 5 mA @ 220 VAC, which is no longer lethal, but I’m not willing to “prove” that! Trouble is that such a setup would blow its fuse with anything over 1 Watt of power, even if only a power-up spike.

Here’s the whole contraption (not wired up yet) – with thanks to Ikea for the “front panel”:

Dsc 2214

I’ll finish this isolation setup for some experiments, but it won’t alleviate much of my fear. Unfortunately, there’s simply no other way to get going…

Meet the new Opto-coupler Plug

In Hardware on Oct 29, 2010 at 00:01

The plug barrage continues…

This time it’s an update of the flawed Opto-coupler Plug, which only worked properly on one channel (unless you patched it up). So here’s the new Opto-coupler Plug v2:

Dsc 2185

Wait! There’s more! It’s actually two plugs in one now:

Dsc 2186

(note: the solder jumpers need to be shorted out to use this as an output board)

Since there was enough room on this board, I decided to make it more versatile: it can now be used as dual Opto-coupled input (as before) or as dual Opto-coupled output plug. In the latter case, the JeeNode drives the IR LEDs and the output is a phototransistor which can be used as low-power (polarized) switch for some external device. The choice is determined by how the IC socket and Opto-coupler are hooked up.

The connectors are the same as before: detachable screw terminals, these are very convenient because you can prepare the wiring elsewhere and then plug / unplug / swap channels as needed.

I have no immediate use for these plugs right now, but of course I had to make sure that everything is working properly, so I hooked both of them up:

Dsc 2190

On the back you can see how things were connected together:

Dsc 2191

Here’s the updated opto_demo.pde test sketch for that – I decided to send the results by wireless for a change:

Screen Shot 2010 10 28 at 18.11.23

Sample output on my central JeeLink:

Opto Output

Yippie – looks like it’s working exactly as intended! Note the inverted signals, BTW.

Docs and shop have been updated for this new plug version. If you have version 1, please let me know and I’ll send out an updated board to you.

Meet the Current Source Plug

In Hardware on Oct 28, 2010 at 00:01

Here’s another new plug, firmly in the realm of home automation: the Current Source Plug drives two independent channels of Power LEDs with either 350 mA or 700 mA current:

Dsc 2183

As you can see, this plug was a very tight fit. These are based on high-efficiency AP8803 switching power supply chips, which also explains the two hefty inductors on the board. The 2 I/O pins are used to control both channels, and can use PWM to dim the LEDs.

The connector on the bottom is for the LED power supply (sorry for the tight fit!), and can be 8..30V. According to the specs, you can have up to 5 power LEDs in series at 30V, so the highest power this plug can theoretically switch is 5x 3W-LEDs @ 700 mA per channel!

There are some thermal limits though, due to the high amount of power involved in this small board. It is best to keep the voltage differential between what the LED needs and the input voltage fairly low. The two 3.7V LEDs I tried worked fine at 6..12V, but the board started heating up quickly with more than 12V (at full power).

Here’s the test setup I used:

Dsc 2182

The big LED is set to 700 mA, the small one to 350 mA – for a total of 1050 mA output. The nice part is the efficiency of this thing: the board draws less than 1050 mA due to the “buck” switching design. I measured roughly 960 mA @ 6V and 490 mA at 12V. At 18V it heated up a lot, I did not dare take it any higher. The main use I see for this board is two channels, each with 1 or 2 power LEDs in series, driven from a 12V supply.

At full power, the board temperature rose about 40°C above ambient after an hour, i.e. roughly 60..70°C. Hot to the touch, but not scorching hot. When dimmed, temperatures immediately went down. Note that the LED lights themselves were hotter than the board. Power LEDs need cooling!

For PWM dimming up to 500 Hz, just use the I/O pins. I haven’t tried it yet, but this could be done with the same rgbRemote.pde sketch as used for the MOSFET plugs.

The documentation and shop have been updated with this new plug.

More goodies coming, stay tuned…

Reporting motion

In AVR, Software on Oct 21, 2010 at 00:01

Yesterday’s post presented a new sketch which did everything the old sketch did, except report motion. The reason was that the requirements for reporting motion are quite different from the rest: it has to be reported right away – using ACKs, time-outs, and retries to make sure this message is properly received.

The latest version of roomNode.pde now adds the missing logic. And it does indeed get a lot messier – doubling the total number of lines in the source code.

Here is the new loop() code:

Screen Shot 2010 10 19 at 22.37.41

The key change is that there is now a check for “pir.triggered()” which will be called outside all normal scheduling actions. Note that this code is still using scheduler.pollWaiting(), so the code is still spending most of its time in power-down mode.

Except that now, we’re also setting up a pin-change interrupt for the PIR sensor:

Screen Shot 2010 10 19 at 22.40.16

The new code to handle these PIR triggers is as follows:

Screen Shot 2010 10 19 at 22.42.14

So instead of folding this complicated case into the rest of the code, when a PIR trigger goes off, we now simply send that packet out and wait for the ACK, repeating it a few times if necessary. The normal measurement and reporting tasks are not affected by any of this, other than that the measurement scheduling is postponed a bit to avoid triggering another report right away.

The new PIR motion sensor turns out to be quite convenient, because it has an on-board trimpot to set the re-trigger timeout. As long as motion is detected more often than this threshold, the PIR output will remain 1, so there is no need to play tricks in software to avoid constant triggers. We’ll get one pin change for the start of motion, and another one when no motion has been detected for a preset amount of time.

Having said that, I’ve implemented a similar re-triggerable one-shot mechanism in software anyway, because my older nodes use the ELV PIR sensor, which send out a pulse for each motion trigger. So all ON pulses within 30 seconds of each other get coalesced into one.

To illustrate that the system is still doing almost nothing most of the time, I added a debug mode which prints a “.” on each iteration of loop(). In normal Arduino sketches, this would cause an incessant stream of characters to be printed out, but in this sketch there are just a few:

Screen Shot 2010 10 19 at 22.12.35

Motion detection now works more or less independently of the normal measure / report tasks.

There are still some rough edges, but I expect this new code to perform considerably better in terms of battery lifetime already. The dreaded battery rundown problem when the central node is not reachable should be gone. All that remains are a few attempts (I’ve set it to 5) whenever the PIR sensor turns on or off. In both cases the ACK has to be received within 10 milliseconds – after that the sketch enters power-down mode again.

The new code should also make it much easier to add sensor types (switches, hall-effect, 1-wire, barometer).

FWIW, this code needs 8238 bytes (without serial I/O), so it’ll still easily fit in an ATmega168. Without SHT11 (which uses floating point) that drops to 5682 bytes, including the RF12 driver. How’s that for a WSN node!

New roomNode code

In AVR, Software on Oct 20, 2010 at 00:01

It’s time to start putting the pieces together now: sensor readout, scheduling of measurements and packet sends, and low-power mode. Looks like the code in the Ports and RF12 libraries is now making this easier than ever.

There’s a new roomNode.pde sketch which illustrates the whole shebang. At 145 lines, it’s a bit too long to include here in full, but I’ll show some of the interesting pieces.

Note that this version implements everything except motion reporting, which is a bit more complex.

Following the good ol’ top-down tradition, first the setup() and loop() code:

Screen Shot 2010 10 19 at 14.06.12

It starts the measurement loop, which then keeps itself running periodically. The report activity is started every once in a while. Note also the “now” variable, which will make it easier to use 2-byte ints in the logic which will decide later about when to report motion, etc.

The measurement code depends completely on what sensors are supported, and is pretty straightforward:

Screen Shot 2010 10 19 at 14.10.36

No surprises, we just have to be careful to do things in an energy-efficient manner. All the readings end up in the “payload” struct.

And here’s the reporting code:

Screen Shot 2010 10 19 at 14.14.24

Here’s some sample output on the serial port:

Screen Shot 2010 10 19 at 14.18.17

I still need to add the logic for motion detection, but with the new scheduling capabiltities, I expect that extra complexity to stay within a small portion of the code – unlike the current rooms.pde sketch, where everything seems to affect everything else.

The best part? My multimeter stays mostly under 60 µa, i.e. the low-power logic is automatically kicking in!

Modular nodes, revisited

In Software on Oct 16, 2010 at 00:01

As pointed out in the comments yesterday, “nodes” in a WSN should to be more parametrized. With ports, it’s very easy to mix and match different sensors – creating nodes which are not all the same should be equally easy.

I’ve touched on a related topic before in a post titled Modular nodes.

Ideally, you want to write interface code for say a PIR motion sensor once, and then re-use it in different nodes. Same for an SHT11 temperature/humidity sensor, an IR send/receive sensor, a barometer, door switches, an OOK receiver, and so on – the list is bound to grow considerably over time.

Even “more ideally” (heh), you probably would like someone else to already have written that interface code, so you can just fill in the parameters and incorporate it into your own room-or-other node.

In fact, the whole (modular!) Plugs & Ports concept of JeeNodes is yearning for this type of modularity to be carried through to the software.

To achieve such modularity all the way through, several questions need to be answered:

  • are these interface code “snippets” always very small and self-contained, or do they need additional C/C++ source files?
  • can interfaces depend on other interfaces / is a class hierarchy the best way to modularize such dependencies and derivations?
  • can we have multiple instances of the same interface in a single node? (answer: yes, for example multiple door-open sensors, attached to different I/O pins)
  • how do we deal with a mix of interfaces which use different timing periods for readout?
  • how do we compose packets to send, if the information types vary?

One way to implement this modularity, is what I’ve been doing in the Ports library until now: define and implement C++ classes for each interface, and then create (static) instances of each interface needed in a particular node.

This is an extract of the Ports.h library header file:

Screen Shot 2010 10 15 at 21.54.25

It works – and I think it’s a decent start – but it doesn’t go far enough:

  • Many configuration parameters are variables (and data members inside C++ objects), even though they are essentially contant (the port number, an I2C device ID, I/O pin choices, etc). This eats up scarce RAM space, and prevents the compiler from fully optimizing the code. The “heavy” solution to this is C++ templates, as I’ve written about in threeolderposts. Trouble is: C++ templates are “viral”, once you start on that path, everything tends to become a template. Not my idea of simplicity…

  • I want to figure out what a good set of reporting periods is, to minimize the number of packets sent, for example. This task comes back with every type of node, so having some automated tool to help with that effort would be useful.

  • There can be severe resource constraints in low-power nodes. I’d like to see what the RAM and EEPROM (and FLASH) usage is when choosing a specific mix of interfaces. I’d also like to find out whether the interrupts can co-exist and still service everything sufficiently quickly. And I’d like to get estimates for battery life. None of this is impossible, even if unnecessary for a first implementation.

  • Implementing pin-change interrupt handlers is not easy to fit into C++ as run-time mechanism, even though for any given interface mix it is very simple to generate the interrupt handler code for it.

  • The result of a choice of interfaces is not just a sketch – it also implies specific packet structures, as used for getting data across. And indirectly, it also means there has to be something node-specific at the central node (not necessarily in that receiving node, it could be code that runs on an attached PC).

  • If the number of interfaces grows considerably, and if more people were to start implementing such interfaces, then the management and versioning of all these interface definitions (code, data, docs) needs to be addressed.

What this points to IMO, is the need for a “configurator” or “wizard” type tool, which knows about a large number of interfaces, and which produces a sketch when given a bunch of configuration choices. An even more convenient tool would let me manage my entire collection of nodes, so I can make most configuration choices once, and then manage all node definitions together. It’d let me add and update interfaces and nodes as needed, over time:

Screen Shot 2010 10 15 at 22.30.14

What comes out is still a C/C++ coded sketch, since that’s what needs to be uploaded to the node.

What should also come out (not included in the above diagram), are one or more packet structure definitions, as well as the code (or data definitions) needed to decode those packets again.

With this approach, you can pick the hardware needed for a specific node, enter your choices into the configurator, and be done with it. Upload the sketch it generated, turn the node on, and launch the central server with the information it needs to understand the new incoming data packets. For other nodes, or to make changes, simply rinse and repeat…

I haven’t decided yet whether I’ll actually go for this. It’s fairly ambitious, even for a simple first implementation. But it sure would scratch an itch of mine…

Room Node redesign

In Software on Oct 15, 2010 at 00:00

Room nodes were one of the first reasons I came up with the JeeNode in the first place. It has all evolved a bit since then (and it will evolve further until there is a good enclosure):

Dsc 2134

It’s now time to start redesigning the software for Room Nodes. The main reason being that the code needs to take more advantage of all the low-power savings achievable with JeeNodes. Current battery lifetimes are 1..2 months, using 3x AA alkaline batteries. That’s not nearly good enough – I really do not want to go through the house replacing tons of batteries every month or so (even rechargable ones).

I can think of two reasons why the current rooms.pde sketch isn’t doing that well:

  1. The “easy transmission” mechanism does retries when no ACK is received – this is a good idea in general, but there is no exponential backoff mechanism in place in case the central node is off, mal-functioning, out of range, or if there is simply too much interference at times. What’s even worse is that the node sits there waiting for an ACK for many seconds, guzzling electricity like crazy with the RFM12B and the ATmega full on!

  2. The code sends out a fresh packet on each transition from the PIR motion detector. If the sensor is in a room where motion is very common, then new packets may get sent out far more often than necessary – and quickly drain the battery.

So the question is how to improve on this. One thing I’m going to do is side-step the rf12_easyPoll() etc. interface for the next Room Node implementation, and go back to rf12_recvDone() etc. Coding at this slightly lower level is more work, but also gives me substantially more control in return.

Next, some decisions need to be made about how often and when to send out packets, and when to work with acknowledgements. Here are some of my considerations for that – evidently not everyone will agree with this set of choices, but I think they are sufficiently general to work in many cases:

  • Temperature, humidity, and light levels need only be sent out once per five minutes. Perhaps averaging the values once a minute to smooth out measurement variations.

  • No need to use ACKs for this. Not knowing the exact temperature for the past hour is not the end of the world. The new logic can just send out readings once every five minutes, with the expectation that most of them will usually come in just fine.

  • The PIR motion sensor is a completely different matter: I’d like to be told when new motion is detected as quickly as possible, i.e. within less than a second.

  • Then again, once motion has been detected, I don’t really care too much about frequent vs. infrequent motion. Telling me once a minute whether any motion was detected in that past minute should be enough.

  • Once motion ceases to be detected for a minute, the system goes back into its highly responsive mode, i.e. the moment new motion is detected, I want to hear about it again, right away.

  • The system could send different packets for different triggers, but I don’t want to complicate things unnecessarily. My expectation is that in a room with no motion, there will be one packet going out every 5 minutes, with one “wasted” bit for the motion detector state. In a busy room, there will be a packet going out up to once a minute due to the motion detector firing all the time. The number of bytes saved is probably not worth the extra trouble of having to deal with different types of packets at the receiving end.

  • The last reason to send out packets, is when the battery voltage of the sensor node is getting low. This can be checked once a minute, along with the temp/humid/light cycle.

  • Changes in motion or battery level are important events. These should use the acknowledge mechanism to make sure the event gets to its destination even with occasional packet loss.

  • The mechanism for acks needs to be more sophisticated than it is now. The first big optimization is to only wait a few milliseconds for the ACK. If it doesn’t come in, go back to sleep, and try again a second later. That should by itself reduce the current worst-case current draw by two orders of magnitude.

  • Refinements such as exponential back-off would be nice, but I don’t expect them to make that much of a difference, in a home monitoring setup where all serious failures are likely to be noticed and resolved within a day.

  • Another refinement I don’t care too much about, is to adjust the 5-minute reporting interval depending on the measured light levels. Note that this does not apply to motion (which must always remain alert) – it’s just a way to reduce packet transmissions even further at times when very little happens anyway. I’m not sure it will increase battery life that much, though: brief packet transmissions are not the main power drain, the always-on PIR is the main determinant for battery life, as far as I can tell.

The highest packet frequency for this new approach is almost two packets per minute: motion is detected, then one minute later a packet comes in reporting that it is no longer being detected, and then immediately after that new motion is detected again.

So if you sit still in front of a Room Node, and move exactly once every 61 seconds, you’ll get extra brownie points and trigger twice as many packets as when you move around all the time. I’m willing to dismiss that scenario as being almost hypothetical :) – I can’t prove it, but my hunch is that this worst-case scenario will always exist, no matter what the algorithm is.

IR decoding with pin-change interrupts

In AVR, Hardware, Software on Oct 14, 2010 at 00:01

Yesterday’s post described a new “InfraredPlug” class which handles the main task of decoding IR pulse timings. The “irq_recv.pde” example sketch presented there depended on constant polling to keep the process going, i.e. there has to be a line like this in loop():

    ir.poll();

Worse, the accuracy of the whole process depends on calling this really often, i.e. at least every 100 µs or so. This is necessary to be able to time the pulse widths sufficiently accurately.

Can’t we do better?

Sure we can. The trick is to use interrupts instead of polling. Since I was anticipating support for pin-change interrupts, I already designed the class API for it. And because of that, the changes needed to switch to an interrupt-driven sketch are surprisingly small.

I’ve added a new irq_send_irq.pde sketch to the Ports library, which illustrates this.

The differences between using polling mode and pin-change interrupts in the code are as follows. First of all, we need to add an interrupt handler:

Screen Shot 2010 10 13 at 00.26.10

Second, we need to enable those interrupts on AIO2, i.e. analog pin 1:

Screen Shot 2010 10 13 at 00.26.44

And lastly, we can now get rid of that nasty poll() call in the loop:

Screen Shot 2010 10 13 at 00.27.51

That’s all there is to it. Does it still work? Of course:

Screen Shot 2010 10 13 at 00.29.16

Note: I made some small changes in the InfraredPlug implementation to tolerate interrupts and avoid race conditions.

This all seems like an insignificant change, but keep in mind that this completely changes the real-time requirements: instead of having to poll several thousands of times per second to avoid missing pulses or measuring them incorrectly, we can now check for results whenever we feel like it. Waiting too long would still miss data packets of course, but this means our code can now continue to do other lengthy things (or go into a low-power mode). Checking for incoming packets a few times a second is sufficient (IR remotes send out a packet every 100 ms or so while a button is pressed).

So the IR decoder now has the same background behavior as the RF12 driver: you don’t need to poll it in real-time, you just need to check once in a while to see whether a new packet has been received. Best of all, perhaps, is that you can continue to use calls to delay() even though they make the main loop less responsive.

There is another side effect of this change: if your code includes a call to “ir.send()”, then the receiver will see your own transmission, and report it as an incoming packet as well. Which shows that it’s running in the background. This could even be used for collision detection if you want to build a fancy IR wireless network on top of all this.

So there you go: an improved version of the InfraredPlug class, which lets you use either explicit polling or pin-change interrupts. The choice is yours…

Decoding IR pulses

In Hardware, Software on Oct 13, 2010 at 00:01

After the last few posts, it must come as no surprise that I’ve been working on a new Infrared Plug – so now it’s time to start exploring the software side of things. Note that IR reception doesn’t really need a plug at all, I simply inserted a TSOP32238 IR decoder chip into port 2 while debugging the code:

Dsc 2129

Note: I’ll be using the TSOP34838 for the planned Infrared Plug. It only differs in pinout (!) – and both can be used at 3.3V, which is essential.

In preparation of that new plug (atoms need time!), I’ve added a new “InfraredPlug” class to the Ports library, with the following interface:

Screen Shot 2010 10 12 at 17.30.37

This allows receiving IR codes on the AIO pin of any port, as well as sending out IR bit patterns on the DIO pin.

There’s a new ir_recv.pde sketch to demonstrate reception of arbitrary IR signals:

Screen Shot 2010 10 12 at 17.33.59

Here is some sample output, using two different Apple remotes which send using the NEC protocol, as described on this excellent site by San Bergmans:

Screen Shot 2010 10 12 at 16.49.22

You’re looking at a decoded bit stream – some minor processing will be needed to extract the actual data bits from each packet. This was done to make the decoder as flexible as possible – allowing it to handle all sorts of remotes.

The basic idea is that you set up the InfraredPlug instance with “slot” and “gap” parameters. The slot value (1..255) specifies the granularity of the time slots used by the decoder (in units of 4 µs). The default slot value is 140, this corresponds to time slots which are 560 µs wide. De gap value tells the driver when to consider a data packet as being complete (in units of 256 µs). The default gap value is 80, i.e. treat a series of pulses as one packet once 20 ms have elapsed after the last pulse.

The values can be changed with the “configure()” method. In fact, ir_demo will change the slot value when it receives an integer followed by lowercase “s” on the serial port (not echoed). The default setting on startup is “140s”. For RC5 codes, use “222s”, for RC6 “111s”, and for Nokia remotes “125s”, to name a few.

Each time a packet has been received, ir_demo will send the decoded data to the serial port. The data consists of a series of hex digits, each representing one 4-bit nibble of data, as returned by the InfraredPlug class:

  • 0..9 = 1..10 slots
  • A = 10 = 11 or 12 slots
  • B = 11 = 13 or 14 slots
  • C = 12 = 15 or 16 slots
  • D = 13 = 17 or 18 slots
  • E = 14 = 19 or 20 slots
  • F = 15 = 21 or more slots

The nibbles at even positions correspond to pulse ON widths, the nibbles at odd positions are pulse OFF widths – both as a multiple of the configured slot time, with the above adjustment of longer pulses applied.

The “send()” method uses a different format. You give it a bit pattern and the number of bits to send. Each bit represents an ON or OFF signal value. The duration of each bit is the same slot value as used in the receiver.

That’s it. A simple design which should be able to support lots of different appliances and remotes.

IR pulse pickup

In Hardware, Software on Oct 11, 2010 at 00:01

With the sending of IR pulses out of the way, the next step is picking them up. That’s a lot simpler since there are various sensors which do this.

But unfortunately I only have a QSC113 IR photo transistor at hand right now. It doesn’t have any sort of 38 kHz filtering, it just senses IR light. Then again, it still seems to work – I don’t understand why, to be honest:

Dsc 2123

Anyway, this seemed like a good test case to throw at the OOK Scope. The name is a bit confusing actually – it was used to analyze OOK-encoded radio signals a couple of months ago, but it’s really more general than that. What the OOK Scope does, is create a histogram of incoming pulse widths (20 .. 4604 µs with the current code).

As a refresher, here’s some OOK Scope output with a 433 MHz radio attached, after pressing buttons on my KAKU remote control:

Screen Shot 2010 10 10 at 22.06.54

The histogram runs sideways: at the top are the short pulses, at the bottom the long pulses. The longer the bar, the more pulses of that length have been picked up.

Now the fun part is that this same setup can also be used for IR pulses:

Dsc 2122

I simply replaced the OOK radio in port 2 by my IR photo transistor, with the short lead to GND and the long lead to AIO2. Here’s what comes out when using the Apple remote:

Screen Shot 2010 10 10 at 22.47.36

The pulses are a lot sharper, which is not surprising since it’s picking up direct light pulses now, not radiomagnetic waves of a much lower frequency and intensity that has to be detected and converted into an electrical signal by the radio.

Reading these values is a bit more work, because the ookScope.pde does some trickery to increase the range of pulse widths it can report in a single byte:

if (width >= 128) {
    width = (width >> 1) + 64;
    if (width >= 192) {
        width = (width >> 1) + 96;
        if (width >= 224) {
            width = (width >> 1) + 112;
            if (width >= 240) {
                width = (width >> 1) + 120;
                if (width >= 248) {
                    width = (width >> 1) + 124;
                    if (width >= 252) {
                        width = (width >> 1) + 126;
                        if (width > 255)
                            width = 255;
                    }
                }
            }
        }
    }
}

See the OOK Scope post for details on how this works.

Back to the readings. The values reported are two strong bands centered around ≈ 105 and 158, respectively, with another set of pulses at 224. The pulse widths corresponding to these are ≈ 420 µs, 652 µs, and 1536 µs if I got my calculations right. That last one might be the time between retransmissions.

I’ll have to revisit this with a real 38 kHz filtering IR sensor when I get them in – but that sort of looks right to me. Another remote sending out RC5 codes ended up with very similar pulse widths, but with more variation.

Tomorrow, I’ll describe the OOK Scope setup in more detail, since it doesn’t seem to be working for everyone…

Update – I just figured out the pinout of a 5V sensor with IR filtering (TSOP1138) – here’s what comes out:

Screen Shot 2010 10 10 at 23.32.07

Hm, more variation now. Then again, also a lot more sensitive, it seems. And it looks like it should still be possible to discriminate between the two pulse widths at position 135, i.e. around 568 µs.

The pulse trains are now more consistent on the scope:

Dsc 2124

Note that I’m driving the JeeNode I/O pin to nearly 5V, which isn’t really such a good idea…

PS. That’ a DSO Nano scope, in case you’re wondering…

Generating IR pulses

In Hardware on Oct 10, 2010 at 00:01

There are lots of projects and schematics floating around the web for encoding and decoding IR remote-control pulses. Many MPU-based ones use one of the built-in hardware timers for this, which is understandable since you can’t easily bit-bang your way out of a 13.158 µs time between switching flanks.

But I don’t want to be constrained to a specific pin, nor dedicate a hardware timer to this task.

Instead, I’ve been experimenting with the venerable NE555. Its normal operating voltage is 4.5 .. 16V, but there’s a CMOS version which will easily go down to 3.3V, as preferred by JeeNodes.

So here’s the circuit (from the ICM7555 docs by NXP):

Screen Shot 2010 10 09 at 14.06.34

The RESET pin can turn this thing on and off. It’ll also need an extra transistor to drive a bright IR LED.

Had to try it out, of course (the chip I used wants at least 4.5V, hence the USB power):

Dsc 2118

Great. It works, but at 35.1 kHz the frequency is a bit off.

Here’s a Logic Analyzer screen shot (warning: MDI toolbar madness, flash from the past!):

Screen Shot 2010 10 09 at 23.11.14

(FWIW: my USB Scope and Logic Analyzer now both work properly on Mac OS X under Parallels 6 emulation – I no longer need a dedicated Windows setup.)

Let’s do the math for the components used in the above test setup, with RA = 1.2 kΩ, RB = 18 kΩ, C = 1 nF:

Screen Shot 2010 10 09 at 14.05.11

f = 37.09 kHz  
∂ = 51.6 %

Let’s use the 1 nF capacitor, smaller would make the circuit more sensitive to stray capacitance. Then I get:

RA + 2 RB = 36.315 kΩ

I don’t want to raise RA much, because that would change the duty cycle in the wrong direction: more LED-on time (i.e. higher current draw). I also don’t want to lower it much further, because that would draw more current in the discharge phase (pin 7 pulled low).

Using 1% resistors, RA = 1.5 kΩ and RB = 17.4 kΩ will do:

f = 38.02 kHz  
∂ = 52.1 %

The 1 nF capacitor will have to be 1% too, of course.

I think I’ll try this. What remains – as always! – is the software, to send out the proper IR bit patterns and to decode the ones coming in. It’d be nice if that could be done fully interrupt-driven like the RF12 driver, because then the whole real-time aspect of IR communication would be taken out of the loop(), so to speak.

Room Node battery life

In AVR, Hardware on Oct 6, 2010 at 00:01

The current Room Node sketch only gets 1..2 months of life out of a 3x alkaline AA battery pack. Not enough – by far – for practical use around the house.

The good news is that it’s almost entirely a software issue. There have been JeeNodes running for many months now, some up to 10 months, so there is no hardware limitation to achieve such lifetimes.

In fact, I’d like to push it a bit further and see how long one could run a Room Node off a single rechargable AA battery using the AA Power board. If it’s not that long, I could still opt for the 3x AA pack.

Let’s estimate the idle current draw of a JeeNode first.

The big consumer is the PIR sensor. I recently switched to a new one, because it only needs 3.3V and because of its low current draw. Note that the PIR motion sensor is the only component in the Room Node which should not be disabled during sleep: the whole point is to be able to detect motion at all times, after all. Also, a PIR sensor needs time to stabilize, in the order of a minute, so turning it on briefly is no option.

Here’s the good news:

Dsc 2077

That’s 41 µA idle current.

The JeeNode draws ≈ 3.3 µa, let’s round it up to 4 µA.

The SHT11 draws 2..5 µW, let’s round it up to 2 µA.

So total idle draw is 47 µA.

As it turns out, transmissions consume a neglegible amount of current – if the frequency of transmission is 5 minutes, for example (i.e. 288x per day). The motion detection is different, this needs to go out as soon as there is motion, but this probably won’t happen more than a dozen times a day, on average).

For a transmission, the RFM12B needs to be on for about 2 ms, at which point it draws around 25 mA. With 2 ms once every 300 seconds, that’s a duty cycle of 1:150000, i.e. under 2 µA when averaged out.

So let’s round up and assume that the average current draw of a Room Node is 50 µA @ 3.3V.

A 3x AA battery pack of 2500 mAh would last 50,000 hours, i.e. over 5 years if we ignore the self-discharge rate … assuming that the low-power code is perfect, that is!

Now for the AA Power Board lifetime estimate. At very low current levels, the efficiency of the LTC3525 regulator is 75..80%, according to the datasheet. But first, we need to estimate the current draw. Keep in mind that the power source will be 1.2 .. 1.3V, so we basically need a 3-fold step up. Let’s calculate the input current draw, assuming 1.2V in, 3.3 V out @ 50 µA, and 75% efficiency:

input current = 50 x 3.3 / 1.2 / 0.75 = 183 µA

With an Eneloop battery, I’ll assume it has 1900 mAh capacity, and loses 15% of its charge in two years. Let’s assume that it’ll be used no more than 2 years, and that it lost that 15% charge right at the beginning. Then this is effectively nothing more than a 1600 mAh battery.

Ok, how long can it power a JeeNode plus Room Board?

lifetime = 1600 / 0.183 = 8743 hours = 364 days

So all in all this setup should be able to run just about one year off a single rechargable AA battery. Note that there was some rounding in several places in these calculations, so these estimates are probably a bit conservative.

One year battery life… that’s in fact exactly what I was hoping for!

Now the “only” remaining challenge is to optimize the “rooms.pde” sketch enough to make this happen.

Software PWM at 1 KHz

In AVR, Software on Oct 3, 2010 at 00:01

While pondering about some PWM requirements for a new project here, I was looking at the rgbAdjust.pde sketch again, as outlined in the Remote RGB strip control weblog post from a few months back. It does PWM in software, and plays some tricks to be able to do so on up to 8 I/O pins of a JeeNode, i.e. DIO and AIO on all 4 ports. The main requirement there, was that the PWM must happen fast enough to avoid any visible flickering.

The rgbAdjust sketch works as follows: prepare an array with 256 time slots, each indicating whether an I/O pin should be on or off during that time slot. Since each array element consists of one byte, there is room for up to 8 such bit patterns in parallel. Then continuously loop through all slots to “play back” the stored PWM patterns.

There is one additional refinement in that I don’t actually store the values, but only store a 1-bit during the change of values. That shaves off some overhead when rapidly changing I/O pins (see the Flippin’ bits post).

There are some edge cases (there always are, in software), such as dealing with full on and full off. Those two cases require no bit flipping, whereas normally there are always exactly two flips in the 256-cycle loop. But that’s about it. It works well, and when I simplified the code to support only brightness values 0..100 instead of the original 0..255, the PWM rate went up to over 250 Hz, removing all visible flicker.

So what rgbAdjust does, is loop around like crazy, keeping track of which pins to flip. ATmega’s are good at that, and because the RF12 driver is interrupt-driven, you can still continue to receive wireless data and control the RGB settings remotely.

But still, a bit complex for such a simple task. Isn’t there a simpler way?

As it turns out, there is… and it’ll even bump the PWM rate to 1 KHz. I have no idea what our cat sees, but I wouldn’t be surprised if cats turned out to be more sensitive than us humans. And since I intend to put tons of LED strips around the house, it better be pleasant for all its inhabitants!

What occurred to me, is that you could re-use a hardware counter which is always running in the ATmega when working with the Arduino libraries: the TIMER-0 millisecond clock!

It increments every 4 µs, from 0 to 255, and wraps around every 1024 µs. So if we take the current value of the timer as the current time slot, then all we need to do is use that same map as in the original rgbAdjust sketch to set all I/O pins!

Something like this, basically:

Screen Shot 2010 10 01 at 01.41.11

(assuming that the map[] array has been set up properly)

No more complex loops. All we need to do is call this code really, really often. It won’t matter whether some interrupts occur once in a while, or whether some extra code is included to check for packet reception, for example. What might happen (in the worst case, and only very rarely) is that a pin gets turned on or off a few microseconds late. No big deal, and most importantly: no systematic errors!

It’s fairly easy to do some other work in between, as long as the main code gets called as often as possible:

Screen Shot 2010 10 01 at 01.51.18

I’ve applied this approach to an updated rgbRemote.pde sketch in the RF12 library, and sure enough, the dimming is very smooth for intensity levels 25..255. Below 25, there is some flickering – perhaps from the millis() timer? Furthermore, I’m back to being able to dim with full 24-bit accuracy, i.e. 8 bits on each of the RGB color controls. Which could be fairly important when finely adjusting the white balance!

So there you have it: simpler AND better! – all for the same price as before :)

Relay Plug stocks

In Hardware on Sep 30, 2010 at 00:01

As it turns out, this slim-line relay (Conrad #504286, PCN-105D3MHZ) is not available until April 2011 (gasp!) … no matter where in the world I look:

Dsc 1813 2

Fortunately, there is an equally-slim replacement with the same footprint (thanks, Lennart!):

Dsc 2007

It’s a bit higher, and it handles a bit more current (up to 5A):

Dsc 2008

I’ve ordered a bunch of these, but I also need to get a new batch of PCB’s – didn’t want to order them without a chance of getting suitable relays (Conrad #502047). The new plugs won’t be here before mid-October. And the new relays are a bit pricier, so I’ve had to raise the price of the kit a bit.

Atoms, oh atoms … why can’t you be more like bits? As in: no stocks to worry about?

Biting a mini-bullet

In Musings on Sep 28, 2010 at 00:01

After some agonizing over the infinite number of trade-offs available these days, I’ve finally made a couple of big decisions w.r.t. Internet and Jee Labs.

Until now, all the web sites for Jee Labs have been running on a rented dedicated web server located in Germany. That little setup has served me extremely well, running some 5 years with just a (precautionary) HD swap about halfway down the road. Downtime over these years has been less than 24 hours I think, in total – or as they say: “three 9’s” (99.9% uptime).

The current server machine is showing its age though, so some form of upgrade and transition is needed in the not too distant future. Preferably one which can again last 5 years or more. Content changes all the time – but a server really shouldn’t need to. It’s a commodity by now.

As it so happens, Fiber to the home (FTTH) is currently being rolled out around here at Jee Labs. Meaning: fast uploads, not just downloads. Which changes the landscape – it’s no longer necessary to rent something, a server at home will work just fine. Jee Labs is not a bank or some high-profile company setup. I don’t need a team of support personnel to get around-the-clock support. If it fails, I can fix it. And if I’m not there to fix it, then Jee Labs has a bigger problem than just its websites…

So the plan is now to move all of the Jee Labs internet “operations” to … Jee Labs in Houten, The Netherlands. Not hastily – there is no rush. But still.

Now I need a server. One which I won’t outgrow. One which won’t break – or at least if it ever does: one which is easily replaceable. I’ve traveled across the planet in my searches. I’ve seen it all. Amazingly small, amazingly cheap, amazingly powerful, amazingly robust, and amazingly simple. None of them is everything at the same time. But I did end up with a setup that fits me.

I’ve decided to base the system on the latest Mac Mini:

Server Hero 20100615

Server edition, i.e. no DVD but a second hard disk. High end stuff, more than I’ve ever plunked down for a server. Still under €0.50 a day, if it lasts and delivers over the planned 6-year lifetime. Modern in terms of capabilities, modern in terms of noise level, and modern in terms of energy consumption. I’m pleased with this decision.

Inside, it’s going to run a couple of virtual machines. That will give me a level of (manually managed) fail-over which I’ve never had before. Security is crucial, but there too, the VM’s should add some good security barriers. One of the VM’s will be used for home automation.

I’m already running parts of the setup at Jee Labs as virtual machines, so the task ahead is to continue that migration, and then bring it together on the new server.

I’ll do my best to minimize the hickups, for this weblog and for the rest of the public-facing activities at Jee Labs and Equi 4 Software. There will no doubt be some disruptions and even foul-ups. But the hard part for me is over – the direction and the goal are clear now. The rest is … just work :)

HomeSeer and JeeNode WSN’s

In Software on Sep 22, 2010 at 00:01

HomeSeer is a commercial Windows-based home automation software package. I’ve seen it demo’d a few times, but I’m not using it myself – nor do I have a license for it (I don’t have a permanent setup running Windows).

The following describes a great new development by Tijl van der Velden, who wrote a very interesting extension for HomeSeer to link into aWSN based on JeeNodes, Room Boards, plus a JeeLink on the PC side.

Tijl just finished his project, which was done as student assignment for Computer Science at the University of Utrecht. He was so kind to send pictures of his setup and screen shots of the resulting application in HomeSeer.

I’m just the messenger in this case, but I’m very happy to be able to report about this on the weblog. For details about Tijl’s project, which has been released as open source on SourceForge, visit the JeeSeer page. The code running on Windows is VBScript, as used by HomeSeer – the software on the JeeLink and JeeNodes are C/C++ Arduino-type sketches.

Here’s his test stup:

Sam 0381

You can see the JeeNode with Room Board on top (and the temperature, humidity, light, and motion sensors), as well as an extra LED and small DC motor, driven by a transistor (with the inductive kickback protection diode).

The sketch running on the JeeNode includes some very interesting customizable “decision rules”, which can be configured from HomeSeer. Here’s the customization screen:

Decision Rules 2

The sketch running on the JeeNode looks fairly generic, allowing for different devices, so that you can use the port I/O pins for various purposes – both as inputs and as outputs. From a brief look, it reminds me a bit of Firmata.

The Jeelink is also running a custom sketch, to be able to pass these special requests and replies to a JeeNode and back. As with RF12demo, you can configure the JeeLink to listen on a specific frequency band and filter out a specific net group. This is also nicely configurable from the HomeSeer web interface:

Config 2

And here is what it’s all about – sensor results and device (i.e. LED + motor demo) control:

Status Page 2

Thank you Tijl, for completing this project and for sharing your results and your code on SourceForge. You are making it possible for others to learn from what you did, to plug what you made directly into HomeSeer, and to let people extend things further as the need arises.

It’s great to see the JeeNode – domotics integration becoming a reality!

Room Node mount?

In Hardware on Sep 21, 2010 at 00:01

I’m still searching for ideas to mount a JeeNode with a Room Board, a.k.a. as a “Room Node”. Now that the AA Power Pack lets me get rid of two of the 3 AA’s, I’m sort of hoping to bump into some new and practical options.

How about this position, against the ceiling?

Dsc 1957

The PIR motion sensor is placed above an empty spot between the JeeNode and the AA Power board. It’ll need to be wired up in that position, of course.

The shapes are still agonizingly unsuited for placement into a corner, but then again… it’s a lot better than with the 3x AA battery pack! Here’s the whole setup again, in close-up:

Dsc 1958

The trick will be to cover it up properly, here’s a first trial using my favorite foam-board as prototyping tool:

Dsc 1960

That’s 6.5 cm wide, btw. Any less, and the battery holder will poke into it and make it wobble.

Does it look good? I don’t know. I think I could live with a slanted 6.5 x 20 cm white strip along the ceiling, with a little PIR peeking out in the middle (and a small hole for the LDR + temperature/humidity sensor).

Next challenge is to come up with a mounting bracket for this darn thing. Perhaps 3D-printed? Two triangles on the end or something? If they slant slightly inwards, they would cast a shadow and not draw much attention…

It all needs to be properly detachable, since this thing runs on battery power. I could stick two little solar panels on the surface to get a warm fuzzy environmental feeling… but I doubt they’ll capture enough energy in that position.

Anyway – I’m happy to have a fresh option to think about. We’ll see…

Long live the AA battery!

In Hardware on Sep 17, 2010 at 00:01

The AA Power board announced yesterday just arrived:

Dsc 1931

And it looks like it does indeed perform exactly as expected. Here’s the ripple:

Screen Shot 2010 09 16 at 13.41.07

That’s with the 1.6 mA LED load, i.e. a 75 µs cycle / roughly 13 KHz – this was as predicted: at light loads, the recharge frequency can reach down into the audible range. But it’s highly unlikely to be noticable due to the tiny size of the inductor, which after all is not built to act as a loudspeaker :)

Here’s the “AAv1” fully mounted for powering a JeeNode via the FTDI connector:

Dsc 1934

(there’s no charge circuit here, I’m just using an externaly-recharged battery as power source)

And here’s the whole setup in actual use:

Dsc 1935

Works like a charm. Runs just fine with the “rooms” and “radioBlip” sketches, and wireless just works – as before.

Quiescent current draw is about 20 µA when powered this way. That goes down to 10 µA when used with two cells @ 2.4V, and down to an amazing 7 µA when powered from a 3V source (a CR2032 ought to work nicely!). Above 3.3V, the circuit becomes just a tad less efficient when it switches into step-down mode, drawing about 30 µA all the way up to 5.5V.

Great, now we’re starting to get into some serious low-power options.

Tomorrow, I’ll describe other ways to use this new AA Power board…

RGB multi-meter?

In Hardware on Sep 12, 2010 at 00:01

How’s that for a weird title, eh? ;)

Just got around to hooking up a test set of 2x 5 meter RGB LED strips to the MOSFET Plugs – using the setup created and described here a few days ago.

These are water-proof strips, with only 30 LEDs/m and a somewhat unfortunate brown strip background color:

Dsc 1925

That’s with all LEDs full on.

Now some more color and power experiments, in the evening – full on:

Dsc 1920

You can see the current reading, the JeeNode setup, and the power supply.

And with 100% / 45% / 15% settings for red, green, and blue, respectively:

Dsc 1923

The color came out much more yellow on this picture than it actually was, btw.

Some power measurements on the 12V line:

  • full on: 2.4 amps @ 12 V = 28.8 watt
  • color-adjusted: 1.9 amps @ 12V = 22.8 watt

The power supply is a beefy 12A @ 12V cage which draws 4.4 watt even without anything connected. That’s very unfortunate, because I’d like to turn the LEDs off on the 12V side and leave the power supply on at all times. Will need to find a better supply – 4A would be plenty.

These results are slightly disappointing. First of all, 60 LEDs per meter will be a minimum to provide a decent level of (indirect) house lighting at full power. But also, it’s frustrating to see how the power gets eaten up in the supply and by the resistors (especially with red LEDs dimmed less than the others).

No doubt this is way better than incandescent lighting, but still…

Another surprising outcome, is that the RGB settings for this strip are completely different from the 5050 RGB test setup I used a few days ago. It looks like I’m going to have to adjust each strip individually to get a nice consistent white balance.

And then there’s the issue of fringing. Looking directly at these LED strips clearly shows the distinct RGB components, with the color balance very much dependent on the viewing angle. I sure hope that the 60 LED/m strip with white background and used as indirect lighting will even this out.

On the plus side, the ≈ 300 Hz PWM of the new rgbAdjust.pde sketch I’m using on the JeeNode seems to make these LED strips completely flicker-free.

Onwards!

RGB strips – the software

In Software on Sep 9, 2010 at 00:01

Now that the hardware is ready, let’s move on to the software. First task is to figure out all the pin assignments with a little “rgbTest.pde” sketch:

Screen Shot 2010 09 08 at 12.43.29

Yep, it works. Here’s AIO4 in action:

Dsc 1913

On to the real thing. I’m going to re-use the code from this post, but with a couple of modifications:

  • since that code apparently still flimmers a bit, I’m going to make it run faster by reducing the number of steps from 256 to 101, i.e. intensity values 0..100 – that should increase the refresh rate to about 300 Hz
  • the fourth value will be re-used as a general intensity control, so “RGBW” now means: take each individual RGB intensity times the W intensity
  • the main logic will remain the same, even for the “White” dimmer – this is harmless, since there is nothing connected to port 3
  • need to re-define the pin assignments to match the above, twice

Ok, the new sketch is here – it’s a bit long to include in this post. Now I can send messages via a JeeLink to control this thing:

  • full on: 100,100,100,100,100,100,100,100,30s
  • full off: 100,100,100,0,100,100,100,0,30s

And here’s a very first / rough attempt to create a decent white tint:

  • 100,40,5,0,100,40,5,100,30s

Here’s my (messy!) workbench with four different light sources:

Dsc 1916

  • top right – a warm white incandescent lamp, seems to use a 12V headlight
  • middle back, under the shelf: commercial sort-of-warm-white LED lamp
  • middle center, magnifying glass: fluorescent cool white tube
  • left front, paper sheet: my RGB test setup, indirect lighting

When looking straight at the LEDs (always a bit painful), you can clearly see the different colors. The color offsets produce a slight fringe in the shadows cast from this light:

Dsc 1917

This won’t be good enough for photographers, but my impression is that it might work out fine when used as indirect lighting.

The results did surprise me quite a bit: for this tint, you have to turn on as much red as possible, add some some green, and drop almost all the blue.

The unfortunate part is that the red LEDs are responsible for most of the energy loss via their series resistors. Sigh. I wish they’d make RGB strips with all resistors the same small value – I could easily adjust the actual intensity with PWM and stay below the maximum specs.

Some estimates gleaned from the lab power supply w.r.t. current draw for the 50 cm 60-LED strip + JeeNode:

  • all off: 10 mA
  • full on: 620 mA
  • warm white: 270 mA

That last one translates to 6.72 Watt/meter (with some 2W eaten up by the red-side resistors, yikes). I don’t think I’d want to go any lower than that as full-on lighting setting, so if Jee Labs is to get more of these RGB strips around the house, I’ll definitely want to use the 60 LED/meter strips.

RGB strips, revisited

In Hardware on Sep 8, 2010 at 00:01

A while back, I reported about hooking up an RGB strip. That was then.

Now there is the MOSFET Plug to make such hookups a lot simpler. So it’s time to revisit that experiment, because I want to find out how well RGB strips would work for < w a r m > white lighting in the house. Theoretically, RGB can generate any color, so that would include any “temperature” of white, right? Trouble is, I’m not convinced that LED strips are color matched well enough across their entire length to accomplish such lighting conditions over a few meters. The other concern is that RGB LEDs have the Red, Green, and Blue LEDs sitting next to each other, so there may be some fringe colorization – maybe diffusers will be needed.

Then again, I do have one LED lamp of 1 meter long which generates an abolutely great tint of white (“white tint” – interesting concept, eh?).

Time to find out:

Dsc 1912

I obtained some samples of “5050” RGB self-adhesive LED strip, one with 30 LEDs per meter, the other with 60 LEDs. They are mounted on nice white flexible strips, and the whole thing was tacked onto my all-time favorite material: foam board!

Since 2 x 3 is 3 x 2, I used 3 MOSFET plugs to connect this together, these are in turn plugged into a Carrier Board with a JeeNode on its back, and the whole kaboodle is placed in half a box. Since the plan is to later attach this unit to much longer LED strips, I don’t really want to close that box – the MOSFETs will no doubt generate too much heat once they drive several amps each.

Here is how everything is wired together:

Screen Shot 2010 09 07 at 22.31.09

Oh, there’s one more wire: on the photo you can see a red jumper wire running from +12V to a PWR pin on the Carrier Board (I used the FTDI connector) – so the same 12V supply is used to power the JeeNode itself.

That’s it. Six output lines to control the on-off state of two independent strips of RGB LEDs.

Tomorrow – the software…

Utility Plug pack

In Hardware on Sep 5, 2010 at 00:01

The recently announced Utility Plugs have room on board to add some resistors, diodes, transistors, LEDs, etc. but that’s not always needed. Sometimes, you just want a way to bring a cable out with a decent connector.

The way to do that is to solder these 4 jumpers to connect everything straight through:

Dsc 1907

Now, all you need is a cable. But beware – this one isn’t what it seems:

Dsc 1906

It only has the middle two wires connected:

Dsc 1911

Not much we can do with those: they are +3V and GND on the Utility Plug!

The way to spot them before cutting the wire, is to look carefully at the connector:

Dsc 1908

As you can see: 4 gold-plated pins on the outside (i.e. RJ-11), but only 2 wires have acually been pushed into the connector. Here’s one I made myself, using modular plugs and flat telephone cable from a local DIY shop:

Dsc 1909

Now I get DIO and AIO as well (possibly altered by the circuits added to the Utility Plug):

Dsc 1910

To better support wired-through scenarios, I’ve added a “Pack of 4” variant of the Utility Plug to the shop:

Dsc 1904

It omits the extra components, so you just need to close those 4 solder jumpers. Note that there was no room on these boards for mounting holes – best way is probably to hot-glue them to a stable base plate of some kind.

Making 6-wire cables

In Hardware on Aug 31, 2010 at 00:01

I’ve been making cables for the Utility Plug recently. They come with the kit, but the reason for choosing these “modular” jacks and connectors, is that they are very easy to make yourself.

FYI, the 26 AWG wires in this type of cabling are rated for 360 mA current. Plenty for signaling and powering electronic stuff, but not suited for high power or high voltages.

I use the following low-cost crimp tool for most of my 4-. 6-. and 8-core cables:

Dsc 1851

Actually, I have a second one for 8-core cables (i.e. RJ-45 network cables) – it’s sturdier but also more expensive:

Dsc 1862

Here’s how the cable is made, from start to finish. First, make a clean straight cut:

Dsc 1852

Then you have to strip the outer mantle, without damaging the inner wires:

Dsc 1853

This is what comes out:

Dsc 1854

It fits perfectly into a “6P6C” RJ-12 modular plug (6 positions, 6 connections):

Dsc 1855

Now the magic part:

Dsc 1856

Seen from the other side, with the plug ready to be crimped on:

Dsc 1857

Here’s a before-and-after picture, you can see the metal pushed into the cable (and the cable jacket clamped for strain relief):

Dsc 1858

Another view:

Dsc 1859

How does it work? Well, here’s the crimp tool, in released state:

Dsc 1860

And here it is again, squeezed tight (it has a stop, ya can’t squeeze too far):

Dsc 1861

If you keep goin’ at it for a while, you get this:

Dsc 1863

And that’s where they end up at Jee Labs:

Dsc 1864

Easy. And if you don’t want to go through all this: just cut up a telephone cable instead (note that such cables will work fine, but most of them only connect the inner 4 wires, i.e. AIO, DIO, +3V, and GND, not PWR & IRQ).

LED strip efficiency

In Hardware on Aug 29, 2010 at 00:01

LED lighting is efficient right? Oh, sure… the LEDs are, but the way they are connected isn’t necessarily!

I’ve always been puzzled by those resistors you see on RGB LED strips:

Dsc 1664 2

My impression is that these strips consists of segments which all have (essentially) the following schematic:

Screen Shot 2010 08 27 at 21.59.22

Measuring the 60-LED/meter RGB strip I have here, I get the following readings for 0.5 m, i.e. 10 of the above segments:

  • RED draws ≈ 180 mA, the voltage over its resistor is ≈ 5.5V
  • GREEN draws ≈ 170 mA, the voltage over its resistor is ≈ 2.2V
  • BLUE draws ≈ 190 mA, the voltage over its resistor is ≈ 2.4V

Total current draw is roughly 540 mA, or 1.08 A/meter @ 12V. So the total power consumption is 13 watts for each meter of LED strip.

But…

  • the red LED’s resistor consumes 0.18 x 5.5 = 0.99 W on each 0.5 m
  • the green LED’s resistor consumes 0.17 x 2.2 = 0.37 W on each 0.5 m
  • the blue LED’s resistor consumes 0.19 x 2.4 = 0.46 W on each 0.5 m

That’s 3.64 W of the 13 W pumped in per meter – turned into … heat!

Is LED lighting a good idea, in terms of efficiency? Yes, probably. A meter of RGB LEDs at full power draws 13 watts and looks a lot brighter to me than a classical lightbulb, halogen light, or even them new fluorescent “long-life” bulbs that are all the rage (but oh so ugly).

Note that I’m not talking of “power LEDs”, i.e. the 1W, 3W, or more LEDs that are used for very bright lights and which need te be mounted on a cooling fin (Infineon, etc). These are usually driven by a (more complex) constant-current source, and not a plain 12V supply. The reason for this is that at those power levels, you couldn’t possibly adjust the current draw via resistors – these would become scorching hot and cause lots of problems of their own!

The are a couple more figures to be gleaned from the above information, btw, but you can also measure these values directly on the RGB strip:

  • the red LED resistors are 300 Ω each, each LED gets 2.2V
  • the green LED resistors are 120 Ω each, each LED gets 3.3V
  • the blue LED resistors are 120 Ω each, each LED gets 3.2V

That voltage is the real reason for all these resistors. If you were to feed exactly 6.6V to the 3 red LEDs (9.8V for green, 9.6V for blue), then you wouldn’t need any resistors to pick up the slack. But that’s not feasible in a practical / cheap way, so instead we drive these strips with 12V and have the resistors eat away 28% of excess energy in the form of generated heat. Note: it would be more accurate to say: “if you were to feed exactly 180 mA, etc” … because the voltage is a “side effect” for each type of LED, the current is what determines their brightness.

Another source of inefficieny is the 12V power supply – let’s assume it’s about 90% efficient. Then 72 watts of power going into the LEDs will draw a total of 111 watts from the power line.

The good news is that these ratios won’t change when the LEDs are dimmed via PWM. A 50% pulse reduces the total amount of energy used by the same percentage (again: 28% of that is gobbled up by resistors).

Sooo… if you’ve got 8 meters of RGB strip going at full power, then that’s about 100 watts – 28 of which are turned into heat before they even reach the LEDs. And the power supply used another 11 to do its job.

I still think LED strips are a good idea – if I can get the white balance right and if their color is very even.

Meet the Opto-coupler Plug

In Hardware on Aug 20, 2010 at 00:01

After two new output plugs, here’s one for input – a dual Opto-coupler:

Dsc 1841

The idea is simple: feed it 5..50 mA of the proper polarity, and the other side can be read out by a JeeNode without any electrical contact. As the name says: light is used to remove the need for a galvanic connection.

This can be used for more than just high voltages: there are many cases where two different low-voltage circuits have independent ground levels, and where you want to keep it that way.

Electricity always takes the path of least resistance (literally!), and with high-current loads (or inductive spikes), you never know when some piece of equipment decides that it would love to send 5A through the GND pins across a JeeNode. There’s no danger involved here, but some traces on the JN print will go up in smoke (literally!).

A simple example is when you’re dealing with two power sources, and hook them up – accidentally or on purpose. Nothing will usually guarantee that the ground pins get connnected first. You might just briefly get the positive high-current supply hooked up in such a way that it finds another ground loop…

As with the Relay Plug, I’ll mention that you can use this Opto-coupler Plug to sense AC mains voltages (well not directly… more on that in a moment). But the risk is all yours.

The terminals on this plug are also detachable, but smaller: they use a 3.5 mm pin separation, and can handle a bit less current. The reason for this distinction is that you don’t want to accidentally put a high-power connector from the Relay Plug into this low-power Opto-coupler Plug. Since the connectors don’t match, this risk is avoided.

So what can you use as input source with this Opto-coupler Plug? Well… that depends – on the resistors soldered onto this plug, to be precise. Each resistor is in series with a LED contained inside the opto-coupler:

Screen Shot 2010 08 19 at 18.11.47

The dual opto-coupler used here will operate with roughly 4 .. 55 mA of current through the LED. The series resistors included with the kit are 1 kΩ @ 1/8W – this translates to a DC input voltage range of about 5 .. 12V. Any higher, and the resistor will get too hot – any lower, and the opto-coupler won’t trigger.

For higher voltages, you can replace these resistors with a higher value. Try to keep current consumption minimal, say 5 mA. Here’s the calculation to make it work with a 24V input: 23 V (roughly 1V gets taken up by the LED) with 0.005 A is … scribble, scribble, scratch, scratch … E=I*R … R=E/I … R = 23 / 0.005 = 4600 Ω!

So you should be good with a 4.7 kΩ resistor. Now let’s calculate the power consumption of that resistor … ponder, ponder … P=I*E … E = I*R … P = I*I*R = 0.005 * 0.005 * 4700 = 0.1175 W. Phew, a 1/8W (0.125W) resistor will work, but with little slack. Not surprising, really: the resistor is eating up 23 of the 24 V sent into the plug. Meaning: heat. That’s why low current use is best: current has a quadratic impact on the power consumption.

The trouble is that with 4.7 kΩ, you can only use the plug with 24V: any lower, and the current through the opto-coupler will be too low, any higher and the resistor will deliver its final puff, in the form of smoke…

So there you have it, with some free electricity calculations thrown in: this plug will work as is on a 5 .. 12V input source, and with the proper resistor value you can also make it work @ 12 .. 24V. The two inputs are fully independent, so different resistor values are possible.

If you happen to have a current-limited source in the 4 .. 55 mA range, then simply omit the resistors and put a dab of solder to close the jumper on the pcb. That’s 0 Ω, if you really want to know :)

On the JeeNode side, first enable the pull-up resistors on AIO and DIO, and then read them out as digital inputs. If you wanted to get maximum sensitivity, you could even use the AIO pin in analog input mode, and place the threshold a bit lower. That’s going to require a bit of experimentation (and it only works on the AIO side).

New café and shop pages have been added, as usual.

There’s one more new plug on the menu, a few days from now … that one will be a bit different from the rest. Even simpler, yet fairly versatile. Stay tuned!

Meet the Relay Plug

In Hardware on Aug 18, 2010 at 00:01

Here’s another plug, useful for various applications around the house – the Relay Plug:

Dsc 1812

This one uses miniature relays to control two independent contacts. It has two MDC3105 relay drivers on board, and uses the same detachable terminals for connection to the outside world as the MOSFET Plug.

Unlike MOSFETs, relays provide a fully isolated switching capability. There is no electrical connection between the switched out pins on the terminal block and the JeeNode. The traces on the PCB were in fact laid out with a wide separation between switched pins and the rest of the circuit.

These plugs have just the right size for the Carrier Board + Box, by the way:

Dsc 1823

The relays currently used for this board are rated up to 3A @ 250V (both AC and DC). This means that you could use them for controlling up to 750W worth of devices connected to the mains on each output. Just keep in mind that messing around with the mains voltage is dangerous and can be lethal. Note also that neither the pins on the underside, nor the screws on the terminal blocks are isolated, so you’ll have to consider really carefully how to physically mount everything to prevent shock hazard. I definitely wouldn’t use these plugs for mains power in the box as shown above – such a box can easily open when dropped.

Did I mention that AC mains can be lethal? Ah, yes, I think I did…

Then again, if you know what you’re doing: sure, go right ahead.

For the rest of us, these relays are probably more suitable for controlling low-voltage lights, motors, fans, and… larger relays. One item on my (infinitely long) to-do list is to use these relays to control the power of a couple of external hard disks. Not just to save on electricity when not in use, but also because disks which are not powered up and hence don’t rotate are pretty safe from software mishaps, both accidental or malicious.

The relays are driven from the PWR line, which has to have a supply voltage between 4 and 6V to operate properly. Less, and the relays won’t turn on – more, and the relays + relay drivers will be damaged. Each relay draws about 30 mA of current while turned on. They are not latching: power loss will switch them off.

Controlling the relays in software couldn’t be simpler: use the Port class in the Ports library to set both DIO and AIO as outputs, and then use digiWrite() and digiWrite2() to control DIO and AIO, respectively. Since each relay uses up one port, you can have up to 4 Relay Plugs, i.e. 8 relays hooked up to a single JeeNode.

Here’s an example which listens for incoming radio packets to control a Relay Plug on port 1 (this example is included in the Ports library as “relay_demo.pde”):

Screen Shot 2010 08 15 at 23.18.02

Sending “1,1,17s” via another JeeNode or JeeLink turns both relays on. Sending “0,0,17s” turns them off again.

Documentation for the new Relay Plug is in the Wiki, and there’s an order page in the shop for them now.

Meet the MOSFET Plug

In Hardware on Aug 16, 2010 at 00:01

There’s a new plug at Jee Labs – one I’ve been waiting to use myself for quite some time – a dual MOSFET plug:

Dsc 1807

The IRLZ34N’s used here should be able to drive over 5A @ 50V, but this will require a heatsink. For use without heatsink, a maximum currrent of 1 .. 3 amps should work fine. Just keep in mind that MOSFETs can generate a few watts of heat when used continuously at 2A or more. You can tie the MOSFETs in parallel for larger currents. You’ll need to add protection diodes to switch inductive loads, such as DC motors, relays, and solenoids.

This plug was designed for driving LED strips, but other loads can be driven as well. With two MOSFET Plugs, there are 4 individually controllable switches – to drive an RGB strip and a white strip, for example.

The terminal blocks used on this plug are heavy duty and detachable and use a standard 0.2″ grid (5.08 mm). They are much more convenient than fixed terminal block, particularly if the plug is mounted high or in some remote spot behind a book case or curtain. The two outputs have separate connectors.

The traces on this board have been made extra wide to be able to handle large currents flowing through the terminal block pins. The pins are laid out as two pairs: one side must be tied to ground, the other side (+A or +D) is then tied to the load, which in turn gets connected to a positive supply voltage (3..50V). Note that the positive supply voltage used by the load is not connected to the plug. A pulldown resistor is used to keep the MOSFETs switched off when the I/O pins are not connected, or not set up as outputs. Also, keep in mind that this plug ties the plug signal ground and the load ground together – it is not isolated from the load power supply.

The length of the plugs is 34 mm, making them a perfect fit for the Carrier Board + Box:

Dsc 1815

Note that a closed box provides little airflow to cool the MOSFETs, so this setup is not recommended for high-current use. Having said that, I’ve been driving a few meters of RGB LEDs with these MOSFETs without them even getting warm. See this earlier weblog post.

For dimmer use, there’s example code for a remote-controlled JN and 4 MOSFETs using software PWM.

I’ve set up a documentation page in the café and an order page in the shop. Since the prototypes worked on first try, these MOSFET Plugs are available as simple through-hole part kits right away.

A Murphy-less plug, so to speak :)

Mac Mini as home server

In Hardware on Jun 18, 2010 at 00:01

Whoa, great news – the Mac Mini is getting even more energy efficient:

Screen Shot 2010 06 15 at 12.41.01

It was announced today. Here’s what the new box looks like (and no more power brick!):

Screen Shot 2010 06 15 at 12.41.20

We’ve been using the Mac Mini as our TV + audio system for several years now. It’s connected to a master/slave power switch to switch off the other components when in sleep mode (sat tuner and amplifier). Works great, although I had to replace the hard disk recently. The new one would be a great successor… one day.

Might also be an excellent option for a home server, although a SheevaPlug or GuruPlug uses even less power in idle mode (approx. 4 vs 10 Watt). But that’s more of a software decision really: Mac OS X vs. Linux.

RGB via the Dimmer Plug

In Hardware on Jun 17, 2010 at 00:01

As someone pointed out in the comments a few days ago (see? that’s what weblog comments are for!), there’s Jee Labs’ own Dimmer Plug to unload the ATmega of all PWM duties:

Dsc 1729

Hm, I really forgot all about that one… doh.

It’s a great suggestion, of course. And fortunately, it can easily be swapped into the RGB strip controller series. All I need is a slightly different JeePlug to tie things together:

Dsc 1730

The result has a 2×3 pin header which matches the one on my previous interface, so now it’s just a matter of swapping cables.

And new software, of course. Here’s a test sketch which cycles brightness and colors similar to the first test sketch:

Screen Shot 2010 06 15 at 18.42.36

Except that this no longer requires any processor attention once set. And there are a few extras: it’ll work with up to four independent sets of RGBW LED strips, and it has a “global” brightness control (currently set to max), making it easy to set up the color once, and then dim the whole shebang while keeping that setting.

Also – because it’s hardware now – the PWM happens much faster. I can’t tell the difference, but I have this hunch that our cat probably can. There’s got to be a difference between blinking at 120 Hz and 100 KHz!

I’m not sure yet which approach I’ll keep. Both software and hardware PWM work fine. Decisions, decisions…

A little GUI for the RGB LED strip

In Software on Jun 16, 2010 at 00:01

After yesterday’s post, this RGB strip control project is essentially done. Keep in mind that I’m doing this only to adjust what comes out as “white”. I’ll leave light levels and color variations up to nature, since all I need to do is look out the window…

But since wireless control is present anyway, I might as well create a little demo using the JeeMon software.

So here goes. The setup I’m using is as follows:

Screen Shot 2010 06 14 at 16.31.37

The JeeNode is configured as node 30 and the JeeLink as node 1 (in the same group). The manual way to send out a color command via serial USB is to type:

<red>,<green>,<blue>,<white>,30s

Where each of the four values are in the range 0..255 (0 = off, 255 = full on).

Now the GUI version (Mac OS X):

Screen Shot 2010 06 14 at 18.21.51

The code for this is as follows:

Screen Shot 2010 06 14 at 18.16.26

Like everything in JeeMon, it’s cross platform since it uses Tcl/Tk.

Here are the screen shots for Linux (Ubuntu) and Windows (W7, XP, 2K), respectively:

Screen Shot 2010 06 14 at 18.01.42 Screen Shot 2010 06 14 at 18.35.25

Screen Shot 2010 06 14 at 18.14.21 Screen Shot 2010 06 14 at 18.09.26

As you can see, the light gray background color was adjusted for the Mac – on some of the other platforms it needs to be darkened a bit to match the default label background.

Anyway. I’m not a GUI wizard, so this’ll have to do for now…

Remote RGB strip control

In Software on Jun 15, 2010 at 00:01

To continue this series on driving RGB strips with a JeeNode, here is a sketch which allows setting the brightness levels using PWM. It’s a bit long for a weblog post, but I thought it’d be useful, since there is quite a bit of trickery in here. Notes follow below:

Screen Shot 2010 06 11 at 23.17.29

This code does some hefty bit manipulation. The idea is to keep an array of 256 time “slots”, with bits to indicate when an I/O pin should be toggled on or off. The loop then continuously scans these slots at the rate of ≈ 32 microseconds per slot (this corresponds to roughly 120 Hz). The 8 bits in each slot map to the JeeNode’s I/O pins: bits 0..3 = AIO1 .. AIO4 and 4..7 = DIO1 .. DIO4.

A refinement is that only the first 255 of the 256 slots are scanned. This way, 0 is 100% off and 255 is 100% on.

The static “masks” array defines which setting gets mapped to which I/O pin. It depends on the way the output driver is connected to the JeeNode.

The main PWM timing loop is done fully in software. It will run slightly irregularly due to timer interrupts and RF12 driver interrupts, but the effects aren’t noticeable.

The RGBW values are stored in EEPROM, so that the LEDs come back on with the same settings after power cycling. The settings can be adjusted by sending a packet with the new values to node 30, group 5 @ 868 MHz.

This sketch could be extended to support “animations”, i.e. ramping up/down to specific levels, mood lights, etc – I’m not interested in that, I just want to be able to trim the color of my room lighting to a pleasant level of white:

Dsc 1723

All I did to adjust the strip on the right was send the following “RGBW” command out via a JeeLink:

255,140,40,120,30s

The above sketch does PWM, but this whole thing is still being turned on and off with an old-fashioned mechanical switch … if you still remember those :)

FWIW, I’m considering making a dual-channel “MOSFET Plug” – two of those could then be used to replicate this same setup for the LED strip on the left.

Tomorrow: a little GUI front end for all this.

RGB driver board

In Hardware, Software on Jun 14, 2010 at 00:01

To follow up on yesterday’s post, I made a more permanent 4-channel board for driving an RGB LED strip plus the original white LED strip already in use.

A JeeNode is used to drive these strips, using a small custom JeePlug to hook up ports 1 and 4, as well as to use the LED voltage as power source for the JeeNode:

Dsc 1717

Here is the plug in more detail:

Dsc 1718

It includes an LP2950 linear regulator to put 5V on the PWR pin, that way this thing can be used with any input voltage from 12 to 24V. Here is the bottom side:

Dsc 1719

The driver itself uses four IRLZ34N MOSFETs, three of which will be used for the RGB strip, and the other for the white strip so that it too can be controlled and even dimmed remotely:

Dsc 1715

The back side is hand-wired using sturdy copper wire, although in this case only 300 .. 600 mA is being switched per color. The 10 kΩ pull-down resistors prevent the lights from turning on in the absence of control signals.

Dsc 1716

And here’s the completed setup:

Dsc 1714

The two wires sticking out are for attaching my 12V lab power supply during testing. The other green 2-pin screw terminal is for attaching the white LED strip.

The RGB ledstrips can now be installed next to the LED strips already in use here at Jee Labs:

Dsc 1722

Here’s a trivial test sketch to turn each of the 4 colors on and off:

Screen Shot 2010 06 11 at 13.17.35

The results can be seen in this brief video.

What remains, is to write the software so this thing can be controlled via wireless. I might add an LDR to sense ambient light levels, or even a Room Board. Perhaps some basic ramp-up / ramp-down PWM logic. Or maybe I’ll just duplicate this setup and drive the two sets of LED strips I have, independently and from a single JeeNode.

Hardware is easy, it’s always the software… the code will be presented tomorrow!

Reminders: 1) June discount and 2) Jee Labs will be closed from July 14th to August 14th.

Driving an RGB strip with MOSFETs

In Hardware, Software on Jun 13, 2010 at 00:01

Another day, another project started. I have a nice 5-meter LED strip in the office, which provides indirect lighting at Jee Labs. Works fine, but despite being called “warm white”, it’s slightly greenish. Not so great…

Someone suggested adding an RGB strip next to it, to compensate for the color.

So to start off this multi-part series, I wanted to simply control RGB. This is very easy to do with three MOSFETs. I used IRLZ34N’s N-channel, since the LED strips are common anode. The circuit is trivial: source to ground, drain to LED cathode, and gate to an I/O pin. Rinse and repeat three times. I didn’t even add a pull-down resistor to the gate, though I probably should.

Here’s the circuit, fully connected to a test strip with 9 RGB LEDs using a separate 12V power supply:

Dsc 1664

I wrote a little test sketch which ramps the light levels up and down using PWM, and which goes through all the RGB combinations – using some bit fiddling:

Screen Shot 2010 06 07 at 13.17.10

The LEDs are pulsed in software, with a cycle time of 8160 µsec (32 * 255), i.e. roughly 120 Hz. No discernible flickering. A more advanced version ought to use interrupts to keep the PWM going in the background.

Here’s a video of the result – with apologies for the very low quality.

Since the JeeNode has RF on board, it will only be a small step to add wireless control. Stay tuned…

Update – Source and drain were listed the wrong way around, I’ve updated the text above.

(Not so) Home Easy

In Software on Apr 23, 2010 at 00:01

Here’s the Elro / Home Easy AB440R remote control:

Dsc 1351

On the surface, it looks like a very clean 433 MHz protocol:

Screen Shot 2010 04 17 at 12.16.22

Here are some bit patterns, as I see them coming in:

Screen Shot 2010 04 17 at 12.15.26

All the pulse widths are in the expected range (first two are timestamp and pulse count):

Screen Shot 2010 04 17 at 12.38.38

This is completely in line with the protocol description I found. Given that it uses a special 0-0 pattern for extended group codes, I decided to pass all the transitions back, leaving the interpretation to higher-level code:

Screen Shot 2010 04 17 at 12.31.28

Here’s what comes out:

Screen Shot 2010 04 17 at 12.30.50

Several very odd problems with this:

  • the incoming bit patterns are less than 50 bits
  • the KAKU decoder also matches these patterns
  • I’m getting spurious empty lines reported

The KAKU decoder match is very surprising, since it only fires when receiving exactly 12 bits! As it turns out, the other way leads to false positives as well: the KAKU transmitter currently triggers the HEZ decoder – but that’s more logical, since the HEZ decoder isn’t checking exact packet sizes yet.

Something very fishy is going on, but I can’t see where :( – despite this, I’ve updated the code.

Oh well, can’t win ’em all…

X10 RF reception

In Software on Apr 20, 2010 at 00:01

One more decoder, a home automation protocol this time – a X10 RF transmitter:

Dsc 1342

That’s a Marmitek SS13, sending out over 433 Mhz (European model).

This is a fairly simple protocol (documented here), although synchronization and packet detection works a bittle differently from the other decoders so far:

Screen Shot 2010 04 16 at 00.06.22

Sample output:

Screen Shot 2010 04 16 at 00.05.35

Easy!

More OOK decoders

In Software on Apr 19, 2010 at 00:01

O(o)k … so there are now several decoders for OOK transmissions: 3 for 433 MHz and 4 for 868 MHz:

Screen Shot 2010 04 15 at 10.36.43

Sample output:

Screen Shot 2010 04 14 at 23.20.21

The code is here now here. It has been set up as an Arduino sketch, but the decoder logic is not Arduino-specific, nor even ATmega-specific in fact. The sketch compiles to under 5 Kb, leaving plenty of room for future extensions.

All that is needed is to call the decoders with pulse widths in microseconds. They all run in parallel, but normally at most one will succeed for any given pattern of pulses. The actual decoding completion happens during the final long pulse (2000 µs or more, in most decoders).

Here is the rest of the sketch, which drives the decoder from pulses measured in an interrupt routine:

Screen Shot 2010 04 15 at 10.36.58

Note that there is something odd in this code: all the decoders are fed the same pulses! In real use, separate receivers will need to be connected for 433 Mhz and 868 Mhz, and then pulses fed to the appropriate decoders only. The reason I did it this way was for testing: I can simply replace the OOK receiver with whatever I’m currently trying out to see if it works – no reset needed.

So that’s it for now: 7 decoders, capable of decoding packets from several dozen different types of sensors and transmitters.

The data is reported as a set of hex nibbles, which need to be separated into the specific bit patterns for each type of packet. Also, checksums still need to be verified, to weed out any remaining false positives.

But that’s another topic, for another day.

Note – the RFM12B receiver cannot receive OOK signals. I hooked up extra hardware to make the above work.

Visonic sensors

In Software on Apr 18, 2010 at 00:01

Another set of sensors is made by Visonic. Here’s the door sensor:

Dsc 1341

It has three sources of triggers: a reed switch, normally kept closed with a magnet on the door or window, an extra set of ordinary contacts, and an internal switch which is released when the case is opened.

There are other sensors using the same protocol, such as a PIR motion detector and a “universal transmitter”.

The sensors send OOK data on the 868 MHz band, but it took me a while to figure it all out. The main reason being that I couldn’t find a preamble for these radio packets – apparently there is none! – instead, the tail of the packet is a good reference point, i.e. the 72 pulses preceding the long pause at the end can be reliably decoded.

Each bit is either a short-long pulse pair, or a long-short pulse pair. This can in fact be used to resync even before the end of the packet is reached, because short-short and long-long combinations indicate that we’re off sync.

The total packet has 72 pulse transitions, i.e. 36 bits of data. I add 4 extra zero bits to create a 5-byte result. Here is the main decoding logic:

Screen Shot 2010 04 14 at 16.28.07

Here is some sample output:

Screen Shot 2010 04 14 at 16.35.43

I’ll postpone decoding of the actual bit pattern to another day but note that you don’t really need to interpret all the bits: just look which patterns your sensor is sending out under various conditions, and you can match the incoming packets accordingly.

FritzBox call log

In Software on Mar 12, 2010 at 00:01

I’ve been using the FRITZ!Box 7170 as ADSL modem and telephone interface for some time now:

Screen shot 2010-03-08 at 12.50.41.png

It has a nifty feature: when you enable the built-in call monitor by typing in “#965“, you can connect to TCP/IP port 1012 to get real-time messages about all phone calls.

This is easy to hook up to JeeMon. I added a new “FritzBox.tcl” file with the following code:

Screen shot 2010-03-08 at 13.15.39.png

(Some experimental code was omitted from the above listing)

To enable this, the following line was added to application.tcl:

Screen shot 2010-03-08 at 13.14.42.png

Here’s an example of an incoming call, as shown in the JeeMon log:

Screen shot 2010-03-09 at 13.51.12.png

And here’s an outgoing call:

Screen shot 2010-03-08 at 12.55.09.png

Neat! I’ll hook this up as events once the JeeMon event system is ready.

These experiments are very useful to see how the current design is working out. The above code depends on the “MessageStream” class in the “Serial” rig. It doesn’t really add much value in this case, but some class hierarchies seem to be emerging. This socket connection is an example of a similar-but-not-quite-the same case as serial connections, requiring its own class. A socket connection is very similar to a serial connection once initialized – but this doesn’t show as clearly in the code as I would like and there’s already a bit of code duplication.

Will probably need some re-shuffling later, to better match concepts / design and implementation.

Xanura CTX15

In Hardware, Software on Mar 9, 2010 at 00:01

Another popular home automation module is the Xanura CTX15:

DSC_1228.jpg

That’s a live 220V power-line connection in the top right corner!

I’ve connected the CTX15 module through a UART Plug, with a 4.7 kΩ resistor in series with the RX signal (yellow from CTX15). This is because the signal swings up to 5V, whereas the UART plug only accepts 3.3V voltage levels. The module is powered from the PWR pin, which on a JeeNode USB carries 5V.

The CTX15 is a bi-directional interface, it can send as well as receive A10-type power-line commands (a superset of X10). The trouble is that it needs to be polled to read out what has been received and buffered so far.

Here’s a sketch which takes care of that:

Screen shot 2010-03-08 at 12.08.53.png

And here’s some sample output:

Screen shot 2010-03-08 at 12.08.40.png

As a test, I powered up yesterday’s XM10E test setup as well, to send out on and off commands to unit A.1 every 3 seconds. As you can see with the CTX being read out every 5 seconds, multiple received packets will sometimes be combined and returned as one reply.

X10 control

In Uncategorized on Mar 8, 2010 at 00:01

Let’s go some more into home automation – the X10 power-line system in this case.

Here’s is a sketch which turns a remote appliance on and off every 3 seconds:

Screen shot 2010-03-07 at 23.06.56.png

I used the Arduino X10 library (had to mess around with the use of headers to get rid of compile errors, and enable the pull-up on the zero-crossing input).

This sketch runs @ 3.3V on a JeeNode with some stuff attached to port 1:

DSC_1224.jpg

It’s just a simple re-wiring to an RJ11 connector. This in turn, plugs into the XM10E opto-isolated interface:

DSC_1225.jpg

There’s also a X10 receiver built into the XM10E, which I’m going to ignore for now.

X10, in its simplest and oldest form, is a power-line transmission system, i.e. the signals to control a switch are sent over the same wires as the AC power itself (using a 120 KHz signal injected at the zero crossings). Proper mains isolation is essential, of course – as built into the XM10E unit.

The result is that you can plug this device into any outlet in the house and it’ll switch on and off as defined in the above sketch:

DSC_1226.jpg

It’s hard to miss – the relay built into that thing switches on and off with a very loud “clunk”!

The power consumption of this switch is 0.6 W off and 0.9 W when on, according to the Cost Control. Not bad, until you start installing many dozens of these switches around the house … then it will add up!

FS20 developments

In Hardware on Aug 18, 2009 at 00:01

Looks like the FS20 remote-controlled system from Conrad and ELV has gained a few new units. Here’s a 60-euro 2-channel power-strip, controlled from 868 MHz, hence also from a JeeNode:

85076_F04_GeSteckdosenl.jpg

Also a 42-euro repeater to get through multiple layers of reinforced concrete.

Great options to avoid having to deal with line voltages. Not ultra-cheap, but still.

The one drawback worth noting with FS20 is that’s it’s not replay-safe. If someone picks up these signals, they can re-send them at a later time, even from outside the house. This means there is essentially no security at all with this approach. But for things like lighting and office equipment, that’s probably not an issue.