August 23, 2011

Manchester encoding/decoding in LibHiJack

The hijack iPhone library implements Manchester encoding for digital communication.  Manchester encoding maps 0 to high-low transition, and 1 to low-high transition.

The iPhone library generates the transitions using full or half period of a sine wave, using a full period when a bit run is detected. An example of this is shown below.

Manchester encoding of 0110011101 by libHiJack

Detection of Manchester encoding is relatively simple: first the signal is regenerated into a square wave by setting all values above 0 to 1 and 0 otherwise. The number of samples between transitions (0 to 1 or 1 to 0) is then measured. When this interval is within an acceptable range (as determined by the baud rate) the bit is read simply by taking the value of the regenerated square wave immediately after the transition. This works out nicely because 1 maps to a low-high transition, and the value immediately after transition is 1, while 0 maps to high-low transition, and the value immediately after transition is 0.

The important thing to note is that detection of a bit occurs at the transition from one bit to the next, and the code ignores transitions during a bit period. Specifically a transition must occur between 3/4 and 3/2 bit periods from last bit detection, otherwise it is ignored.

For example the transition between sample 64 and 96 is ignored because it occurs 1/2 a bit period since the last bit detection at sample 64.

Finally, the UART frame used consists of a start bit, eight data bits, one parity bits and one stop bit. Note my example doesn't include the parity bit since I reimplemented the encoding algorithm in python to produce the graph.