Rentalito goes Spark Core

The Rentalito is a never ending project. It began as a funny project at work using an Arduino UNO and an Ethernet Shield, then it got rid of some cables by using a Roving Networks RN-XV WIFI module, after that it supported MQTT by implementing Nick O’Leary’s PubSubClient library and now it leaves the well known Arduino hardware to embrace the powerful Spark Core board.

Spark Core powered Rentalito

Spark Core powered Rentalito – prototype

Spark Core

The Spark Core is a development board based on the STM32F103CB, an ARM 32-bit Cortex M3 microcontroller by ST Microelectronics, that integrates Texas Instruments CC3000 WIFI module. It makes creating WIFI-enabled devices extremely easy.

The main benefits of migrating from the Arduino+RN-XV bundle to Spark Core are:

  • Powerful 32 bit microcontroller
  • Reliable WIFI connection (auto-reset on failure)
  • Smaller foot print
  • OTA programming (even over the Internet)

And of course it’s a good opportunity to add a couple of features: temperature and humidity sensor and IR remote control to switch the display on and off or fast forward messages.

MQTT support

Spark forum user Kittard ported Nick’s MQTT library to the Spark Core. Since the Spark team implemented the Wiring library for the Spark Core it normally takes very little effort to port Arduino code to the Core.

The library supports both subscribing and publishing. You can subscribe to as many topic as you wish and you get the messages in a callback function with the following prototype:


void (*callback)(char*,uint8_t*,unsigned int);

From here it’s very easy to just store the last value for every topic we are subscribed to, along with some metadata like the precision or the units.

Publishing is even easier. A simple call to publish method is all it takes:


bool PubSubClient::publish(char* topic, char* payload);

DHT22 support

DHT22 support is provided by another port, in this case from Adafruit’s DHT library for Arduino. Forum user wgbartley (this guy is from the Spark Elite, people that basically live on the Spark forums) published the ported DHT library for the Spark Core in github.

Recently another user (peekay123, also from the Elite) has published a non-blocking version of the DHT22 library. It uses interrupts to trap transitions on the data line and calculate timings and a state machine to track message structure. The previous one performs all the calculations in a single method call and disables interrupts to keep control over the timing.

HT1632C dot matrix display support

This one I ported it myself from my previous fork of the original HT1632C library for Arduino by an anonymous user. You can checkout the code at bitbucket (Holtek’s HT1632C library for the Spark Core). The library supports:

  • 32×16 displays
  • drawing graphic primitives (points, lines, circles,…)
  • drawing single colour bitmaps
  • printing chars and texts in fixed positions or aligned to the display boundaries
  • red, green and orange colours
  • 23 different fonts
  • 16 levels of brightness
  • horizontal and vertical scroll

It’s still a work in progress but it’s almost in beta stage.

IR remote support

I had an old-verison Sparkfun IR Control Kit (check it here) laying around and I thought it was a good idea to have a way to switch the LED display on and off. I struggled for a couple of days with the IRRemote library for Arduino (like some others) but finally I quit and I decided to implement my own simpler version.

The approach is very much the same as for the DHT22 non-blocking library before: an interrupt-driven routine that calculates and stores pulse lengths and a state machine to know where in the decoding process we are.

void ir_int() {

    if (ir_status == STATUS_READY) return;

    unsigned long now = micros();
    unsigned long width = now - ir_previous;

    if (width > BIT_1) {
        ir_pulses = 0;
        ir_status = STATUS_IDLE;
    } else {
        ir_data[ir_pulses++] = width;
        ir_status = (ir_pulses == 16) ? STATUS_READY : STATUS_DECODING;
    }

    ir_previous = now;

}

Then in the main loop we check if the message is ready, perform the corresponding action and reset the state:

if (ir_status == STATUS_READY) {

    if (millis() > ir_timer) {

        int key = ir_decode();

        switch(key)  {
            case 10: next(); break;
            case 18: previous(); break;
            case 34: brightness(1); break;
            case 42: brightness(-1); break;
            case 2: toggle(); break;
            default: break;
        }

    }

    ir_status = STATUS_IDLE;
    ir_timer = millis() + IR_DEBOUNCE;

}

