Home Automation – Receiver

 Arduino, DIY, Electronics, Home Automation  Comments Off on Home Automation – Receiver
Aug 112015

I have made a couple of attempts over the past years to make a Home Automation Receiver with an Arduino Uno and a simple 433MHz receiver.
But so far I have failed, believing the Uno maybe wasn't fast enough for the task at hand.
By chance a colleague of mine stumbled upon my blog, and wondered if I did not have any such receiver at hand, since I had made transmitters way back in time.
I told him about my endeavors and my disbelief about the performance. Luckily he did not listen too much, and did some internet searching.
Of course there are sketches out there for the receiver task. After looking at some of them I decided to try to do one myself.
One major difference in my new sketch, compared to my older attempts, is the use of pulseIn(). Before I tried to sample with digitalRead()  but could never get a consistent result.
With pulseIn() we detect only the low part of the pulses, and by comparing the length of the low part, conclude what type of bit it was.

This is what the HW setup looks like.

Here is the sketch.

   Joakim Wesslen

   We detect data pulses by catching the low part of every pulse.   


More info at:  

Physical data structure (in air):
0        10        20        30        40        50           60
1234567890123456789012345678901234567890123456789012 34 56 7890 1234

Bits #01-52 -> TxCode (T)
Bits #53-54 -> Group (G)
Bits #55-56 -> On/Off (O)
Bits #57-60 -> ? Dimming/Channel ? (D)
Bits #61-64 -> Device Nbr (N)

Logical data structure:
0        10        20           30  
12345678901234567890123456 7 8 90 12

Bits #01-26 -> TxCode (T)
Bits #27 -> Group (G)
Bits #28 -> On/Off (O)
Bits #29-30 -> ? Dimming/Channel ? (D)
Bits #31-32 -> Device Nbr (N)


int rxPin = 12;

boolean debugOn = false;  // enable debug prints

int tPause = 0; // debugging
int tSync = 0; // debugging

unsigned long loopCounter = 0;  // stats
unsigned long dataCounter = 0;  // stats

// Setting limit boundaries
int pauseMinTime = 7000;
int pauseMaxTime = 14000;

int syncMinTime = 2100;
int syncMaxTime =  3200;
int oneMinTime = 70;
int oneMaxTime = 300;

int zeroMinTime = 1000;
int zeroMaxTime = 1900;

signed long timeout1 = 1000000;
signed long timeout2 = 100000;

#define MAX_STR 150

char bin[MAX_STR + 1];

// get a 'binary' 32 bit string from value
char *dec2binStr(unsigned long ul)
 int len = sizeof(ul) * 8;
  int c, d;
  int count = 0;

  memset(bin, len, '0');

  for (c = len-1 ; c >= 0 ; c-- )
    d = ul >> c;

    if ( d & 1 )
       bin[count] = '1';
       bin[count] = '0';
  bin[len] = '\n';
  return bin;

// log function
void ilog(const char *fmt, ...)
  char tmpStr[MAX_STR + 1];
  va_list ap;

  va_start(ap, fmt);
  vsnprintf(tmpStr, MAX_STR + 1, fmt, ap);

// debug log function
void dlog(const char *fmt, ...)
  if (debugOn) 
    char tmpStr[MAX_STR + 1];
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(tmpStr, MAX_STR + 1, fmt, ap);

char binPhy[MAX_STR + 1];

// get a 'binary' 64 bit string from value
char *dec2binPhyStr(unsigned long ul)
 int len = sizeof(ul) * 8;
  int c, d;
  int count = 0;

  memset(binPhy, MAX_STR, '0');

  for (c = len-1 ; c >= 0 ; c-- )
    d = ul >> c;

    if ( d & 1 )
       binPhy[count] = '1';
       binPhy[count+1] = '0';
       binPhy[count] = '0';
       binPhy[count+1] = '1';
    count += 2;
  binPhy[len*2] = '\n';
  return binPhy;

