Dealing with millis() overflow

If you like to KISS it, you’re like me. Counting time with millis() is pretty decent, short of an actual real time clock module. Accuracy is not very good if your ATMega MCU is using a resonator (internal or external) but in cases like the GarageMote or the MailboxNotifier where you need a rough idea when something last happened, millis() is nonetheless very handy and sufficient. What I mean is things like “garage closed X seconds ago” or “mailbox opened Y seconds ago“.

All is fine until millis() falls off the edge of the unsigned long universe. That universe is only about 49.71 days long or a total of 4294967295 milliseconds. Because it is unsigned it then wraps back to 0. The Arduino site attempts to explain why this happens.

Let’s simplify and assume unsigned long max = 1000. Now let’s look at the two cases:

  • Normal: If the event you care about is recorded by millis() at 500, and time passes until millis() returns 600, the difference between the two millis() readings is 100. Nice and simple, no sleep lost.
  • Overflowed: If the event you care about is recorded by millis() at 950, and time passes until millis() overflows and wraps around to 70, the time difference between the two millis() readings is 120.

To solve this second case you have to add the two chunks of millis() together, but maybe that’s not totally obvious. That’s why I put together this diagram to illustrate what I mean. The red parts are the total time we care about. This is the time that passed since the event we care about.

Here is sample Arduino code that will achieve this result:

To get the unsigned long max you can just convert -1 (negative 1) to unsigned long. Because there is no such thing as negative anything in unsigned types, -1 simply wraps around backwards to the last value of the long spectrum, giving you the maximum.

I will have to admit that some of the sample sketches I released so far are ignoring this issue and will cause Moteinos to appear as non responsive when checking when an event last happened. Moving forward I will make an effort to push upgrades to fix these logical bugs. In the meantime you are now empowered to know how to get around it yourself.

Getting more serious about SMD production

I’ve been doing all manual SMD assembly ever since I started Low Power Lab, and still do at this moment. I find it too hard to outsource assembly and too prone to some issues.

Anyway, in the beginning there were tweezers, a microscope, and a toaster over for reflowing. I very quickly realized that the tweezer method was insane to put it mildly, the only worst thing that I can think of is actually soldering everything with a soldering iron instead of using paste. Nonetheless the first ever Moteino batch was tweezer-microscope+reflow assembled. Then I figured out how to make metal stencils out of soda cans. That works beautifully, costs next to nothing, and the more you make the faster and better it gets, and those stencils never wear out, unlike mylar or other plastic stencils. It’s the closest you will get to real stainless steel stencils. But I could only spread paste on 1 piece and it gets tedious, watch this video of how I actually do it. Panelizing PCBs sounded a bit scary.

So finally I made the jump and panelized a batch of Moteinos recently. The panel has 2.5mm tooling holes that are spaced on a NxN cm grid (which would fit the Stencil8 tooling block), but quite frankly they could be spaced any way. The tooling holes match holes in the stencil such that the stencil alings perfectly with the PCB. I don’t have a tooling block because quite frankly I don’t think it’s needed. I drilled holes in some MDF using a 2.5mm drill bit (the thin sheets that come with the stencil are right size and perfect for the job), using the PCB to pilot the holes. Then 2.5mm steel tooling pins align the stencil with the PCB.

The time savings is significant, especially if multiple panels are assembled at once. I was reluctant at first and I was worried about the spacing between the PCBs and other things like that. But glad I did it and this is a first step towards more serious in house assembly. The v-scoring means the PCBs are snapped apart after reflowing, and the edges will be a bit rougher than the nicely routed PCBs I was used to. I do however snap the panels in 3 rows for easier SMD assembly with my pick and place vacuum tool. After reflow they are snapped into individual pieces. The panelization is done at the PCB fab for an extra fee.
The McMasterCarr parts for the pins and the drill bit are: here for the pins and here for the drill bit.

Next up: pick and place machine maybe? Haha.

Moteino Power Shield now available

I kept talking about it here and there in the forum and the blog. And finally now it’s for real. Parts have been sitting around for weeks and I finally managed to free up some time and get a few assembled, take some shots and put it up on the shop. I know a lot of people asked “how about if you have projects that require 5V because of some special sensors”. So this little board came about for that specific reason. And since I was at work generating 5V from almost nothing, why not add a lipo charger, a voltage level detector, a little prototyping area and a switch (but maybe not the kitchen sink) ?

The charger chip is the popular MCP73871, charges at 500mA via USM mini-B and has a charging status LED. The booster is the mighty TPS61220 adjustable output boost regulator. The output voltage is 5V by default. It can be switched to 3.3V if wanted, by means of a solder jumper:

Even though it works, you should avoid trying to get 3.3V output from a 3.7V lithium battery, because … well … it defeats the purpose of it. Try getting 3.3V output from something much less than that, say a AA/AAA cell, that will put this board to good use.