The decoding is a matter of translating pulse lengths to bits.

int ir_decode() {
    unsigned int result = 0;
    for (byte i = 0 ; i < 16 ; i++)
        if (ir_data[i] > BIT_0) result |= (1<<i);
    if (REMOTE_CHECK != (result & REMOTE_CHECK)) return 0;
    return result >> 8;
}

It’s very important to add some noise reduction components around the IR receiver, otherwise you will only get streams of semi-random numbers every time you press a key in the remote. You can check the datasheet for the specific model you are using (for instance, check the “application circuit” in the first page of the TSOP382 IR receiver Sparkfun sells) or check the schematic in the next section.

Schematic and layout

The project is mostly a software Frankenstein (well, not quite so, you can check the code in bitbucket). The hardware part is pretty simple. You can get all the information you need from tutorials and datasheets. My only advice is to add noise suppression circuitry around the IR receiver.

Schematic

Schematic

Next steps

I’m ready to try to do my first home etching experiment and this project looks like a good candidate. The first step was to create a board layout using Eagle. The board should be one-layered and the form factor the same as the Arduino, so it could use the same holes the Arduino did in the display frame.

And this is the result:

Board layout

Board layout

As you can see it’s mostly one-layered, I will have to use one wire to connect the DHT22 sensor VCC pin. The layout looks promising and I’m eager to see the final result. Hopefully I will post it here soon.

Thanks for reading!

Light table: a family project

My older daughter (she’s 4 years) loves drawing. My younger daughter (she’s 1 year old) loves doing whatever her sister does. So last Christmas the three wise men carried a new kids table for them. The “old” one was quite abused already. You get to know how tough things are when you let a kid play with them for a while… Anyway we had already thought about a second life for it.

The poor old IKEA Lack Table

The poor old IKEA Lack Table

Some time ago I stumbled on a great “instructables” by Mr. Chutney where he repurposed exactly the same IKEA table we had as a light table. It was very easy and the light table was going to be a great fun for our daughters so I ordered a methacrylate board from a local supplier and a really cheap LED Strip from Amazon Marketplace (mine included a 12V 5A EU-plug power supply) and waited patiently for them to arrive.

5 meters 5050 RGB Led Strip with remote & power supply (courtesy of Amazon.es)

5 meters 5050 RGB Led Strip with remote & power supply (courtesy of Amazon.es)

Bill of Materials

  • An IKEA Lack Table (6.99€)
  • Am 5 meters RGB 5050 LED Strip, with remote and power supply (I bought mine for 15.50€)
  • A 550x550mm methacrylate board, snow-translucent (44€ from local supplier). Have them drill 4 holes in the corners for you: 5mm diameter, 30mm from each side.
  • 4 20x5mm, round head, screws to fix the methacrylate sheet to the table (some cents)
  • A 2.1×5.5mm DC barrel jack for box mounting like this one (0.74€)
  • White glossy paint (optional but recommended)
  • Tooling (a Dremmel to cut the table although a cutter might do, a paint brush, masking tape, wires, ruler, pencil, safety glasses and a dust mask…)

Yep, that’s just about 67€ of materials. Not bad if we compare it with the 300€ of the cheapest ones you can find on the Internet.

Procedure

Since Mr. Chutney article is very explanatory I will only comment the differences in my approach. He used two sheets of translucent material: a 8mm clear acrylic sheet that fits in the table hole and a second thinner 3mm “opal” one over it without covering the entire table surface. To do so he needed to recess the solid table legs in the corners to hold the first acrylic sheet which should fit exactly the hole dimensions.

Since “exactly” is too precise for me I planned a simpler solution. Besides, I wanted the translucent sheet to cover the whole surface of the table so I just cut the hole leaving 50mm each side (the size of the legs) and bought a 550x550mm translucent sheet with four holes where I would screw it to the solid legs. You can order the methacrylate sheet with rounded edges for a better finish but laser cut finish was OK for me.

Dremmel is my friend

