Archive for the ·


· Category...

ESP8266 galore

Comments Off

More than a year ago, I tried out the ESP8266, but didn’t get very far. The scene and products have evolved a lot since then, and today it’s as easy to use and develop with the ESP8266 as with the Arduino. Some shields are also coming online, although there are no common form factors yet.

DealExtreme stocks a number of different boards and chips. Among them, the most interesting are the various boards from Wemos. They have a two form factors: The “D1″, a rather large board which matches the Arduino Uno layout and header pins; and the neat and small “D1 min” at only 34×25 mm. What makes the latter very appealing, is a range of small shields which stack on top of each other, just like the old Arduino.

There are already several interesting shields available from Wemos. Including a temperature sensor; 64×48 pixel OLED display; 220 V relay; motor driver; SD card; battery connector; single button; single LED; and a DIY “proto board”. These are not available from DX, and are best ordered from Wemo’s AliExpress shop. Please note, the ones linked here do not have the header pins soldered, so a bit of manual soldering work is required.


Comments Off

DIY Arduino Debug Shield

Comments Off

Debugging with LEDs; it’s probably even more primitive than debugging with printf statements. However, to get a very immediate feedback on what’s happening, or which pins are in use, it can be useful. So what better way then than a ~$2 homemade shield to pop on top of your existing project.

DealExtreme supplies all the parts needed: A versatile prototyping shield board with holes and wires in sensible locations; a bag of assorted LEDs; resistors; and header pins. (The board and headers in this project used 6x and 8x header pins, to fit with the older Duemilanove. The Uno another other boards have slightly different pin layouts, so plan ahead).

Now, I’m not an expert at soldering, nor product design, but this shield does the job, and already helped in programming my next project. Lesson learnt: Lay out the components all the way before heading off with the iron. I should have gone with the 3mm LEDs all the way. Or, maybe surface mount could have worked. Next time.

Comments Off

Hello World! from the UG-2864 “OEL Display Module” / SSD1306

Comments Off

There is a wide range of cute small OLED (organic LED, aka. Organic Electro-Luminescence) display modules around. Adafruit has a range, the same or similar can also be found all over eBay and Amazon, and of course from DealExtreme. They are available in modules for the Arduino, Raspberry Pi, or other micro controllers. Some are based on basic DATA, CONTROL, LOCK interfaces, while others implement the SPI or I2C bus protocols. The OLED makes for a bright high contrast wide viewing angle screen. Most are monochrome, while a few come with 16 bit colors.

I got the $7 0.96 inch 128*64 pixel I2C version from Deal Extreme. It is indeed small, but also very nice and sharp. Even small fonts are easily readable. It was easy to get up and working with the Arduino UNO, although with a few gotchas to watch out for. The I2C interface makes it very easy to hook up, with only two wires in addition to power (5V and ground).

For background, this GeekOnFire page goes into detail about the memory addressing and low level commands. Further details can be found in the Univision Technology display (UG-2864HLBEG01, UG-2864HSWEG01) and Solomon Systech driver chip (SSD1306) data sheets. See also this note which compares the SPI and I2C protocols.

Scan and Detect

There are also multiple drivers and graphics libraries around, some of which are available directly through the Arduino IDE Library Manager. I’ll go through the details below, but before we get there, make sure the module is hooked up correctly and detected. See the Arduino Wire library reference for which pins to hook up. It varies based on Arduino board and version.

Note, for the Arduino Uno, the pins are Analog 4 and Analog 5.

Once plugged in, copy the sketch from this simple I2C Scanner, and upload. Open the Serial Monitor, and observe something like “I2C device found at address 0x3C“.

Take great care to note the exact address. It might be either 0x3C or 0x3D, and the libraries below will have to be modified accordingly.


The U8glib library supports a long list of different LEDs. It is available directly from within the Arduino IDE Library Manager by searching for “U8glib”. Once installed, open the Examples list, and try the “HelloWorld” example.

However, before uploading, you need to uncomment the correct display. In my case, it was around line 90, and looked like:

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0); // I2C / TWI

Once uploaded, the display should show “Hello World!”. Also try out the other examples, like the GraphicsTest, but make sure to always uncomment the correct initialization line.


The Adafruit library focuses on the displays they offer, and comes in two parts, the SSD1306 driver and the Adafruit Gfx library. Searching for “Adafruit SSD1306″ and “Adafruit gfx” in the Arduino IDE Library Manager should give perfect hits.

The Adafruit driver and examples take some custom modifications before they work, though. First, in the file Adafruit_SSD1306/Adafruit_SSD1306.h, make sure the following lines are uncommented and correct according to the display you have (see the scanner section above). Make sure the other similar lines above or below are commented out.

#define SSD1306_I2C_ADDRESS 0x3C

#define SSD1306_128_64

Secondly, in the ssd1306_128x64_i2c example sketch, again make sure that the address is defined correctly, according to what the scanner said. Within the setup() method, you will see this line, which you might have to modify:

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);


Finally, the GeekOnFire library is yet another easy wait to get started with the OLED display. It is not available in the Arduino Library Manager, but can just as easily be downloaded from their site, and installed from the Arduino IDE through its ZIP file.