// debug statistics printout
void printStats(unsigned long loopCnt, unsigned long dataCnt)
  ilog("Loops: %d, Packets: %d", loopCnt, dataCnt);

// print decoded receiver data
void printPacketData(unsigned long data)
  ilog("Received: %s", dec2binStr(data));
//  ilog("ReceivedPhy: %s", dec2binPhyStr(data));

// receiver for home automation data
void dataReceiver(void)
  dlog("--- Wait for Pause and Sync ---");

  int i = 0;
  signed long t = 0;
  byte prevBit = 0;
  byte currBit = 0;
  // Packet data, logical structure
  unsigned long dataPacket = 0;

  // Wait for Pause bit (10500 us).
  while ((t < pauseMinTime) || (t > pauseMaxTime))
    t = pulseIn(rxPin, LOW, timeout1);
  tPause = t; // Save timing for debugging purposes
  if (t == 0)
    dlog("!!! - Pause Timeout - Start over.");
    goto start_over;

  // Wait for Sync bit (2750 us).
  while ((t < syncMinTime) || (t > syncMaxTime))
    t = pulseIn(rxPin, LOW, timeout1);
  tSync = t; // Save timing for debugging purposes
  if (t == 0)
    dlog("!!! - Sync Timeout - Start over.");
    goto start_over;

  // data collection loop
  while (i < 64)
    t = pulseIn(rxPin, LOW, timeout2);  // shorter timeout?
    if (t == 0)
      dlog("!!! - Data Timeout - Start over.");
      goto start_over;
    else if (t > zeroMinTime && t < zeroMaxTime)
      currBit = 0;
    else if (t > oneMinTime && t < oneMaxTime)
      currBit = 1;
      dlog("Incorrect data - Start over. t=%d", t);
      goto start_over;

    if (i % 2 == 1)
      if ((prevBit ^ currBit) == 0)
        // must be either 01 or 10, not allowed to be 00 or 11
        dlog("Bad data - Start over");
        goto start_over;
      // Store packet bits
      dataPacket <<= 1;
      dataPacket |= prevBit;
     prevBit = currBit;
   if (i > 0)

void setup()
  pinMode(rxPin, INPUT);
  ilog("Home Automation Receiver");

void loop()

Next, I shall try and make this into a library.

Micro Python

 DIY, Electronics, Python  Comments Off on Micro Python
May 182014

Received my Micro Python board on the 12th of May which is a Kickstarter project I supported back in November last year, https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers.

I just backed the project as I thought it was an interesting idea to use python in an embedded product.
So far I haven't had time to play around with it much, but I am really looking forward to it.

Here is the official web site for the project, http://micropython.org/.

board and box

One thing I noticed though upon starting the device up is that, at least on my Ubuntu machine, I did not get the pop-up window of the pyboard drive as described in the tutorial, if I have the SD-card inserted. If the SD-card is inserted, the only thing I get is the USB drive of that card. Without the SD-card inserted, I get the pyboard drive with the files mentioned. So I will go on without the card for now.

The tutorial, http://micropython.org/doc/tut-contents, is really nice and easy to follow.

To get a micro python prompt to write instructions directly to the board do,

screen /dev/ttyACM0

This is what you get from the help() function on micro python interpreter.

>>> help()         
Welcome to Micro Python!

For online help please visit http://micropython.org/help/.

Quick overview of commands for the board:
  pyb.info()    -- print some general information
  pyb.gc()      -- run the garbage collector
  pyb.delay(n)  -- wait for n milliseconds
  pyb.Switch()  -- create a switch object
                   Switch methods: (), callback(f)
  pyb.LED(n)    -- create an LED object for LED n (n=1,2,3,4)
                   LED methods: on(), off(), toggle(), intensity()
  pyb.Pin(pin)  -- get a pin, eg pyb.Pin('X1')
  pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p
                   Pin methods: init(..), value([v]), high(), low()
  pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object
  pyb.ADC(pin)  -- make an analog object from a pin
                   ADC methods: read(), read_timed(buf, freq)
  pyb.DAC(port) -- make a DAC object
                   DAC methods: triangle(freq), write(n), write_timed(buf, freq)
  pyb.RTC()     -- make an RTC object; methods: datetime([val])
  pyb.rng()     -- get a 30-bit hardware random number
  pyb.Servo(n)  -- create Servo object for servo n (n=1,2,3,4)
                   Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])
  pyb.Accel()   -- create an Accelerometer object
                   Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()

Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name
Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD
Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN
Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)