Dremmel is my friend, sorry tindie…

Safety first

Safety first (yep, that’s me)

Use a screwdriver to lift the wood, it's glued to the underneath cardboard.

Use a screwdriver to lift the wood, it’s glued to the underneath cardboard.

Under the thin wood surface of the table there is a pattern of cardboard that provides consistency to the table while keeping it light. The cardboard is easily removable by hand leaving a nice space under the remaining table surface for the LED strip controller.

The cardboard patterm

The cardboard patterm

Removing the cardboard

Removing the cardboard

Once I had the interior clean I painted it with white glossy paint. As Mr. Chutney says it does make the difference. This was my 4 year old daughter task and she enjoyed messing with the paint (maybe too much).

The insides of the table painted white. My daughter painted too much...

The insides of the table painted white. My daughter painted too much…

Then I drilled a hole the size of your DC barrel jack near one of the legs. The barrel jack is a neater solution than having a cable hanging from under the table. My LED strip came with a short 2.1×5.5mm pigtail which I soldered to the terminals of the jack but you can just wrap the wires to them and use some glue, electrical tape or a small stretched plastic tube to keep them in place.

It was time to run a quick test to see if everything was OK. I connected the strip and the short power cable to the controller and the power supply to the jack under the table, pressed the ON button in the remote and the LED strip shined white. Good.

Next step was to plan how to stick the strip trying cover the whole surface evenly to have a uniform light. I tried a couple of approaches starting from the end near the controller. The final one is a “S” pattern but now that I’m thinking about it again I will probably try a new one next time I open the table: a squared ellipse going outside in. The wood surface is rough and chances are your strip wont stick long. I used some tape to keep it in place.

The LED strip in place

The LED strip sticked to the wood with the help of some tape.

I used adhesive white paper to hide some scribbles and stickers on the remaining surface of the table. Using some masking tape and painting it white would have been also an option.

Detail of the barrel jack from inside

Detail of the barrel jack from the inside

The jack from under the table, with the power supply plugged in.

The jack from under the table, with the power supply plugged in. What’s the other hole for?

Finally I screwed the methacrylate sheet to the table with four 20x5mm round head screws.

The table with the methacrylate sheet

The table with the methacrylate sheet without the screws while doing some final tests

The LED strip I used is an RGB one with 5050 chips. You can’t control the LEDs individually (they are not addressable) but you can set the whole strip to whatever color you want. The controller has a 2.1×5.5mm barrel jack for power input, a 4 wire connector for the LED strip and an IR receiver that reads the codes from the remote even through the sheet of methacrylate. So you just point to the table and select the color you want and voilà. My daughters love it!

The LED strip controller

The LED strip controller. The black thingy at the end of one of the cables is an IR receiver

Conclusions?

This is a low-tech project but a very fun one. If you have kids they will love this table. My little one (1 year old) likes playing with some colored rounded glasses we have, spraying them over the table and changing the light color with the remote to see how the glasses change. The older one uses it to copy drawings or x-ray negatives and it doubles as a chillout/mood light for their bedroom!

X-ray negative on the light table

X-ray negative on the light table

The only issue I had was with the brightness control and the effects. Although the remote has a couple of buttons to rise and lower brightness it simply doesn’t work. And three out of the four color effects you can play with are just too psychedelic for my taste (strobing light, flashing,…).

But maybe I can do something about it… :D

Building Spark Core firmware locally

I have recently started a couple of projects based on the great Spark Core board. Hopefully I will be able to talk about them here soon.

The Spark Core

The Spark Core (courtesy of spark.io)

The Spark Core is a development board based on the STM32F103CB, an ARM 32-bit Cortex M3 microcontroller by ST Microelectronics (the same you can find in the new Nucleo platform by ST) that was crowd-funded through a kickstarted campaign. But there are some big things about this board.

  • First, it comes with a CC3000 WIFI module by Texas Instruments, which is the shiny new kid on the block. Adafruit has the module available in a convenient breakout board.
  • Second, it is Arduino compatible in the sense that it implements the wiring library, that is, you can port Arduino projects to this board with little effort.
  • Third, Spark.io, the company behind the Spark Core, has developed a cloud based IDE you can use to write your code and flash it to your Spark Core Over the Air (OTA).
  • And fourth, you can communicate with your Spark Core with a simple API through the cloud, exposing variables and invoking methods.