As with the Adafruit library, the I2C address has to be modified, and a similar initialization line can be found within the setup() method of their examples:


Comments Off

RFID tag reading with the RDM630 module

Comments Off

To read RFID tags with an Arudino is easy using the RDM630 card reader module (also sold as RDM6300 in a slightly different version). It’s available from DealExtrme, including a pack of 10 RFID cards, or keychain fobs. These are all based on 125 kHz cards and reading, using the EM4100 protocol. (That is important, since there are many different frequencies and protocols used under the same umbrella name RFID).

John Boxall at has an excellent beginner’s tutorial on using the module. Hooking up the module is easy, needing only +5V and ground, plus a single pin (lower left on the RDM6300) to a digital pin on the Arduino. He opts for using SoftwareSerial so he can define the incoming RX data pin to something else than the standard pin 0. That way, it does not interfere with the serial transfer while uploading new sketches.

Reading from the module then boils down to reading from the SoftwareSerial class. In essence, it looks some like this, when surrounding boilerplate is removed:

#include <SoftwareSerial.h>
SoftwareSerial RFID(2, 3); // RX, TX

// setup

// loop
if (RFID.available() > 0) {
  int byte =;

He goes on to implement some convenience methods which parse the incoming numbers and compare them to a whitelist of accepted cards.

The only missing feature I had wished for in this reader, is to detect multiple cards at once. As far as I understand, that is not possible, and only more expensive readers (or possibly other protocols) can do so.

Comments Off

Wifi with the ESP8266

Comments Off

The ESP8266 is an interesting chip that has gained a lot of traction lately. At only $5, it’s quite impressive what you get: a wifi to serial adapter, a TCP/IP stack, and even an embedded user-programmable micro controller. It is in fact a complete System-on-a-Chip itself. As an adapter, it can easily be connected to a micro controller like the Arduino, and there is now also an SDK to program it stand-alone. Espressif, the Chinese company behind it targets the “Internet of Things” market, which is bound to grow in the near future. They also seem keen on creating an open source community around the chip, with an open source Github project, the open source SDK, and a community forum.

The chip comes on a large range of modules and break-out boards, as seen below. Deal Extreme stocks most of them, and I got the ESP-01 with easy to use header pins.

With a bit of help from various blogs about the board, I had it up and running. The basics are neatly explained by ray, with the AT commands to try out first. shin-ajaran goes into a bit more detail about the wiring and other options. And once you have it running, the MIT class instruction mentions a few scripts to try out. Finally, Dave Vandenbout explains firmware flashing and more advanced use.

My own Hello World attempt does not add much to what is already mentioned above. To summarize, my basic setup includes:

  • The ESP-01 ESP8266 board.
  • A USB-to-TTL serial cable, e.g. based on the PL2303
  • Assuming you get a 5V USB-TTL cable, you need to lower the input voltage. I got the $2 AMS1117 Power Module
  • Two resistors for a 5 to 3.3 voltage divider. I went with 100 and 220 Ohm; see shin-ajaran blog post for details.
  • A breadboard to connect the voltage divider.
  • Also note, I had to connect both the reset (RST) pin and CH_PD pin to 3.3 VCC before the terminal on the computer connected.

In the pictures below I’ve tried to show my setup. Not sure how much clarity it adds, though. It shows the pins of the esp-01: red for 3.3 VCC, black for ground, green for URXD (connected via a voltage divider, and matching green on the PL2303 cable), and yellow for UTXD (connect directly to white on the PL2303 cable). The breadboard shows the voltage divider, and all the red VCC wires connect (but of course not connect to the resistors).

Comments Off

Soil Moisture Sensor

Comments Off

Over at Andrew Frueh has an interesting article on a DIY soil moister sensor. It is simply two large nails with wires attached. By measuring the resistance of the soil between the nails, he gets a crude measurement of how wet the soil is. The more water, the lower resistance. He points to a few problems with this approach, including temperature affecting the resistance, as well as salinity and pH levels playing a role. Furthermore, electrolysis and corrosion is a problem over time. Frueh has improved on the basic circuit by using a H-bridge to alternate the direction of the current for the readings. That way, the nails last longer.

A different approach to measuring soil moisture, is to measure the dielectric constant. An example of such a sensor is the commercial product VG400 from Vegetronix. It sells for $37, so it doesn’t scale to use it for many plants the same way as two nails does. The method is interesting though, with more basic information in this University of Cambridge module.

Comments Off

3x3x3 LED cube with fewer wires

Comments Off

A few weeks ago, I mentioned that it would be possible to optimize the number of wires and components needed for a 3x3x3 single colour LED cube by using “the 9th bit” (the output pin, intended for daisy chaining) on a 8 bit serial in / parallel out shift register. Other examples of the 33 cube I’ve seen are simply pulling 12 wires (9 LEDs on each layer, and 3 layers) back to the Arudino. At that scale, it is of course feasible, but still, when it’s possible to get by with half, why not? So I put together a small 33 cube doing just that.

Previously, I made the claim that the 8 bit shift register retains 17 bits of data. I’ll have to revise that down, to 16.5 bit. It is possible, as already mentioned, to use the output pin as a 9th visible output, as seen in the images and code below. However, the value of the output pin is shared with the 8th element of internal register, thus 17 distinct bits are not realised. It becomes more clear when considering the timing diagram of the of 595. Below is an extract and cut-out from the Texas Instruments data sheet [PDF].

The diagram above is truncated both in the horizontal and vertical axis, to highlight the last cycles, when the output pin, denoted QH’ in the digram, gets its value. As can be seen, when the 7th pin, or QG, is shifted up one (the first red line, when RCLK goes from high to low), QH’ gets that bit set as well. Note that the internal states of the shift register is not shown here. In the next cycle, SRCLK is latched, and the internal value of the 8th pin is made visible on QH, on the yellow line. The result is, that either QG + QH’ are on at the same time, or QH + QH’. This was frustratingly easy to reproduce in code, but not what I wanted.

To control all the nine LEDs of a layer independently, I had to set the output pin after the other eight pins were latched. However, if cycling quickly, it would then not get enough time on, and thus would look very dim. The final trick was to insert a short delay after all pins were set correctly, as seen in the code and discussion on timing below.

For the construction of the cube, I used LEDs from a 100-pack for $4.30 from DealExtreme, soldered onto a small 4x6cm (14×20 points) PCB. Following “fruitkid101″ video instructions, I drilled holes for a template in a piece of wood. As it was all by hand, it turned out a bit skewed, but for this small project I found it didn’t matter so much. Next time I’ll be a bit more precise. Soldering the legs together turned out be easy. I made the spacing between the LEDs small enough for one cathode leg to reach across its two neighbours, which meant that I only had to bend the ones in the corner. I soldered the corners first, and then the ones in between, finishing off with the centre LED. Positioning the anode legs between the layers was a bit more tricky, but with a double bend, as seen in the picture below, it was easy to make the leg from the layer beneath stay close enough to solder to its upstairs neighbour. Since the joints were for both the electrical contact, as well as the structural, I applied quite a bit of solder.

The interface to the Arduino is through the three direct pins which controls the sinks for each layer, and three pins for data, clock and latch of the shift register. The overview can be seen in this picture, and below. The small breadboard with the shift register also contains a 100 Ohm resistor for each pin, including the output pin.

As mentioned above, part of the motivation for this project was to control the cube with fewer pins, and use the output pin of a shift register for the 9th LED. That led to another interesting revelation in the code, and how to control brightness. As seen in the snippet below, which includes the display() method and the external fields used, the first inner for-loop for the shift register is all normal. It shifts the first 8 bits, with Most Significant Bit in the 8th element (index 7) of the display buffer buf[]. Surrounding that for-loop is the latch, however, notice that on the first line of the outer for-loop, the layer pin is set HIGH, which means, it is turned off. Before the layer we operate is turned on, the output pin is set to the value of buf[8] (and equivalent for higher layers). This is done within the second inner for-loop, inside the if-block. Strictly speaking, the if was not necessary; it would have been fine to shift out the extra bits every time.

Only after every pin is set to its correct state, is the layer turned on and the LEDs lit. However, if doing this without a delay, the LEDs would seem very dim, or almost off. Even if running the display() method only takes 400 micro seconds without the delay, for a good 2500 iterations per seconds, the problem would be that the LEDs would be turned off most of the time. To fix that, the delay is inserted, which holds the LEDs for a little while per iteration over a layer. With a one millisecond delay, the full method takes 3.4 ms, and can be executed ~300 times per second or a 300 Hz refresh rate of full cube.

However, with a delay of only 1 millisecond the LEDs are still somewhat dim. The fraction of time where the LEDs are off is still significant: For each layer 400/3 = 133 µs off vs. 1000 µs on, or about 12% of the time. If the delay is increased to 2 milliseconds, that ratio goes down to 6%, and the LEDs are noticeable brighter. The refresh rate goes down to ~150 Hz, but we are still far from the 50 Hz limit which is required to avoid flickering. In fact, we can go all the way up to a 6 ms delay before the limit is near (1000 ms / 50 / 3 = ~6 ms). However, it is hard to notice a difference between 3 and 6 ms delay. It would have to be measured. The lesson learnt then, is that it is not the refresh rate which matters the most when multiplexing LEDs, but rather the ratio of time the LEDs are on. Furthermore, with a 16 MHz MCU like the ATmega328, there is plenty of room for doing other stuff, and little need for premature optimization of code.

Future work will include utilizing the Arduino timer library for controlling the display buffer. Currently, that bit of the code is rather clunky. I would also like to experiment with fading and controlled blinking. Again, the timer library will be useful, but I’d probably also use the buffer to hold an intensity value, rather than just on/off. Also, I would like to measure the brightness with the different delays discussed above. One way would be using an LDR (light dependent resistor), but I might also look at the cheap $30 lux meters from DealExtreme. Finally, I’ll of course have to make some interesting patterns and animations, which should lead to an API for some level of abstraction. There’s lots to do!

Extract from code. See the full file for further details and GPL 3 license.

// Digital output pins

const int data =  5;
const int latch = 6;
const int clock = 7;

const int layer0 =  9;
const int layer1 = 10;
const int layer2 = 11;

const int layers[3] = {layer0, layer1, layer2};

const int outputPinCount = 6;
int outputPins[outputPinCount] = {
  data, clock, latch, layer0, layer1, layer2};

// Frame buffer
const int lights = 27;
int buf[lights];

void display() {
  for(int l = 0; l < 3; l++) {
     // Turns the layer off
     digitalWrite(layers[l], HIGH);
     // Shifts out the first 8 bits
     digitalWrite(latch, LOW);
     for(int i = 0; i <= 7; i++) {
       digitalWrite(clock, LOW);
       int bit = buf[l*9 + 7-i];
       digitalWrite(data, bit);
       digitalWrite(clock, HIGH);
     digitalWrite(latch, HIGH);
     // Shifts 9 more bits to set the output pin
     if (buf[l*9 + 7] != buf[l*9 + 8]) {
       digitalWrite(data, buf[l*9 + 8]);
       for(int i = 0; i <= 8; i++) {
 	digitalWrite(clock, LOW);
 	digitalWrite(clock, HIGH);
     // Turns the layer on, and hold for 3 ms
     digitalWrite(layers[l], LOW);
     // Turns the layer off again
     digitalWrite(layers[l], HIGH);

Comments Off

16×2 LCD and button shield

Comments Off

I recently picked up this 16×2 character LCD and button shield from DealExtreme. It is similar to the Hitachi based shields and displays sold elsewhere, but with a slightly different pin-out. It still fits right onto the Uno or Duemilanove. For only $6 it’s almost a must in any project toolkit. What’s more, it’s compatible with the LiquidCrystal Arduino library, and very easy to get started with. Just note the modified pin connections, and you’re set to go.

The sketch below will display “hello world”, a counter, and the value of the button presses on the screen. Furthermore, you can use the up and down button to adjust the back-light brightness. Just an example; I’m sure there are unlimited uses for this screen.

Please note, the button values was what I read from my shield, through the analog pin. Although it seems very consistent, other shields might give different readings. It’s probably a good idea to shift off the two least significant bits to allow for some leeway.

// Code under GPL; please see full file for details.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup() {
  pinMode(10, OUTPUT);  // for backlight adjustment
  lcd.begin(16, 2);

  lcd.print("Hello World!");

int button_value;

int light = 100;

void loop() {
  lcd.setCursor(0, 1);
  button_value = analogRead(A0);
  if (button_value == 132)
    light = min(light + 1, 255);
  if (button_value == 306)
    light = max(light - 1, 0);
  analogWrite(10, light);  

  String tmp = " ";
  tmp += light;
  tmp += " ";
  tmp += button_value;
  tmp += "   ";  // erase previous digits

  lcd.setCursor(4, 1);  

Comments Off

Sparkfun orders

Comments Off

Here’s a list of items I’ve ordered from Sparkfun over the years. Mostly for my own reference than anything else, and maybe not of much interest to others.

 Stepper Motor - 125 (200 steps/rev)  Stepper Motor - 68 (400 steps/rev)  Hook-up Wire - Red  Liquid Pump - 350GPH (12v)  Arduino Uno - R3 Nut - Nylon (4-40 Stackable 10-Pin Header AVR 8 Pin 10MHz 1K 4A/D - ATtiny13 10 segment LED gauge bar P-Channel MOSFET 60V 27A N-Channel MOSFET 60V 30A Jumper Wire - 0.1 4-pin Voltage Regulator - 5V Electrolytic Decoupling Capacitors - 100uF/25V JST Right-Angle Connector - Through-Hole 2-Pin JST Right Angle Connector 5 x Rectifier 1N4007 3 X Transistors - NPN 2N3904 3 X Transistors - PNP 2N3906  XT60 Connectors - Male/Female Pair JST RCY Connector - Male/Female Set (2-pin) Resistor Kit - 1/4W (500 total) RF Link Transmitter / 434 MHz RF Link Receiver / 434 MHz  BigTime Watch Kit  Capacitor Ceramic 22pF  Tweezers - Straight (ESD Safe)  Crystal 16MHz  Ceramic Resonator 16MHz  AVR 28 Pin 20MHz 32K 6A/D - ATMega328  ATmega328 with Arduino Optiboot (Uno)  STK500 Compatible USB Programmer  Miga NanoMuscle  Ribbon Cable - 6 wire (15ft)  PIR Motion Sensor  Stepper Motor with Cable  Hook-up Wire - Red  Light Pipe - Clear Core (6mm  Light Pipe - White Core (6mm  Light Pipe - White Core (3.5mm  I2C EEPROM - 256kbit  Heat Shrink Kit  Hook-up Wire - Yellow  Ribbon Cable - 10 wire (3ft)  Ribbon Cable - 6 wire (3ft)  Hemostats - Straight  Solder Wick #2 5ft. - Generic  6 Pin Right Angle Female Header  Hook-up Wire - Black  XBee Explorer Dongle  RFM22B-S2 RF Transceiver Breakout Board  RF Link Receiver - 4800bps (434MHz)  RF Link Transmitter - 434MHz  EasyDriver Stepper Motor Driver  Small Stepper Motor  Temperature Sensor - LM335A  IC Hook with Pigtail  555 Timer  XBee 1mW Chip Antenna - Series 1  Infrared Emitters and Detectors  Open Logic Sniffer - Probe Cable Kit  IC Hook to IC Hook Cables  IR Receiver Breakout DIP Sockets Solder Tail - 28-Pin 0.3 DIP Switch - 8 Position Hook-up Wire - White 74HC238 - 3 to 8 Line Decoder LED Display Driver (8-Digit) - MAX7219CNG Jumper Wire - Female to Female Connector 2x5 Pin IDC Ribbon Cable AVR Programming Cable Jumper Wire Kit Jumper Wires Premium 6 Button Pad 4x4 - LED Compatible LED Matrix - Serial Interface - Red/Green/Blue Arduino Mega Arduino Main Board Button Pad Controller SPI Super Bright LED - White - 1pcs Super Bright LED - Yellow - 1pcs Super Bright LED - Green - 1pcs Infrared LED - 950nm Triple Output LED RGB - Diffused - 100pcs Super Bright LED - Red - 1pcs Infrared LED - 850nm Super Bright LED - Blue - 1pcs XBee Explorer Regulated

Comments Off

Simple multiplexing with two shift registers

Comments Off

There are many ways to drive multiple LEDs, which in sum would require more IO pins and more current than is available on the control chip. The simplest way is perhaps multiplexing, and in this example I’ve used two 8 bits serial-in/parallel-out shift registers to achieve that. I’ll skip the theory for now, but I think the structure and layout of the LED matrix is worth highlighting.

Below the 64 LEDs are shown in a grid of 8 columns and 8 rows. To light a specific LED, there has to be a potential difference between its two pins, thus the pin connected to a column should be set HIGH, and the other row pin to LOW. To individually control all the LEDs, the active row is cycled very quickly. For each step of the cycle, the specific LEDs of that row is set, and then changed for the next row. If done quickly enough (typically at least 50 times per second; 50 Hz), it will appear as if all the LEDs are always on.

The example in the figure shows register A set to 0000 0011, for the two right-most LEDs. Register B is set to 1011 1111, thus activating the second row from the top. In theory, the settings of the two registers could have been reversed, and then the two bottom LEDs of the second column had been lit. However, since LEDs are directional, and does not let current through when the polarity is reversed, this is not possible (at least not with the simple diagram shown below).

Please note that the drawing glosses over a few details: First, the pin-placements of the chips are not as per specification; the right most pin, in case of register A and top for B, are in fact ground. Pin 0, for the first bit of the register is actually on the opposite side (which is always rather annoying and confusing). See this post for details.. Secondly, there should be an array of resistors: one between each column line and chip A (see this picture as an example). Finally, although it is possible to drive the LEDs from the Arduino, as seen in the pictures further down, external power will improve brightness, thus a set of resistors would also be required.

8x8 LED matrix with two shift registers

Once the LED side of the registers are hooked up, there are a few wires to connect to the Arudino: Each shift register needs at least its data-in, clock and latch pins connected (plus pins which need high or ground). The data pin sets the next bit to be pushed onto the register. The clock pin does one shift on its transition to HIGH. Finally, the latch pin copies the content of the internal shift register onto the externally visible storage register. See Mike Szczys’s video for details on how this works.

There are a few ways these three wires from each register can be hooked up. One way, as seen in the pictures and code below, is to connect each data, clock, and latch pin separately, for a total of six IO pins on the Arduino. It is also possible to sync the latch of both registers, thus combining both of these pins onto a single IO pin. The code below could have benefited from this optimization (see the comments in the code). Secondly, it is possible to sync both latch and clock pins of both registers, and shift out two bits in parallel. In code, this would thus only required a single for-loop, however, an extra call to digitalWrite() (for the second data bit) would be required. I’ve not measured what difference this makes, so any insight here is welcome. Finally, it would be possible to daisy chain the two shift registers together. This would only require three IO pins, however would waste a lot of time shifting redundant bits onto the second shift register.

// Code under GPL; please see full file for details.

// Digital pins for two independent shift registers.
const int dataA =  5;
const int latchA = 6;
const int clockA = 7;

const int dataB =  8;
const int latchB = 9;
const int clockB = 10;

const int outputPinCount = 6;
const int outputPins[outputPinCount] = {
  dataA, clockA, latchA, dataB, clockB, latchB};

// Frame buffer
const int lights = 64;
int buf[lights];

void setupPins() {
  for (int i = 0; i < outputPinCount; i++) {
    pinMode(outputPins[i], OUTPUT);

void setup() {


void loop() {

void clearAll() {

void setAll(int v) {
  for (int i = 0; i < lights; i++) {
    buf[i] = v;

void display() {
  for(int grp = 0; grp < 8; grp++) {
    digitalWrite(latchB, LOW);

    // Writes a single bit to the B register.
    // 0 means that group is active / on, 1 means off.
    // At the beginning of the loop, one 0 is shifted
    // onto the first bit, and later shifted upwards
    // as 1s turn the previous groups off.
    digitalWrite(clockB, LOW);
    digitalWrite(dataB, grp == 0 ? 0 : 1);
    digitalWrite(clockB, HIGH);
    digitalWrite(latchA, LOW);

    // Depending on the arrangement of the LEDs, and which
    // bits are conceptually most/least significant, shift in
    // increasing or reverse order.
    for(int i = 7; i > -1; i--) {
      digitalWrite(clockA, LOW);

      int bit = buf[grp * 8 + i];
      digitalWrite(dataA, bit);

      digitalWrite(clockA, HIGH);

    // Here and above, both latches are set to the same
    // value at the same time, this could have been combined
    // onto the same IO pin.
    digitalWrite(latchA, HIGH);
    digitalWrite(latchB, HIGH);

In the pictures below, the LEDs are on a single line, rather than in a grid, however, the grouping seen above still applies. Furthermore, each LED in my project is dual colour, so there only 32 of them, but still 64 pins to control. On my LED "breakout board" I've added a double set of headers for each pin on each LED, so I can easily connect them in any combination. The 8 pin jumper-wires from this post really came in handy.

For my custom dual shift register breakout board, I used this 4 x 6 cm PCB, and made the pins I needed available through headers. Please note that I made a mistake when placing the output headers, and for some reason assumed the pin on the opposite side was Q8 or QH, rather than 0 / A. On the shift register without resistors, I was able to correct this because there was room, however the other one was flush with the side, so it had to be corrected in the wiring (which makes some of the pictures below misleading). This board is somewhat similar to what you can buy pre-made from DealExtrme, however their version is using two daisy chained shift registers, and as mentioned, this will waste time when cycling the groups of LEDs.

Finally, note again that although it is possible to drive all this from the Arduino, even when powered over USB, better performance will be achieved with a higher powered external brick. Also, note that it is possible to mess up the code, so that all LEDs are turned on at the same time, and potentially draws more than 1 A. I shall not be held liable for what ever damage that might cause to hardware or people. Please see the license in the code for details.

First, some "making of" pictures, soldering all the LED pins and headers.

And here's the final product, well at least for now.

Comments Off

Large bright 10 mm LED

1 comment

Earlier this year, I found some uncommon LEDs at Clas Ohlson: Large bright 10mm LEDs (note that the link takes you to selection of different kinds; I got the “ultra white”). As seen from the pictures below, it is unusually large, compared to the 5mm LEDs which are most common. At 5000 mcd it is also very bright, and can easily be used as a flash light. Its forward voltage is 3.2 V, so with three AA batteries and a ~68 Ohm resistor, you’re all set.

I used a macro lens to take some of the pictures, and I found this one particularly interesting (make sure you zoom in 1:1). You can very clearly see the wire bond between the anvil and post. With most LEDs, this is usually too small to get a glimpse of. In this picture, you can get an idea of its cone. Like most LEDs, it is very directional, and thus flash-light idea.

Nexa Home Automation – 433 MHz codes

1 comment

After successfully decoding the Everflourish home automation controls, and integrating that with a DIY Android app, I thought it was time to expand the system. I picked up a new set of switches and remote, however, this was a different brand, Swedish Nexa, and thus a slightly different code. So, time do go through the RF decoding again, and adjust my RF remote source code.

I found two people working with this system, taking different approaches to controlling it from the Arudino. The author of the arduinocoder seems to interface through the remote, while Sebastian Nilsson had success with the HomeEasy project. I was tempted to use that code, however, as I was also interested in analysing the raw data, I brought out my DIY “oscilloscope” instead.

Since this home-made RF-to-audio device is something I thought I’d use in the future as well, I took the RF receiver off the breadboard, and soldered it onto a mini PCB, as seen in the pictures above. While working with RF components, I always find myself coming back to winavr’s and Dave Houston’s blog on how to wire this together. Unfortunately, the receiver was a bit more sensitive to the voltage level than I had expected, so taking 4.5 or 6 V from my power brick did not work. Instead, I used an Arduino, or a small 5V converter.

After this was done and plugged in, I found myself in Linux audio problems. Between two HDMI video cards, one external USB audio source, and the onboard audio port, it has gotten rather difficult to find the correct knob to turn to make sure the correct input is not muted, or too low. Here I found the application pavucontrol to very useful, as it clearly displays which devices and ports are available, and which applications output sound. (yum install pavucontrol). In Audacity, the input source was simply “default”, while recording in mono.
Remember to NOT stick any home made equipment into the microphone port; use line-in instead.

Part of the wire message from one of the buttons on the remote can be seen above. Compared to the Everflourish system, it looks a bit more dragged out and the edges are not so clear cut. There’s probably a few reasons for that: The resistors I used between the RF receiver and audio line were slightly different (this time 47k and 100k, vs. 100 Ohm and 1k in the previous). Also, the power source played a small role. Finally, the message is different, and in particular, the timings of wave is shorter; see below for details.

wire_bits=`cat $file | grep label.*title | cut -d '"' -f 6 | tr -d '\n' | sed "s/\([01]\{2\}\)/\1 /g"`
data_bits=`echo $wire_bits | sed "s/01/0/g" | sed "s/10/1/g"`
data_bytes_bin=`echo $data_bits | tr -d ' ' | sed "s/\([01]\{8\}\)/\1 /g"`
data_bytes_hex=`echo $data_bytes_bin | tr ' ' '\n' | while read b; do echo "obase=16; ibase=2; $b" | bc; done | tr '\n' ' '`
echo -e " $wire_bits \n $data_bits \n $data_bytes_bin \n $data_bytes_hex"

The snippet above extracts the labels from the Audacity XML project file and groups every wire bit, so the correspond to one data bit. A 01 on the wire is a 0, and a 10 is 1. This is a typical Manchester code. Next, the data bits are grouped into bytes, and finally expressed in hex. It then becomes clear how the message is structured: The 26 first (most significant) bits are a unique “house” or “remote control” code; the last four bits are the button ID; the 27th bit is a group flag, and the following (28th) is the the on/off bit. See also the documentation from the HomeEasy project below for further details.

01 01 10 01 01 01 10 10 10 10 10 10 01 01 10 10 10 10 10 01 10 10 01 10 10 01 01 10 01 01 01 10
0 0 1 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 0 1 1 0 1 1 0 0 1 0 0 0 1
00100011 11110011 11101101 10010001
23 F3 ED 91

The data is encoded on the wire (aerial) as a Manchester code.

A latch of 275us high, 2675us low is sent before the data.
There is a gap of 10ms between each message.

0 = holding the line high for 275us then low for 275us.
1 = holding the line high for 275us then low for 1225us.

The timings seem to vary quite noticeably between devices. HE300 devices have a
low for about 1300us for a 1 whereas HE303 devices seem to have a low of about
1100us. If this script does not detect your signals try relaxing the timing

Each actual bit of data is encoded as two bits on the wire as:
Data 0 = Wire 01
Data 1 = Wire 10

The actual message is 32 bits of data (64 wire bits):
bits 0-25: the group code – a 26bit number assigned to controllers.
bit 26: group flag
bit 27: on/off flag
bits 28-31: the device code – a 4bit number.

Once that was all clear, I just had to modify my transmitter code, which is connected over serial to my computer, and takes switch commands from my mobile phone. In the future, I will probably move to use an Ethernet shield, or possibly Bluetooth. There has been some problems with the connection to the Arudino, and also in sending the RF signals to the switches. In the new code, I’ve added quite a lot of extra redundancy, repeating the same command many times to makes sure it is received by the switch.

I’ve split the code into a library which can send commands to the Everflourish and Nexa systems, and the main sketch which takes commands from serial. There’s probably a few things to improve on, so feel free to send me comments or patches.

The code is released under GPL 3, or later version.

8 bits shift register – 17 bits of data

1 comment

Although the serial-in, parallel-out shift register, aka. SN74AHC595, SN74AHC594 or just “595″ / “594″, is an easy component to hook up and use, it might not be immediately obvious what’s going on inside the chip. At least it was not to me. Therefore I found Mike Szczys’s demonstration very enlightening. He shows how to drive the shift register manually, all without any micro-controller. The functional pins of the register is hooked up to buttons, so he can slowly go through the sequence of setting the data bit, clocking or shifting that onto the register, and then closing the latch to show the result on a line of LEDs.

Combined with the data sheet for the 595, it becomes more clear how the chip works: There are two separate registers on the chip; the visible storage register, and the internal shift register. When the latch (aka. “RCLK”, or “ST_CP”) goes high, the bits from the shift register is copied over to the storage register, and becomes visible on the external pins.

So that makes for 16 potentially different bits of information. However, as the title suggest, there’s one more available: It’s the output pin, typically used to daisy chain multiple shift register chips together. Even though it is part of the internal shift register, which thus consists of 9 bits, it is externally visible, and retains its state after the latch is closed. The drawing below shows this, with nine yellow external dots indicating visible bits, and eight blue dots indicating internal bits, for a total of 17 bits.

In the figure I’ve marked the QH’ as externally visible, even though it is part of the internal shift register. There probably aren’t many applications in which you’d use that as an active output, but one that comes to mind is a 3x3x3 LED cube. In a typical setup, you’d have three layers of 9 LEDs, for 12 wires altogether. Instead of controlling each LED in a layer individually, you could use a shift register, however you’d be one pin short (or 7 pins wasted if using two chips). So why not use the output pin for the 9th LED?

The programming would work as normally when addressing a shift register, but instead of shifting out 8 bits, you’d shift 9. The only problem would be that the 9th LED connected to the output pin would see the previous bits flying past as new bits are shifted onto the register. This might not be a big problem, as cycling the layers will probably be too fast to notice. If it is an issue, one could just disable all layers while bits are shifted out, and turn on only the relevant layer when done. I think this is a small experiment I’ll have to make, so stay tuned.

How to make an LED Cube


User “fruitkid101″ has a short and to-the-point video up on YouTube on how to construct a 3x3x3 LED cube, and drive it with an Arudino. What distinguishes his video from the hundreds of other LED cube videos out there, is that he explains step by step how to arrange the LEDs and route the wiring. Secondly, as it’s only three layers and nine columns, he needs no other components (save for resistors and three transistors), and all twelve wires are hooked directly up to the Arudino.

Another interesting and instructive video is Kevin Darrah’s on a 8x8x8 RGB cube. (Unfortunately, it wont show in HTML5 yet, but can be downloaded with the Video DownloadHelper Firefox plugin). He explains how to construct the towers which make up the cube, and also goes into detail on testing the LED and connections along the way. Much more work, of course, but also looks very cool.

Home automation with Arduino and Android

Comments Off

Last year I made the first progress towards a DIY remote for my home automation light switches (using the Everflourish RF based system). The goal was to use the 433.92 MHz radio transmitter and an Arduino to control the switches. Furthermore, the Arduino would receive control commands from my always-on computer, with Bash command line control (’cause that’s the way I like it). Finally, a custom Android app was developed as yet another option for remote control. The project is now fully operational, with a few adjustments here and there remaining. The figure below shows a high level overview.

From left to right, the mobile phones run Android apps which present a simple interface to control the lights. Each light can be turned on and off individually, or by some pre-sets (e.g. everything on or off, “good morning”, or “movie time”). The application has hard-wired the IP address of my always on server / PC on the local network. There is of course nothing stopping me from connection to a public IP (and port-forward), however, I don’t need away-from-home control at this point. The phone app simply sends a “light switch command” to the PC, which forwards it directly to the Arduino (see details below).

In this setup, the server is only a proxy, however, it could of course also be used to implement pre-programmed settings. E.g. daily rhythm commands when we’re away on holiday, or other automated functions. Since this box is also my PC, I can also send commands directly to the Arduino over serial /dev/tty; I have some convenience bash-scripts for that. For the phone app, it only does the forwarding on a hard-wired port:

while true; do nc -l 1234 > /dev/ttyUSB0; done

Maybe that bit could be improved in the future. Especially, since there are occasionally a few hiccups in the phone to PC communication. For example, the switch from 3G to local Wifi connection might be delayed as we enter the house, so commands will buffer up, and then suddenly sent en masse. Also, this would be a natural place to expand the system with pre-programmed actions. It should also be noted that to get this to work, I had to enable communication on the port 1234 both on the Wifi router, and the local server firewall.

Finally, the Arduino, connected via USB, accepts the incoming serial messages. The encoding is simple: A two digit code where the first digit is the index of the light, and the second is 0 or 1 for off or on (see the loop() method in the source listing below). So, “11″ will turn on the first light, while “10203040″ turns off all four lights. (Note that in the code below, to make things clearer for myself, index 0 is skipped).

The code below is all there is the the Arduino part. It hard-codes the Everflourish messages and timings. It should be noted that the messages as found in the previous article, are most likely some form of Manchester code, as there are always pairs of 01 or 10. Thus, the hard-coded messages could have been shortened, but this would have added (a bit) to the complexity of the code, so I left it.

The main loop waits for incoming bytes on the serial USB connection, and sends the according light switch command to the RF transmitter on pin 2. Here there is probably also room for some improvements, to avoid illegal numbers, stuck states, etc. Once a valid code is received, the transmitted signal for that button is repeated four times, just as seen with the original remote control.

(Download source)

#define OUT_PIN 2

// Timings in micro seconds
#define SHORT_UP_0 567
#define LONG_UP_1 1134
#define DOWN_SPACE 680
#define UP_END 15000

const int PREAMBLE = {0x00};
const int OFF[] = {0x55};
const int ON[]  = {0xaa};

const int light_array[][5] = {
  // main
  {0x65, 0xa9, 0x46, 0x95, 0x67, },
  {0x65, 0xa9, 0x46, 0x96, 0x96, },
  {0x65, 0xa9, 0x46, 0x99, 0xa3, },
  {0x65, 0xa9, 0x46, 0x9a, 0x61, },

  // aux
  {0x65, 0xa9, 0x46, 0x95, 0xaa, },
  {0x65, 0xa9, 0x46, 0x96, 0x53, },
  {0x65, 0xa9, 0x46, 0x99, 0x62, },
  {0x65, 0xa9, 0x46, 0x9a, 0xa1, },

void setup() {

    pinMode(OUT_PIN, OUTPUT);

void loop() {
  if (Serial.available() > 1) {
     int light_id = - '0';
     int on = - '0';
     for(int i = 0; i < 5; i++) {     
        send(light_array[light_id], on);
 void send(const int *light_data, boolean on) {
   digitalWrite(OUT_PIN, LOW);
   send_bytes(PREAMBLE, 1, 4);
   send_bytes(light_data, 5, 8);
   send_bytes(on ? ON : OFF, 1, 8);
   digitalWrite(OUT_PIN, HIGH);
   digitalWrite(OUT_PIN, LOW);
   digitalWrite(OUT_PIN, HIGH);
 void send_bytes(const int *bytes, int len_bytes, int len_bits) {
   for(int b = 0; b < len_bytes; b++) {
     int data_byte = bytes[b];
     for(int i = len_bits - 1; i >= 0; i--) {
      digitalWrite(OUT_PIN, HIGH);
      digitalWrite(OUT_PIN, LOW);
      int data_bit = ((data_byte >> i) & 1);
      if (data_bit == 0) {
      } else {

Comments Off