Control commands:
  CTRL-A        -- on a blank line, enter raw REPL mode
  CTRL-B        -- on a blank line, enter normal REPL mode
  CTRL-C        -- interrupt a running program
  CTRL-D        -- on a blank line, do a soft reset of the board

For further help on a specific object, type help(obj)

To close the screen session do 'Ctrl + a' and 'Ctrl + d' in sequence.

As I said before, really looking forward to digging deeper into what I can do with this board.

Home Automation – RF Protocol, update.

 DIY, Electronics, Home Automation  Comments Off on Home Automation – RF Protocol, update.
May 012014

Since I wrote the posts on 'Home Automation RF Protocols for simple devices' back in 2012, I have received some questions and feedback, which I find very enjoyable. Unfortunately I have had to turn off the comment options, as I have also received a lot of spam. Still people who really want to, have managed to find my email address (in the 'About Me' page). Some of the questions was on devices which I haven't made the decoding of myself. This made me quite curious, so I went and bought some of these devices.

Now I have three different makers of simple devices, namely Proove from 'Kjell & Company', Anslut from 'Jula', and Nexa which is a wellknown brand not belonging to a special franchise but can be found almost anywhere.

Starting with the 'Anslut' devices, it is really similar to the Proove one when just looking at them. Here is a picture of the transmitters, with Proove to the left and Anslut to the right.



Opening the Anslut transmitter the PCB is also identical to Proove, but checking the IC, it was not the same as in my Proove transmitter.
This one was labeled,
But after some searching on the internet it seems to be made by Holtek too.
I would imagine it is just another version of their '8-Bit OTP MCU with RF Transmitter' line-up of IC:s.
The Xtal is marked 13.560 MHz, which is 1/32nd of 433.92 MHz.

The pin-out of the IC is identical to the one on the Proove device

 Vcc  9-|       |-8 Vcc
     10-|       |-7
     11-|       |-6
 Vcc 12-|       |-5 SW4
 SW8 13-|       |-4 SW3
 SW7 14-|       |-3 SW2
 SW6 15-|       |-2 SW1
 SW5 16-|      o|-1 Dout

As everything is so similar between these devices, I strongly suspect the decoded data to also be very similar.
This time around I have a digital logic analyzer to decode the data transmitted on the Dout pin.

To my surprise I see a packet burst consisting of SIX packets, and not four as I saw last time. Of course this is most likely due to measurement tool limitations, as I used a USB oscilloscope last time, and it might not have had the bandwidth/capacity to capture all of the data. Anyway, this is what it looks like with the logic analyzer.



Zooming in a bit on the packet burst.


Zooming in on one packet to decode bits.


Defining the pulses.
High 250 us, low about 2750 us  -> Sync
High 250 us, low about 1500 us. -> Zero (0)
High 250 us, low 250 us. -> One (1)
Last bit.
High 250 us, low 10500 us. -> Pause
A packet consist of, Sync + Data + Pause.

Decoding 'Data part' of a packet.

0        10        20        30        40        50           60
1234567890123456789012345678901234567890123456789012 34 56 7890 1234

Bits #01-52 -> TxCode (T)
Bits #53-54 -> Group (G)
Bits #55-56 -> On/Off (O)
Bits #57-60 -> ? Dimming/Channel ? (D)
Bits #61-64 -> Device Nbr (N)

As every other bit sent over the air is redundant, it is the inverse of the previous bit, the packet consist of 32 logical bits