It is really awesome, and it works!

Now there are similar solutions, even for the Arduino platform, like codebender.ccwifino.com or the mbed Compiler, but they don’t pack all the features Spark Core does, and the hardware they require is more expensive and sensibly bulkier.

The team at Spark.io is very involved and active so I foresee a great future for their solution, but there are still lots of things to polish. They are facing some criticism due to the fact that the Spark Core has to be connected to the cloud in order to work, that means it needs a WIFI connection and Internet access. Besides, that also means that all the communications have to pass through Spark.io servers. But this will soon be only optional. On one hand they are refactoring the code to remove the requirement for the Spark Core to be connected at all, and on the other hand they are about to release their cloud server under an open source license (the firmware is open source already) so you could have your own cloud in your own server. The release of their cloud server will be a major event. The Spark Core strength lies on the possibility of flashing it remotely and the API to execute methods and retrieve values.

In the mean time I have to say that building and flashing the code remotely is slow… If you are like me and want to code small iterations and build frequently it is a bit frustrating… But since the firmware is open you can build it locally.

The Spark Core firmware is split into 3 different repositories: core-firmware, core-common-lib and core-communication-lib, totaling almost 500 files and more than 336k lines (including comments, makefiles,…). It is big. To build your own firmware you have to modify/add your files to the core-firmware project. This means having copies of this repository for every single project you are working on. And this repository alone is +187k lines of code. If you use a code versioning system for your code (GIT, SVN,…) you have two main options: forking and have big repositories or ignoring a bunch of files (but having the whole firmware code in the working copy, presumably outdated). Not good.

So I decided to go the other way round. Projects with just the minimum required files and a way to transparently “merge” and “unmerge” a single core-firmware folder with my project. I have created a small bash script that does that and allows you to build and upload the code from the command line without leaving you project folder.

I don’t know if I am reinventing the wheel but “my” wheel is making me save a lot of time. I can manage my build from within my favourite IDE (vim) keeping the main core-firmware folder clean and up to date.

The code is in the spark-util repository at bitbucket. The README file explains the basics of it and provides some use cases.

Any comment will be very welcomed.

Ciseco XRF modules & LLAP Protocol

In my last post about counting events with Arduino and PCF8583 I talked about this “yet another weather station” project I was working on last summer. The station was deployed in the garden of a cute apartment we rented in an old “masia” near Olot, 100 km north of Barcelona. It is in the mountainside, surrounded by woods and 10 minutes walking from the near town. It has a beautiful garden with plenty of space. We spent there most of the summer but now we are still driving there on the weekends. It’s colder, sometimes freezing, and when it rains, well, it does rain. Off course it was the perfect excuse to build another weather station.

One decision I had to take when designing the new weather station was how to send data from the nice housing I built for it in the garden to my home server in Barcelona. I needed some kind of internet connection in the house but that’s something I will talk about in another post. I could have used a RN-XV WIFI module like the one I’m using for the rentalito but it’s expensive and I really wanted something simpler to use.

I had already a couple of Ciseco’s XRF radios and decided to give them a try (they are now selling version 2 of theses radios, I have v1.5 modules). These modules provide an easy way to create a wireless transparent RF serial connection between two nodes, no need to configure anything. They have a better range than Bluetooth, WIFI or Zigbee, since they use a longer wavelength to operate (868 to 915 MHz). Off course they can do a lot more than that. They are based on Texas Instruments’ CC1110, a low-power System-on-Chip and you can write and load your own firmware on them. Ciseco provides a series of closed-source firmwares (they call them “personalities“) for these radios, focused on different sensor inputs. You can find more information in the openmicros.org wiki, there is enough to spend a couple of hours reading but I have to say the wiki is kind of a mess, although they have improved it a lot in the last year or so.