I’ve started using this to power MotionMote from a small 400mA battery since the PIR sensor requires at least 5V, and Moteino will work great with 5V input (on “VIN”). So that’s a great application, and battery voltage monitoring comes included, sweet. The little lipo won’t last a long time (actually I don’t know how long … we’ll see), but when it does, I can see it from the incoming battery level indicator, and then just quickly recharge it. Not awfully inconvenient. The battery voltage monitor is just a VCC-1Meg-470K+0.1uF-GND circuit which divides the voltage and feeds it into Moteino analog pin A7 where you can read it as analog and interpret it according to what battery you got hooked up. A formula that I use for batteries up to 9V is:

As you can see there’s also a small prototyping area. The Moteino can be mounted above or below, your choice, just keep the power pins aligned of course. The switch should be OFF to avoid loads when charging and let the charger exert its love on the battery uninterrupted.

At this point it hasn’t been extensively tested but I’ve had no issues using it in my projects. And hey this little board will resurrect your AA batteries from among the many dead you surely have around (you didn’t throw all those away right?). Getting 5V/3.3V from as low as 0.7 is not too hard for the Moteino Power Shield.

Eagle schematic and layout are available on Github.

SwitchMote source code released!

The source code for SwitchMote is finally “done”. As always, consider this a beta release at best, you should always check the github repository for any updates. There are 2 parts to configuring and programming a SwitchMote.

SwitchMoteConfig sketch, which needs to be loaded and used once, after assembly and before SwitchMote installation. This sketch is meant to help setup the essential parameters of the Moteino in the SwitchMote such as frequency, node and network IDs, RFM69 type (W or HW), encryption key, description, and some other utilities that may be extended in the future. All these parameters are then stored to EEPROM and will not be dependent on hardcoded values in your sketch.
This is especially useful when you have some nodes with RFM69W Moteinos and some with RFM69HW. It’s hard to keep track of all the transceivers settings. Additional settings could be added, like power level, bitrate, etc. Keeping the configuration with each node is most efficient in applications like SwitchMote. Setup once and forget!

SwitchMote sketch is the permanent sketch that will get loaded on your SwitchMotes. Note that this sketch will read the EEPROM configuration that was setup with the SwitchMoteConfig sketch mentioned above. This sketch does several things.

  • keeps track of which buttons were pressed, and manages the modes of operation
  • any button can be in ON or OFF mode – reflected in GREEN or RED led status
  • listens for BTNx:y tokens, to put button x in mode y, x={0,1,2}, y={0,1}
  • listens for SSR:y tokens, to turn the SSR on or off and the associated button in that same state (reflected by the LEDs)
  • if the button associated with the relay (SSR) is pressed then the SSR is turned ON or OFF depending on the mode that button transitions to
  • if a button is held pressed for at least 3 seconds (configurable) it enters SYNC mode, explained below
  • if a button has SYNC data it will notify the remote SwitchMotes to virtually “press a button”, and transition that button to the mode specified in the SYNC data
  • if any button is held pressed for at least 6 seconds (configurable) it erases the internal SYNC data in EEPROM. This could be modified such that only the SYNC data associated with the pressed button is erased, not the entire SYNC data
  • notifies the gateway, if any present, that a button was pressed

Note that SwitchMotes loaded with this sketch will work independently and with each other without the need for a network gateway or coordinator. A gateway is by default notified but the feature can be removed if not desired.

Also note that a SwitchMote can work without a relay, in which case only the neutral wire N and a hot wire to either one of S1/S2 is needed. In this case the SwitchMote can just act as a controller for other SwitchMotes or be customized to send other commands to other Moteinos. For instance you could open/close your garage (with GarageMote). The sky is the limit of what you can do.

Further details of the SYNC feature and how to use it are documented on the SYNC mode section of the SwitchMote page. Please refer to that page for any updates and latest information on SwitchMote.

Happy switching & sync-ing!

P.S. This code was released for RFM69 transceivers only because of huge growing interest in these line of transceivers and diminishing interest in RFM12B. You are welcome to port this to a RFM12B implementation as long as you keep within the boundaries of the CC-BY-NC-SA license.

Wireless programming a SwitchMote Moteino

I’m close to being done coding the SwitchMote, I think the code will be released tomorrow. I’ve been testing the code on the SwitchMote here in the lab because I can physically interact with the buttons on it. Needless to say, every time I want to upload the new firmware I cannot disconnect the breaker, unscrew the wall plate and the mains wiring, detach the unit from the wall to be able to upload through FTDI, that would be awful.

Enter wireless, over the air, magic, programming of Moteinos.
I’ll just say that it comes in very handy when your project is in the wall!

I’ll cut this short and let you watch how it happens, too bad the flashing LED is not very visible on the video while upload is in progress:

One note to mention is that I’ve recently patched the wireless programming library to shift frequency up by 8Mhz during upload so the heavy RF traffic would interfere less with the rest of the network packets. Also I added an option to use another LED to be flashed during upload – handy for SwitchMote which has a bunch of LEDs on the front panel which are all on other pins than the default D9. I’m also planning to experiment with increasing the bitrate during the upload, maybe double it, and see how much faster and reliable that is. But that might prove tricky since several other settings depend on that, so all settings have to be changed back to what they were after the upload is complete.

SwitchMote released!

SwitchMote is now finally released and available as a kit in the shop!
Thanks to all the followers for their patience!

There is now a guide page for SwitchMote that includes assembly details, technical specs, and of course relevant disclaimer and warnings. Anyone attempting to buy SwitchMote should read that guide and agree to the terms of purchase before doing so. LowPowerLab assumes no responsibility for how SwitchMote is used.

The guide is a work in progress and more details are added as they become available. Code is not yet published as it needs some final touches, but should be ready in a few days.

SwitchMote has been in development for months and went through several prototype revisions. But it paid off. The current version is stable and more user testing will hopefully lead to turn out even better features and fine tune the future revisions.

SwitchMote project update and demo

I put together a quick video to show the progress of SwitchMote and a simple demonstration of how it works and how it can be used in home automation. My goal is to offer a smart wireless light switch controller that allows syncronization with other units independently (without the need of a gateway/coordinator) to create light scenes, and increase the usability of a regular light switch.

Continue reading

SwitchMote – one step closer to reality!

Just got another batch of SwitchMote and SwitchMote Shield PCBs from OSHPark the other day and I put one together for a test run. In the meantime Kris K has suggested I try another type of cover for SwitchMote. I think his idea was great and today I lasered a few of these covers that are meant to fit in the cutout of a regular rectangular light switch and they turned out very nice. This way people could replace the light switch and keep the original cover, or upgrade to a rectangular cutout cover (HomeDepot has all sorts of light switch covers, even paintable if you’d like to blend them with the wall color). The acrylic is also available in different colors from different sources but for now I’ll go with the usual white I’ve been using before.

The button caps come in different colors so I got a few samples to try out. I think blue, red, yellow and white should cover most needs. The green I found was pretty washed out, didn’t really like it, but I’ll keep looking. Here are a few build photos, and more in my flickr SwitchMote set:

More people started asking when this will be available. I’m already producing custom versions of this and I’m trying to get as much testing done as I can. It is mains power stuff so I’m taking this seriously. This 3rd prototype of SwitchMote includes a varistor and trace fuses for added safety against transients and overloads. I need to develop the firmware stack for this and think of how I want SwitchMotes to interact with each other. The SwitchMotes will need to be wirelessly re-programmable when the need arises so users would not have to disconnect it from the wall when they want to update it. But I want SwitchMote to be pretty autonomous. I will install and try a few on my own, planning on replacing some 3 way switches and some outside lights I’d like to turn ON/OFF from the master bedroom. Fingers x-ed. But so far so good, all the buttons work, the LEDs glow nicely in the dark and are very visible even from a distance, and mechanically the unit is pretty much where I want it to be. This setup should fit easily in any standard switch box.

Will follow up with details on progress, stay tuned!

Wishing a very Happy Holidays Merry Christmas and a Happy 2014 to everyone reading this blog!

Can RFM12B talk to RFM69?

I was asked this question a lot of times. Didn’t have a clear answer because in my early attempts to make them talk to each other I didn’t have success. I didn’t spend a lot of time on that since my interest has leaned towards RFM69 transceivers since they are much nicer and feature-rich overall (nicer packet engine, hardware AES encryption, digital RSSI etc).

Forum user timw has forked my RFM12B and RFM69 libraries and modded them to make them compatible, see this forum post for details. Turns out these mods makes communication possible between RFM12B and RFM69 transceivers. This is great news!

I was able to load his version of the libraries in my Arduino/libraries folder (I had to move/remove my original libraries because of conflicts), and using the examples that come with the two libraries (Struct_receive example on the RFM69 side, and Struct_send on the RFM12B side) I was able to see data coming through the RFM69 end. Seems very stable too. The signal strength (RSSI) fluctuates a little more than if I had RFM69 radios on both ends but it’s great to actually see a signal strength for a RFM12B transmitter:

The caveat is that the encryption must be turned off on both ends with the current version of the libraries. That’s because RFM69 uses hardware AES encryption and RFM12B does not support hadware encryption but uses a software XXTEA algorithm instead. The two are not compatible. One workaround would be to port/duplicate the XXTEA encryption on the RFM69 side, probably a little slower but worth it if encryption is important.

So anyway this should help folks that are trying to salvage their RFM12B nodes and make use of them while moving towards RFM69 based nodes. For me personally I will likely just upgrade everything to RFM69 moving forward but still this is a great development. Thanks timw for sharing your work!