Going back to my Proove tranmitter, and hooking it up to the digital logic analyzer, it also shows a packet burst consisting of six packets. All of the decoding is the same as for the Anslut device.
Defining the pulses.
High 250 us, low about 2500 us  -> Sync
High 250 us, low about 1250 us. -> Zero (0)
High 250 us, low 250 us. -> One (1)
High 250 us, low 10000 us. -> Pause

Time to check the Nexa device. Note this is the simple version, and cheap, of their devices.

First I open up the transmitter, and can immediately see that it is completely different to the other ones.


This is how the other side of the pcb looks like.


The component on the frontside marked 'H R4334' at position SAW101, is a SAW filter with three pins.
1 - Input
2 - Output
3 - GND

Debuging the IC, which has no markings on it, on the backside gives.

 5 -|        |- 4 
 6 -|        |- 3 
 7 -|        |- 2 
 8 -|       o|- 1

Using the oscilloscope to have a look at the signals.	 
1 - 3.8 V
2 - Dout, Pulse train when pressing button
3 - 
4 - 3.8 V noisy
5 - < 1 V rippled
6 - same as 5
7 - same as 5
8 - GND

So, we seem to have a Dout pin here too. Time to hook up that analyzer again.

This is what a packet burst looks like. Note, only five packets in the burst.

Zooming in a bit on that burst.


Finally here is how a packet looks like.


Data part time decoded:
High 250 us, low 2750 us -> Sync
High 250 us, low 250 us -> one
High 250 us, low 1250 us -> zero
High 250 us, low 10000 us -> Pause

This is exactly the same as the Proove device timing, and as expected the data part of the packet is also the same as the Anslut and Proove devices.

With this new knowledge, I have decided to update/change my 'Home Automation, RF Protocols' page to reflect my new findings, and to only have device data which I have decoded myself.

I have also updated the Arduino library that I made some years ago. Since there are some differencies between Proove/Anslut and Nexa, such as the channel code and the way to number unit 1 to 3, I made two librabries: Proove/Anslut and Nexa.

Arduino with Relay module

 Arduino, DIY, Electronics  Comments Off on Arduino with Relay module
Nov 022013

Got myself a relay module the other day, as I wanted to use an actuator, and the current supplied from the Arduino itself was not enough to make it work.

This is what I got, http://www.kjell.com/sortiment/el/elektronik/mikrokontroller/arduino/relamodul-for-arduino-p87878.

Here is how I connected the 'Songle SRD-05VDC-SL-C' relay with an actuator to an Arduino.

The pin marked:
'+'  connected to 5V from Arduino
'- ' connected to GND from Arduino
'S' connected to GPIO#2 from Arduino

In the other end connect the middle connector ('Common') to an external voltage source,
in my case 5V, as the actuator was a 5V actuator. The NO ('Normally Open') connector is strapped to one of the actuators input. The NC ('Normally Closed') connector is not used. The other actuator pin is connected to the external power sources GND completing the circuit.

When the GPIO#2 is put high, the external 5V source is fed to the actuator, making it move.
So the only thing you need in your Arduino sketch is 'digitalWrite' of the proper GPIO.
It took me some time to figure the relay out, since I watched some instruction on the internet on how to connect a relay, and all of them used some external diodes and transistors.
But that is not necessary with this one, as it is already mounted on the PCB of the relay module.

ASCII art of the setup:

Arduino |      -----------------
        |      |               |
        |      |     Relay     | 
   5V  --- + --|               |-- NC
        |      |     module    |
   GND --- - --|               |-- Common ---------------- 5V external src
        |      |               | 
GPIO#2 --- S --|               |-- NO -----|
        |      |               |           |       ------- GND external src
        |      |               |           |       |
        |      -----------------           |       |
---------                                  |       |
                                           |       |
                                         |            |
                                       ==|  Actuator  |=====|
                                         |            |

The vendor data sheet of the module, http://www.songle.com/en/pdf/20084141716341001.pdf