Ciseco XRF wireless RF radio

Ciseco XRF wireless RF radio v1.5

Anyway, out-of-the-box these modules are a transparent RF link and their footprint is compatible with XBee modules, so you can use them with your XBee Explorers, Arduino FIOs,… (well played Ciseco). Like in my previous weather station I decided to use an Arduino FIO as a controller (DC-IN, LiPo battery backed, XBee socket,…) so I just stacked one of these modules on it. Inside the house I prepared the “gateway”: an Arduino Leonardo, with an Ethernet shield and a Wireless Shield with another XRF module. The Ethernet shield connected the Arduino to a TP-LINK WR703N WIFI router loaded with openWRT with a 3G USB stick. The small router provides internet connection to the Arduino and to any other device inside the house via WIFI. The WR703N is a really awesome, small and hackable piece of hardware. But as I have already said, you will have to wait for the whole picture of the connection between the weather station and my home server, I want to focus on the radios and the protocol now.

Now that we have the hardware it’s time to think about the message. Ciseco promotes the use a a light-weigth protocol named, well, Lightweight Local Automation Protocol, or LLAP. You can read all about it in the LLAP Reference Guide in the openmicros.org wiki. The protocol defines two node types: controller and device; a message format formed by a start byte (‘a’), device identification (2 bytes) and a payload (9 bytes); and a communications protocol (address allocation, request/response pairs,…). The different “personalities” provided by Ciseco use this message protocol to report sensor values and they can even be configured remotely this way. But Ciseco also provides an Arduino LLAPSerial library so anyone can easily create LLAP devices using XRF radios or other products from the company that integrate a MUC.

Ciseco LLAP library for Arduino is OK, and it works, but it looks like a draft, something you can use to build upon it. So I decided to do just that. You can checkout my version of the LLAPSerial library for Arduino from Bitbucket. Initially I did a fork of Ciseco version but finally I decided to break the dependency with it because some features I added made it incompatible with the original one, although the protocol is 100% backwards compatible. The differences are summarized in the README file but here you have a quick-view:

  • Removed power management code (this library focuses on LLAP protocol and messaging)
  • Added support to use different Hardware and Software serial ports
  • Provided a unique overloaded sendMessage method that supports sending char/int/float messages
  • Provided a way to broadcast messages (see below) using special device ID ‘..’
  • Defined the “coordinator” node, which will always process all messages, regardless the destination
  • Disallow CHDEVID to coordinator nodes
  • Major renaming and refactoring (sorry)
  • Added doc comments
  • Address negotiation and persistence NEW!!

This sample code shows the use of the library to report data from a DHT22 temperature and humidity sensor using LLAP.


#include <LLAPSerial.h>
#include <DHT22.h>

#define DEVICE_ID "DI"
#define DHT_PIN 2

// DHT22 connections:
// Connect pin 1 (on the left) of the sensor to 3.3V
// Connect pin 2 of the sensor to whatever your DHT_PIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT22 dht(DHT_PIN);
LLAPSerial LLAP(Serial);

void setup() {

   // This should match your radio baud rate
   Serial.begin(115200);

   // This device has a static ID
   LLAP.begin(DEVICE_ID);

}

void loop() {

   static unsigned long lastTime = millis();
   if (millis() - lastTime >= 10000) {

      lastTime = millis();

      DHT22_ERROR_t errorCode = dht.readData();
      if (errorCode == DHT_ERROR_NONE) {
         float t = dht.getTemperatureC();
         float h = dht.getHumidity();
         LLAP.sendMessage("HUM", h, 1);
         LLAP.sendMessage("TMP", t, 1);
      } else {
         LLAP.sendMessage("ERROR", (int) errorCode);
      }

   }

}

There are some things missing from the library, being the main one the address allocation feature the protocol describes (also missing from Ciseco’s implementation). I will try to add it soon. In the meantime feel free to use any of the two libraries and enjoy the simplicity of LLAP. The last version of the library supports address negotiation between the nodes and the coordinator following the guidelines at LLAP Reference Guide, including address persistence, so a node will keep its address after a reboot.