0% found this document useful (0 votes)
59 views32 pages

Modular Mid-Range Picmicro K L Decoder in C: Ee Oq

Uploaded by

ognarf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views32 pages

Modular Mid-Range Picmicro K L Decoder in C: Ee Oq

Uploaded by

ognarf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

AN745

Modular Mid-Range PICmicro® KEELOQ® Decoder in C


OVERVIEW FIGURE 1: DECODER PIN OUT
This application note describes a KEELOQ code hop- MCLR 1 28 NU
ping decoder implemented on a Microchip Mid-range LRNOUT 2 NU
27
Enhanced FLASH MCU (PIC16F872). The software
RFIN 3 26 VLOW
has been designed as a group of independent modules
(standard C source files "C" ). NU 4 25 LEARNOUT
NU 5 24 OUT3
For clarity and ease of maintenance, each module cov-
ers a single function. Each module can be modified to LEARN 6 23 OUT2
accommodate a different behavior, support a different NU 7 22 OUT1
MCU, and/or a different set of peripherals (memories, VSS OUT0
8 21
timers, etc.).
OSCIN 9 20 VDD
KEY FEATURES OSCOUT 10 19 VSS

NU 11 18 NU
The set of modules presented in this application note
implement the following features: NU 12 17 NU
NU 13 16 NU
• Source compatible with HITECH and CCS C
compilers NU 14 15 NU
• Pin out compatible with PICDEM-2 board
• Normal Learn mode
TABLE 1: FUNCTIONAL INPUTS AND
• Learn up to 8 transmitters, using the internal OUTPUTS
EEPROM memory of PIC16F872
• Interrupt driven Radio Receive (PWM) routine Pin Pin Input/
Function
• Compatible with all existing KEELOQ hopping code Name Number Output
encoders with PWM transmission format RFIN 3 I Demodulated
selected, operating in "slow mode" (TE = 400 µs) PWM signal from
• Automatic synchronization during receive, using a RF receiver
4 MHz RC oscillator
LEARN 6 I Input to enter learn
mode
LEARN- 25 O Output to show the
OUT status of the learn
process
OUT0..3 21,22,2 O Function outputs,
3, 24 correspond to
encoder input pin
VLOW 26 O Low Battery indica-
tor, as transmitted
by the encoder
VDD 20 PWR 5V power supply
VSS 19, 8 GND Common ground
Note: All NU pins are tristate

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 1


AN745
DESIGN OBJECTIVES Although the code can be compiled in a set of indepen-
dent object files and then linked together to build the
Each module has been designed for maximum simplic- actual application, we kept all the modules included in
ity and maintainability. Whenever possible, we favored line with the main module to retain compatibility with
clarity of design over efficiency in order to show the compilers that have no linker such as CCS PIC C.
basic concepts of the design of a KEELOQ decoder with-
out the constraints of previous PIC16C5X implementa-
MODULES OVERVIEW
tions such as limited RAM, STACK, or other resources.
To achieve maximum ease in maintenance, we The code presented in this application note is com-
adopted "modern" C language programming tech- posed of the following basic modules:
niques, specifically: RXI.C interrupt driven receiver
• All pin assignments are mapped through KEYGEN.C KEELOQ key generation routines imple-
#define directives. This results in almost com- menting Normal Mode
plete code independence from the specific pin out
FASTDEC.C KEELOQ decrypt routine
chosen
• Drivers to peripherals that are specific to a given MEM-87X.C PIC16F87X EEPROM driver
processor type (such as PIC16F872) have been TABLE.C transmitters table memory manage-
encapsulated in more generic modules ment (linear list)
• Function input and output values are documented MAIN.C the actual initialization and main loop
• Pseudo-graphical representation of the data
structures used and program flow is commented
whenever possible

FIGURE 2: MODULES OVERVIEW

Timer0
RXI.C Interrupt
Radio Receiver

1st Buffer X

RF_FULL
Flag
MEM-87X.C
Learn Receive Buffer
TABLE.C
Out S0
MAIN.C - Insert
Out S3 - Search
Main Loop
Learnout - IDwrite EEPROM
- HopUpdate
VLOW - ClearMem

- RDword
- WRWord
KEYGEN.C
- Normal KEYGEN
- Load Manufacturer Code
- DecCHK
- HopCHK

FASTDEC.C
- Decrypt

KEELOQ®

PIC16F872

DS00745A_C-page 2 Confidential  2001 Microchip Technology Inc.


AN745
RECEIVER MODULE with the first rising edge of every bit in the incoming
code word. This allows the decoder to operate from an
The receiver module has been developed around a fast inexpensive (uncalibrated) RC clock. In doing so, the
and independent Interrupt Service Routine (ISR). The last rising edge/bit of every code word is lost (resulting
whole receiving routine is implemented as a simple in an effective receive buffer capacity of 65-bit).
state machine that operates on a fixed time base. This
can be used to produce a number of virtual timers. The For HCS20X and HCS30X encoders this implies that
operation of this routine is completely transparent to the REPEAT bit (being the 66th) cannot be captured.
the main program and similar to a UART. In fact, the While for Advanced Encoders like the HCS36X or
interrupt routine consumes only 30% of the computa- HCS4XX, the reader can easily modify the definition of
tional power of the MCU working in the background . the constant BIT_NUM to 68 to receive all bits trans-
mitted with exception of the last queue bit Q1 (being the
After a complete code word of 66 bits has been prop- 69th), again rarely used.
erly received and stored in a 9 bytes buffer, a status flag
(RF_FULL) is set and the receiver becomes idle. The only resource/peripheral used by this routine is
Timer0 and the associated Overflow Interrupt. This is
It is the responsibility of the main program to make use available on every mid-range PICmicro MCU. Timer0 is
of the data in the buffer and to clear the flag to enable reloaded on overflow, creating a time base (of about
the receiving of a new code word. 1/3 TE = 138 µs). The same interrupt service routine
In order to be compatible with all KEELOQ encoders, also provides a virtual 16-bit timer, derived from the
with or without oscillator tuning capabilities, the same base period, called XTMR.
receiver routine constantly attempts to resynchronize

FIGURE 3: CODE WORD TRANSMISSION FORMAT


TE

LOGIC ‘0’

LOGIC ‘1’

Bit
Period

Encrypted Portion Fixed Portion of Guard


Preamble Header of Transmission Transmission Time
TP TH THOP TFIX TG

FIGURE 4: CODE WORD ORGANIZATION


Fixed Code Data Encrypted Code Data

VLOW and Button Button Overflow Discrimination


Repeat Status Status 28-bit Serial Number Status bits bits 16-bit
(2 bits) (4 bits) (4 bits) (2 bits) (10 bits) Sync Value

Encrypted using
BLOCK CIPHER Algorithm

Serial Number and Button


2 bits
of Status + Status (32 bits) + 32 bits of Encrypted Data

Transmission Direction

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 3


AN745
Since the radio input is polled (for 1 µs) on multiples of Due to double buffering of the receiver and the
the base period (138 µs), the chance of a glitch (short PICmicro MCU execution speed and efficiency (even
noise pulse) disturbing the receiver is reduced. running at 4 MHz only), it is possible to receive and
Further, since the time base produced is constant, the decrypt, at the same time, each and every incoming
same interrupt service routine could easily be extended code word.
to implement a second UART as a separate state For an overview of some of the different security levels
machine for full duplex asynchronous communication that can be obtained through the use of different key
up to 1,200 baud at 4 MHz. generation/management schemes, refer to the "Secure
Note: This would also require the main oscillator Data Products Handbook" [DS40168] (Section 1,
to be crystal based. KEELOQ Comparison Chart, Security Level Summary).

Other implementations of the same receiver module A detailed description of the Normal Learn key gener-
can be obtained using other peripherals and detection ation scheme can be found in Technical Brief TB003
techniques. These include: "An Introduction To KEELOQ Code Hopping"
[DS91002].
• Using the INT pin and selectable edge interrupt
source More advanced Key Generation Schemes can be
implemented replacing this module with the techniques
• Using the Timer1 and CCP module in capture
described in Technical Brief TB001 "Secure Learning
mode
RKE Systems Using KEELOQ Encoders" [DS91000].
• Using comparator inputs interrupt
All of these techniques pose different constraints on the TABLE MODULE
pin out, or the PICmicro MCU, that can be used. This
One of the major tasks of a decoder is to properly main-
would lead to different performances in terms of
tain a database that contains all the unique ID’s (serial
achievable immunity from noise and or CPU overhead,
numbers) of the learned transmitters. In most cases,
etc.
the database can be as simple as a single table, which
associates those serial numbers to the synchronization
FAST DECRYPTION MODULE
counters (that are at the heart of the hopping code
This module contains an implementation of the KEELOQ technology).
decryption algorithm that has been optimized for speed This module implements the easiest of all methods, a
on a mid-range PICmicro microcontroller. It allows fast simple "linear list" of records.
decryption times for maximum responsiveness of the
system even at 4 MHz clock. Each transmitter learned is assigned a record of 8
bytes (shown in Table 2), where all the relevant infor-
The decryption function is also used in all learning mation is stored and regularly updated.
schemes and represents the fundamental building
block of all KEELOQ decoders.
TABLE 2: TRANSMITTER RECORD
KEY GENERATION MODULE Offset Data Description
This module shows a simple and linear implementation +0 FCODE Function code (4 bits) and
of the Normal Learn Key Generation . upper 4 Serial Number bits
This module uses the KEELOQ Decrypt routine from the [24..28]
Fast Decryption module to generate the key at every +1 IDLo Serial Number bits [0..7]
received code word instead of generating it during the
+2 IDHi Serial Number bits [8..15]
learn phase and storing it in memory. The advantage is
a smaller Transmitter Record of 8 bytes instead of 16 +3 IDMi Serial Number bits [16..23]
bytes (see Table 2). This translates in a double number +4 SYNCH Sync Counter 8 MSB
of transmitters that can be learned using the 64 byte
internal EEPROM available inside the PIC16F872. +5 SYNCL Sync Counter 8 LSB
This space reduction comes at the expense of more +6 SYNCH2 Second copy of SYNCH
computational power required to process every code +7 Second copy of SYNCL
SYNCL2
word. When a new code word is received, the key gen-
eration algorithm is applied (Normal Learn) and the
resulting Description key is placed in the array
DKEY[0..7]. During a continous transmission (the
user is holding the button on the transmitter), the key
generation is not repeated, to save time, the last com-
puted Decryption Key value is used safely instead (the
serial number being the same).

DS00745A_C-page 4 Confidential  2001 Microchip Technology Inc.


AN745
The 16-bit synchronization counter value is stored in THE MAIN PROGRAM
memory twice because it is the most valuable piece of
information in this record. It is continuously updated at The main program is reduced to a few pages of code.
every button press on the remote. When reading the The behavior is designed to mimic the basic behavior
two stored synchronous values, the decoder should of the HCS512 integrated decoder, although just the
verify that the two copies match. If not, it can adopt any parallel output is provided (no serial interface).
safe resync or disable technique required depending Most of the time, the main loop goes idle waiting for the
on the desired system security level . receiver to complete reception a full code word.
The current implementation limits the maximum num- Double buffering of the receiver is done in RAM, in
ber of transmitters that can be learned to eight. This is order to immediately re-enable the reception of new
due to the size of the internal EEPROM of the codes and increase responsiveness and perceived
PIC16F872. range.
This number can be changed to accommodate different
PICmicro models and memory sizes by modifying the CONCLUSION
value of the constant MAX_USER.
The C language source increases the readability of the
The simple "linear list" method employed can be scaled program structure and eases the maintenance. This
up to some tens of users. But due to its simplicity, the benefit has come at the cost of the program size. That
time required to recognize a learned transmitter grows in terms of memory words, has considerably increased
linearly with the length of the table. over the equivalent code written in assembly (more
It is possible to reach table sizes of thousands of trans- than 30% larger).
mitters by replacing this module with another module Selecting a FLASH PICmicro microcontroller from the
that implements a more sophisticated data structure mid-range family as the target MCU allows us to make
like a “Hash Table” or other indexing algorithms. the code simpler and cleaner. It also provides larger
Again due to the simplicity of the current solution, it is RAM memory space and a deeper hardware stack.
not possible to selectively delete a transmitter from Interrupts have been used to "virtualize" the receiving
memory. The only delete function available is a Bulk routine as a software peripheral and to free the design
Erase (complete erase of all the memory contents) that of the hard real time constraint that it usually poses.
happens when the user presses the Learn button for up Still, many of the resources available on the
to 10 seconds. (The LED will switch off. At the release PIC16F872 are left unused and available to the
of the button, it will flash once to acknowledge the designer. These include:
delete command). To allow for selective transmitter • Timer1, a 16-bit timer
removal from memory, more sophisticated techniques • Timer1 oscillator, a low power oscillator for real
will be analyzed in future application notes, by simply time clock
replacing/updating this module.
• CCP module, capable of capture, compare and
PWM generation
MEM-87X MODULE
• Timer2, an 8-bit timer, with auto reload
This module is optimized to drive the internal EEPROM • 10-bit A/D converter with a 5 channel input
of the PIC16F87X device. multiplexer
The module make the memory generically accessible We resisted introducing extra features and optimiza-
by means of two routines RDword and WRword that tions in favor of clarity. For example:
respectively read and write a 16-bit value out of an
even address specified in parameter IND. • Speed optimizations and code compacting
• More complex key generation schemes
Replacing this module with the appropriate drivers,
(and adapting the pin out) make possible the use of any • Multiple manufacturer codes
kind of nonvolatile memory. This includes internal and • Co-processor functionality
external serial EEPROMs (Microwire®, SPI™ or I2C™ • Advanced user entry and deletion commands
bus) of any size up to 64 Kbytes. • Large memory tables (up to 8,000 users)
• Serial interface to PDAs and/or terminals for
memory management and logging
These are left as exercises to the advanced reader/
designer or as suggestions for further application
notes.

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 5


AN745
MEMORY USAGE FUNCTION REFERENCES
HEADERS
Compiling with HITECH 7.86r3 KEELOQ Code Hopping AN642 DS00642
Decoder on a PIC16C56
Memory Usage Map: Converting NTQ105/106 AN644 DS00644
Designs to HCS200/300s
Program ROM $0000 - $00A8 $00A9 ( 169) words
Program ROM $04Af - $07FF $0351 ( 849) words Code Hopping Security AN645 DS00645
System on a PIC16C57
Program ROM $2000 - $2005 $0006 ( 6) words
Secure Learn Code Hopping AN652 DS00652
Program ROM $2007 - $2007 $0001 ( 1) words
Decoder on a PIC16C56
$0401 ( 1025) words
KEELOQ Simple Code Hopping AN659 DS00659
total Program
Decoder
ROM
Bank 0 RAM $0021 - $006D $004D ( 77) bytes KEELOQ Code Hopping AN661 DS00661
Decoder on a PIC16C56
Bank 0 RAM $0070 - $0074 $0005 ( 5) bytes
(public version)
$0052 ( 82) bytes
Secure Learn Code Hopping AN662 DS00662
total Bank 0
Decoder on a PIC16C56
RAM
(public version)
Bank 0 Bits $0100 - $0105 $0006 ( 6) bits
total Bank 0 KEELOQ Simple Code Hopping AN663 DS00663
bits Decoder (public version)
Using KEELOQ to Generate AN665 DS00665
Hopping Passwords
PICmicro Mid-Range MCU AN662 DS00672
CCS PCW C Compiler, Version 2.535, Code Hopping Decoder
4511 HCS410 Transponder Decoder AN675 DS00675
using a PIC16C56
Filename: D:\WORK\SMAD\AN\DECC\MAIN.LST
Modular PICmicro Mid-Range AN742 DS00742
ROM used: 1155 (28%) MCU Code Hopping Decoder
1155 (28%) including unused fragments
Secure Learning RKE Systems TB001 DS91000
RAM used: 71 (37%) at main () level Using KEELOQ Encoders
84 (44%) worst case
An Introduction to KEELOQ TB003 DS91002
Stack: 4 worst case (3 in main +1 for interrupts) Code Hopping
A Guide to Designing for TB021 DS91021
EuroHomelink Compatibility
KEELOQ Decryption & IFF TB030 DS91030
Algorithms
KEELOQ Decryption Routines in TB041 DS91041
C
Interfacing a KEELOQ Encoder TB042 DS91042
to a PLL Circuit
KEELOQ CRC Verification Rou- TB043 DS91043
tines

DS00745A_C-page 6 Confidential  2001 Microchip Technology Inc.


AN745

Software License Agreement


The software supplied herewith by Microchip Technology Incorporated (the “Company”) for its PICmicro® Microcon-
troller is intended and supplied to you, the Company’s customer, for use solely and exclusively on Microchip PICmi-
cro Microcontroller products.
The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights
are reserved. Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under appli-
cable laws, as well as to civil liability for the breach of the terms and conditions of this license.
THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED
OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
NESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIR-
CUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON
WHATSOEVER.

APPENDIX A: DECHIT H SOURCE CODE


// Module DECHIT.h
//
// include this file when using the HiTech C compiler
//
#define HITECH

#include <pic.h>
#include <string.h>

typedef unsigned char byte;


typedef signed char sbyte;
typedef signed int word;

#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0

#define BIT_TEST( x, y) (( (x) & (1<<(y))) != 0)

// set config word


__CONFIG( UNPROTECT | (FOSC1 | FOSC0) | BODEN);
__IDLOC(0x1234); // define ID locations

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 7


AN745
APPENDIX B: DEECCS H SOURCE CODE
// Module DECCCS.h
//
// include this file when using the CCS C compiler
//
#define CCS

#DEVICE PIC16C63

typedef short bit; // one bit


typedef unsigned int byte; // one byte unsigned
typedef signed int sbyte; // one byte signed
typedef signed long word; // one word signed

// un-supported directives
#define static
#define volatile
#define interrupt

#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0

//
// F872 special function registers
//
#byte TMR0 = 0x01 // Timer 0
#bit T0IF = 0x0B.2 // Timer 0 interrupt flag
#bit T0IE = 0x0B.5 // Timer 0 interrupt enable
#bit GIE = 0x0B.7 // Global Interrupt Enable

#byte OPTION = 0x81 // prescaler timer0 control


#byte ADCON1 = 0x9f // A/D converter control

#byte TRISA = 0x85 // PORT A


#byte PORTA = 0x05
#bit RA0 = 0x05.0
#bit RA1 = 0x05.1
#bit RA2 = 0x05.2
#bit RA3 = 0x05.3
#bit RA4 = 0x05.4
#bit RA5 = 0x05.5

#byte TRISB = 0x86 // PORT B


#byte PORTB = 0x06
#bit RB0 = 0x06.0
#bit RB1 = 0x06.1
#bit RB2 = 0x06.2
#bit RB3 = 0x06.3
#bit RB4 = 0x06.4
#bit RB5 = 0x06.5
#bit RB6 = 0x06.6
#bit RB7 = 0x06.7

#byte TRISC = 0x87 // PORT C


#byte PORTC = 0x07

// internal EEPROM access


#byte EEADR = 0x10d
#byte EEDATA = 0x10c
#byte EECON1 = 0x18c
#byte EECON2 = 0x18d
#bit WR = 0x18c.1

DS00745A_C-page 8 Confidential  2001 Microchip Technology Inc.


AN745
#bit RD = 0x18c.0
#bit WREN = 0x18c.2
#bit EEPGD =0x18c.7

// macro versions of EEPROM write and read


#defineEEPROM_WRITE(addr, value) while(WR)con-
tinue;EEADR=(addr);EEDATA=(value);EEPGD=0;GIE=0;WREN=1;\
EECON2=0x55;EECON2=0xAA;WR=1;WREN=0
#defineEEPROM_READ(addr) ((EEADR=(addr)),(EEPGD=0),(RD=1),EEDATA)

// configuration and ID locations


#FUSES RC, NOWDT, NOPROTECT, BROWNOUT
#ID 0x1234

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 9


AN745
APPENDIX C: MAIN C SOURCE CODE

// *********************************************************************
// Filename: MAIN.c
// *********************************************************************
// Author: Lucio Di Jasio
// Company: Microchip Technology
// Revision: Rev 1.00
// Date: 08/07/00
//
// Keeloq Normal Learn Decoder on a mid range PIC
// full source in C
//
// Compiled using HITECH PIC C compiler v.7.93
// Compiled using CCS PIC C compiler v. 2.535
// ********************************************************************

//#include "decccs.h" // uncomment for CCS compiler


#include "dechit.h" // uncomment for HiTech compiler
//
//---------------------------------------------------------------------
// I/O definitions for PIC16F872
// compatible with PICDEM-2 demo board
//
// +-------- -------+
// Reset -|MCLR O RB7|- NU(ICD data)
// (POT) -|RA0 RB6|- NU(ICD clock)
// RFin -|RA1 RB5|- Vlow(Led)
// NU -|RA2 RB4|- LearnOut(Led)
// NU -|RA3 PRG/RB3|- Out3(Led)
// Learn -|RA4/T0CKI RB2|- Out2(Led)
// NU -|RA5 RB1|- Out1(Led)
// GND -|Vss INT/RB0|- Out0(Led)
// XTAL -|OSCIN Vdd|- +5V
// XTAL -|OSCOUT Vss|- GND
// NU -|RC0 RX/RC7|- NU(RS232)
// NU -|RC1 TX/RC6|- NU(RS232)
// NU(SW3) -|RC2/CCP1 RC5|- NU
// NU -|RC3/SCL SDA/RC4|- NU
// +----------------+
//

#define RFIn RA1 // i radio signal input


#define Learn RA4 // i learn button

#define Out0 RB0 // o S0 output


#define Out1 RB1 // o S1 output
#define Out2 RB2 // o S2 output
#define Out3 RB3 // o S3 output
#define Led RB4 // o LearnOut Led
#define Vlow RB5 // o low battery

#define MASKPA 0xff // port A I/O config (all input)


#define MASKPB 0xc0 // port B I/O config (6 outputs)
#define MASKPC 0xff // port C I/O config (NU)

// -----------------global variables ---------------------------

byte Buffer[9]; // receive buffer

//---------------------------------------------------------------
//

DS00745A_C-page 10 Confidential  2001 Microchip Technology Inc.


AN745
// keeloq receive buffer map
//
// | Plain text | Encrypted
// RV000000.KKKKIIII.IIIIIIII.IIIIIIII.IIIIIIII.KKKKOODD.DDDDDDDD.SSSSSSSS.SSSSSSSS
// 8 7 6 5 4 3 2 1 0
//
// I=S/N -> SERIAL NUMBER (28 BIT)
// K=KEY -> buttons encoding (4 BIT)
// S=Sync -> Sync counter (16 BIT)
// D=Disc -> Discrimination bits (10 BIT)
// R=Rept -> Repeat/first (1 BIT)
// V=Vlow -> Low battery (1 BIT)
//
//-- alias -------------------------------------------------------------
//
#define HopLo Buffer[0] //sync counter
#define HopHi Buffer[1] //
#define DisLo Buffer[2] //discrimination bits LSB
#define DOK Buffer[3] //Disc. MSB + Ovf + Key
#define IDLo Buffer[4] //S/N LSB
#define IDMi Buffer[5] //S/N
#define IDHi Buffer[6] //S/N MSB

#define S0 5 // Buffer[3] function codes


#define S1 6 // Buffer[3] function codes
#define S2 7 // Buffer[3] function codes
#define S3 4 // Buffer[3] function codes
#define VFlag 7// Buffer[8] low battery flag

//----------------- flags defines ------------------------------------


bit FHopOK; // Hopping code verified OK
bit FSame; // Same code as previous
bit FLearn; // Learn mode active
bit F2Chance; // Resync required

//--------------------------------------------------------------------
// timings
//
#define TOUT 5 // 5 * 71ms = 350ms output delay
#define TFLASH 2 // 4 * 71ms = 280ms half period
#define TLEARN 255 // 255 * 71ms = 18s learn timeout

//byte Flags; // various flags


byte CLearn, CTLearn; // learn timers and counter
byte CFlash, CTFlash; // led flashing timer and counter
byte COut; // output timer
byte FCode; // function codes and upper nibble of serial number

word Dato; // temp storage for read and write to mem.


word Ind; // address pointer to record in mem.
word Hop; // hopping code sync counter
word EHop; // last value of sync counter (from EEPROM)
word ETemp; // second copy of sync counter

//
// interrupt receiver
//
#include "rxim.c"

//
// external modules
//
#include "mem-87x.c" // EEPROM I2C routines

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 11


AN745
#include "table.c" // TABLE management
#include "keygen.c" // Keeloq decrypt and normal keygen

//
// prototypes
//
void Remote( void);

//
// MAIN
//
// Main program loop, I/O polling and timing
//
void main ()
{
// init
ADCON1 = 0x7; // disable analog inputs
TRISA = MASKPA; // set i/o config.
TRISB = MASKPB;
TRISC = MASKPC;
PORTA = 0; // init all outputs
PORTB = 0;
PORTC = 0;
OPTION = 0x8f; // prescaler assigned to WDT,
// TMR0 clock/4, no pull ups

CTLearn = 0; // Learn debounce


CLearn = 0; // Learn timer
COut = 0; // output timer
CFlash = 0; // flash counter
CTFlash = 0; // flash timer
FLearn = FALSE; // start in normal mode
F2Chance = FALSE; // no resynchronization required

InitReceiver(); // enable and init the receiver state machine

// main loop
while ( TRUE)
{
if ( RFFull) // buffer contains a message
Remote();

// loop waiting 512* period = 72ms


if ( XTMR < 512)
continue; // main loop

// once every 72ms


XTMR=0;

// re-init fundamental registers


ADCON1 = 0x7; // disable analog inputs
TRISA = MASKPA; // set i/o config.
TRISB = MASKPB;
TRISC = MASKPC;
OPTION = 0x0f; // prescaler assigned to WDT, TMR0 clock/4, pull up
T0IE = 1;
GIE = 1;

// poll learn
if ( !Learn) // low -> button pressed
{
CLearn++;

DS00745A_C-page 12 Confidential  2001 Microchip Technology Inc.


AN745
// pressing Learn button for more than 10s -> ERASE ALL
if (CLearn == 128) // 128 * 72 ms = 10s
{
Led = OFF; // switch off Learn Led
while( !Learn); // wait for button release
Led = ON; // signal Led on
ClearMem(); // erase all comand!
COut = TOUT; // single lomg flash pulse time
// timer will switch off Led
CLearn = 0; // reset learn debounce
FLearn = FALSE; // exit learn mode
}

// normal Learn button debounce


if (CLearn == 4) // 250ms debounce
{
FLearn = TRUE; // enter learn mode comand!
CTLearn = TLEARN; // load timout value
Led = ON; // turn Led on
}
}
else CLearn=0; // reset counter

// outputs timing
if ( COut > 0) // if timer running
{
COut--;
if ( COut == 0) // when it reach 0
{
Led = OFF; // all outputs off
Out0 = OFF;
Out1 = OFF;
Out2 = OFF;
Out3 = OFF;
Vlow = OFF;
}
}

// Learn Mode timout after 18s (TLEARN * 72ms)


if ( CTLearn > 0)
{
CTLearn--; // count down
if ( CTLearn == 0) // if timed out
{
Led = OFF; // exit Learn mode
FLearn = FALSE;
}
}

// Led Flashing
if ( CFlash > 0)
{
CTFlash--; // count down
if ( CTFlash == 0) // if timed out
{
CTFlash = TFLASH; // reload timer
CFlash--; // count one flash
Led = OFF; // toggle Led
if ( CFlash & 1)
Led = ON;
}
}

} // main loop
} // main

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 13


AN745

//
// Remote Routine
//
// Decrypts and interprets receive codes
// Does Normal Operation and Learn Mode
//
// INPUT: Buffer contains the received code word
//
// OUTPUT: S0..S3 and LearnOut
//
void Remote()
{
// a frame was received and is stored in the receive buffer
// move it to decryption Buffer, and restart receiving
memcpy( Buffer, B, 9);
RFFull = FALSE; // ready to receive a new frame

// decoding
NormalKeyGen(); // compute the decryption key
Decrypt(); // decrypt the hopping code portion

if ( DecCHK() == FALSE) // decription failed


return;

if ( FLearn)
{
// Learn Mode

if ( Find()== FALSE)
// could not find the Serial Number in memory
{
if ( !Insert()) // look for new space
return; // fail if no memory available
}

// ASSERT Ind is pointing to a valid memory location


IDWrite(); // write Serial Number in memory
FHopOK = TRUE; // enable updating Hopping Code
HopUpdate(); // Write Hoping code in memory

CFlash = 32; // request Led flashing


CTFlash = TFLASH; // load period timer
Led = TRUE; // start with Led on
FLearn = FALSE; // terminate successfully Learn
} // Learn

else // Normal Mode of operation


{
if ( Find()== FALSE)
return;
if ( !HopCHK()) // check Hopping code integrity
return;

if ( FSame) // identified same code as last memorized


{
if ( COut >0) // if output is still active
COut = TOUT; // reload timer to keep active
else
return; // else discard
}

else // hopping code incrementing properly


{

DS00745A_C-page 14 Confidential  2001 Microchip Technology Inc.


AN745
HopUpdate(); // update memory

// set outputs according to function code


if ( BIT_TEST(Buffer[3],S0))
Out0 = ON;
if ( BIT_TEST(Buffer[3],S1))
Out1 = ON;
if ( BIT_TEST(Buffer[3],S2))
Out2 = ON;
if ( BIT_TEST(Buffer[3],S3))
Out3 = ON;

// set low battery flag if necessary


if ( BIT_TEST(Buffer[8],VFlag))
Vlow = ON;

// check against learned function code


if ( (( Buffer[7] ^ FCode) & 0xf0) == 0)
Led = ON;

// init output timer


COut = TOUT;
}// recognized
} // normal mode

} // remote

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 15


AN745
APPENDIX D: RXI C SOURCE CODE
// **********************************************************************
// Filename: RXI.c
// *********************************************************************
// Author: Lucio Di Jasio
// Company: Microchip Technology
// Revision: Rev 1.00
// Date: 08/07/00
//
// Interrupt based receive routine
//
// Compiled using HiTech PIC C compiler v.7.93
// Compiled using CCS PIC C compiler v.2.535
// ********************************************************************
#define CLOCK 4 // MHz
#define TE 400 // us
#define OVERSAMPLING 3
#define PERIOD TE/OVERSAMPLING*4/CLOCK

#define NBIT 65 // number of bit to receive -1

byte B[9]; // receive buffer

static byte RFstate; // receiver state


static sbyte RFcount; // timer counter
static byte Bptr; // receive buffer pointer
static byte BitCount; // received bits counter
word XTMR; // 16 bit extended timer

volatile bit RFFull; // buffer full


volatile bit RFBit; // sampled RF signal

#define TRFreset 0
#define TRFSYNC 1
#define TRFUNO 2
#define TRFZERO 3

#define HIGH_TO -10 // longest high Te


#define LOW_TO 10 // longest low Te
#define SHORT_HEAD 20 // shortest Thead accepted 2,7ms
#define LONG_HEAD 45 // longest Thead accepted 6,2ms

#pragma int_rtcc // install as interrupt handler (comment for HiTech!)


interrupt
rxi()
{
// this routine gets called every time TMR0 overflows
RFBit = RFIn; // sampling RF pin verify!!!
TMR0 -= PERIOD; // reload
T0IF = 0;

XTMR++; // extended 16 long timer update

if (RFFull) // avoid overrun


return;

switch( RFstate) // state machine main switch


{

case TRFUNO:
if ( RFBit == 0)
{ // falling edge detected ----+
// |

DS00745A_C-page 16 Confidential  2001 Microchip Technology Inc.


AN745
// +----
RFstate= TRFZERO;
}
else
{ // while high
RFcount--;
if ( RFcount < HIGH_TO)
RFstate = TRFreset; // reset if too long
}
break;

case TRFZERO:
if ( RFBit)
{ // rising edge detected +----
// |
// ----+
RFstate= TRFUNO;
B[Bptr] >>= 1; // rotate
if ( RFcount >= 0)
{
B[Bptr]+=0x80; // shift in bit
}
RFcount = 0; // reset length counter

if ( ( ++BitCount & 7) == 0)
Bptr++; // advance one byte
if (BitCount == NBIT)
{
RFstate = TRFreset; // finished receiving
RFFull = TRUE;
}
}
else
{ // still low
RFcount++;
if ( RFcount >= LOW_TO) // too long low
{
RFstate = TRFSYNC; // fall back into RFSYNC state
Bptr = 0; // reset pointers, while keep counting on
BitCount = 0;
}
}
break;

case TRFSYNC:
if ( RFBit)
{ // rising edge detected +---+ +---..
// | | <-Theader-> |
// +----------------+
if ( ( RFcount < SHORT_HEAD) || ( RFcount >= LONG_HEAD))
{
RFstate = TRFreset;
break; // too short/long, no header
}
else
{
RFcount =0; // restart counter
RFstate= TRFUNO;
}
}
else
{ // still low
RFcount++;
}
break;

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 17


AN745

case TRFreset:
default:
RFstate = TRFSYNC; // reset state machine in all other cases
RFcount = 0;
Bptr = 0;
BitCount = 0;
break;

} // switch

} // rxi

void InitReceiver()
{
T0IF = 0;
T0IE = 1; // TMR0 overflow interrupt
GIE = 1; // enable interrupts
RFstate = TRFreset; // reset state machine in all other cases
RFFull = 0; // start with buffer empty
XTMR = 0; // start extended timer
}

DS00745A_C-page 18 Confidential  2001 Microchip Technology Inc.


AN745
APPENDIX E: TABLE C SOURCE CODE
// *********************************************************************
// Filename: TABLE.c
// *********************************************************************
// Author: Lucio Di Jasio
// Company: Microchip Technology
// Revision: Rev 1.00
// Date: 08/07/00
//
// EEPROM TABLE Management routines
// simple "linear list" management method
//
// Compiled using HiTech C compiler v.7.93
// Compiled using CCS PIC C compiler v. 2.535
// ********************************************************************/
#define MAX_USER 8 // max number of TX that can be learned
#define EL_SIZE 8 // single record size in bytes

// ------------------------------------------------------------
//Table structure definition:
//
// the EEPROM is filled with an array of MAX_USER user records
// starting at address 0000
// each record is EL_SIZE byte large and contains the following fields:
// EEPROM access is in 16 bit words for efficiency
//
// DatoHi DatoLo offset
// +-------+-------+
// | FCode | IDLo | 0 XF contains the function codes (buttons) used during learning
// +-------+-------+ and the top 4 bit of Serial Number
// | IDHi | IDMi | +2 IDHi IDMi IDLo contain the 24 lsb of the Serial Number
// +-------+-------+
// | HopHi | HopLo | +4 sync counter
// +-------+-------+
// | HopHi2| HopLo2| +6 second copy of sync counter for integrity checking
// +-------+-------+
//
// NOTE a function code of 0f0 (seed transmission) is considered
// invalid during learning and is used here to a mark location free
//
// -----------------------------------------------------------
// FIND Routine
//
// search through the whole table the given a record whose ID match
//
// INPUT:
// IDHi, IDMi, IDLo, serial number to search
//
// OUTPUT:
// Ind address of record (if found)
// EHop sync counter value
// ETemp second copy of sync counter
// RETURN: TRUE if matching record found
//
byte Find()
{
byte Found;
Found = FALSE; // init to not found

for (Ind=0; Ind < (EL_SIZE * MAX_USER); Ind+=EL_SIZE)


{
RDword( Ind); // read first Word
FCode = (Dato>>8);

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 19


AN745
// check if 1111xxxx
if ( (FCode & 0xf0) == 0xf0)
continue; // empty

if (IDLo != (Dato & 0xff))


continue; // fails match

RDnext(); // read next word


if ( ( (Dato & 0xff) == IDMi) && ( (Dato>>8) == IDHi))
{
Found = TRUE; // match
break;
}
} // for

if (Found == TRUE)
{
RDnext(); // read HopHi/Lo
EHop = Dato;
RDnext(); // read HopHi2/Lo2
ETemp= Dato;
}

return Found;
}

// -----------------------------------------------------------
//INSERT Routine
//
//search through the whole table for an empty space
//
//INPUT:
// IDHi, IDMi, IDLo, serial number to insert
//
//OUTPUT:
// Ind address of empty record
//
//RETURN: FALSE if no empty space found
//
byte Insert()
{
for (Ind=0; Ind < (EL_SIZE * MAX_USER); Ind+=EL_SIZE)
{
RDword(Ind); // read first Word
FCode = (Dato>>8);
// check if 1111xxxx
if ( (FCode & 0xf0) == 0xf0)
return TRUE; // insert point found
} // for

return FALSE; // could not find any empty slot


} // Insert

//-----------------------------------------------------------
//Function IDWrite
// store IDHi,Mi,Lo + XF at current address Ind
//INPUT:
// Ind point to record + offset 0
// IDHi, IDMi, IDLo Serial Number
// XF function code
//OUTPUT:
//
byte IDWrite()
{
if (!FLearn)

DS00745A_C-page 20 Confidential  2001 Microchip Technology Inc.


AN745
return FALSE; // Guard statement: check if Learn ON

Dato = Buffer[7];
Dato = (Dato<<8) + IDLo;
WRword(Ind); // write first word

Dato = IDHi;
Dato = (Dato<<8) + IDMi;
WRword(Ind+2); // write second word

return TRUE;
} // IDWrite

//------------------------------------------------------------
//Function HopUpdate
// update sync counter of user record at current location
//INPUT:
// Ind record + offset 0
// Hop current sync counter
//OUTPUT:
// none
//
byte HopUpdate()
{
if (!FHopOK)
return FALSE; // Guard statement: check if Hop update

Hop = ((word)HopHi<<8) + HopLo;


Dato = Hop;
WRword(Ind+4); // write at offset +4
Dato = Hop;
WRword(Ind+6); // back up copy at offset +6
FHopOK = FALSE; // for safety disable updating hopping code

return TRUE;
} // HopUpdate

//-----------------------------------------------------------
//Function ClearMem
// mark all records free
//INPUT:
//OUTPUT:
//USES:
//
byte ClearMem()
{
for (Ind=0; Ind < (EL_SIZE * MAX_USER); Ind+=EL_SIZE)
{
Dato = 0xffff;
WRword( Ind);
}

return TRUE;
} // ClearMem

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 21


AN745
APPENDIX F: MEM-87X C SOURCE CODE
// *********************************************************************
// Filename: mem-87x.c
// *********************************************************************
// Author: Lucio Di Jasio
// Company: Microchip Technology
// Revision: Rev 1.00
// Date: 08/11/00
//
// Internal EEPROM routines for PIC16F87X
//
// Compiled using HiTech PIC C compiler v.7.93
// Compiled using CCS PIC C compiler v. 2.535
// *********************************************************************

void RDword(word Ind)


{
Dato = EEPROM_READ( Ind);
Dato += (word) EEPROM_READ( Ind+1) <<8;
}

void RDnext()
{
// continue reading
EEADR++; // NOTE generate no carry
Dato = ((RD=1), EEDATA);
EEADR++;
Dato += ((RD=1), EEDATA)<<8;
}

void WRword(word Ind)


{
EEPROM_WRITE( Ind, Dato); GIE = 1; // write and re-enable interrupt
EEPROM_WRITE( Ind+1, Dato>>8); GIE = 1;
}

DS00745A_C-page 22 Confidential  2001 Microchip Technology Inc.


AN745
APPENDIX G: KEY GENERATION SOURCE CODE
// -------------------------------------------------------------------------
// LEGAL NOTICE
//
// The information contained in this document is proprietary and
// confidential information of Microchip Technology Inc. Therefore all
// parties are required to sign a non-disclosure agreement before
// receiving this document.
// -------------------------------------------------------------------------
//
// Keeloq Normal Key Generation and Decryption
// Compiled using CCS PIC C compiler v. 2.535
// Compiled using HITECH PIC C compiler v. 7.93
//
// version 1.00 08/07/2000 Lucio Di Jasio
//
// =========================================================================

byte DKEY[8]; // Decryption key


byte SEED[4]; // seed value = serial number
word NextHop; // resync value for 2 Chance

#ifdef HITECH
#include "fastdech.c" // for HITECH optimized version
#else
#include "fastdecc.c" // for CCS optimized version
#endif

// ----------------------------------------------------------------------
void LoadManufCode()
{
DKEY[0]=0xef; // DKEY=0123456789ABCDEF
DKEY[1]=0xcd;
DKEY[2]=0xAB;
DKEY[3]=0x89;
DKEY[4]=0x67;
DKEY[5]=0x45;
DKEY[6]=0x23;
DKEY[7]=0x01;
}

//----------------------------------------------------------------------
//
// Key Generation routine
//
// Normal Learn algorithm
//
// INPUT: Serial Number (Buffer[4..7])
// Manufacturer code
// OUTPUT: DKEY[0..7] computed decryption key
//
void NormalKeyGen()
{
byte HOPtemp[4]; // HOP temp buffer
byte SKEYtemp[4]; // temp decryption key

// check if same Serial Number as last time while output active


// it was stored in Seed
if (( SEED[0] != Buffer[4]) ||
( SEED[1] != Buffer[5]) ||
( SEED[2] != Buffer[6]) ||
( SEED[3] != (Buffer[7] & 0x0f)) ||

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 23


AN745
(COut == 0))
{
// no new KeyGen is needed
memcpy( HOPtemp, Buffer, 4); // save hopping code to temp
memcpy( SEED, &Buffer[4], 4); // make seed = Serial Number
SEED[3] &= 0x0f; // mask out function codes

// compute LSb of decryption key first


memcpy( Buffer, SEED, 4); // get SEED in
Buffer[3] |= 0x20; // add constant 0x20
LoadManufCode();
Decrypt();
memcpy( SKEYtemp, Buffer, 4); // save result for later

// compute MSb of decryption key


memcpy( Buffer, SEED, 4); // get SEED in
Buffer[3] |= 0x60; // add constant 0x60
LoadManufCode();
Decrypt();
memcpy( &DKEY[4], Buffer, 4); // move it into DKEY MSb
memcpy( DKEY, SKEYtemp, 4); // add LSb

// ready for Decrypt


memcpy( Buffer, HOPtemp, 4); // restore hopping code
}
else // same Serial Number as last time...
{ // just keep on using same Decription Key
}

} // Normal KeyGen

//----------------------------------------------------------------------
//
// Valid Decryption Check
//
// INPUT: Serial Number (Buffer[4..7])
// Hopping Code (Buffer[0..3])
// OUTPUT: TRUE if discrimination bits == lsb Serial Number
// and decrypted function code == plain text function code
byte DecCHK()
{
// verify discrimination bits
if ( DisLo != IDLo) // compare low 8bit of Serial Number
return FALSE;

if ( ( (Buffer[3] ^ IDMi) & 0x3)!= 0) // compare 9th and 10th bit of SN


return FALSE;

// verify function code


if ( ((Buffer[3] ^ Buffer[7]) & 0xf0)!= 0)
return FALSE;

return TRUE;
} // DecCHK

//----------------------------------------------------------------------
//
// Hopping Code Verification
//
// INPUT: Hopping Code (Buffer[0..3])
// and previous value stored in EEPROM EHop
// OUTPUT: TRUE if hopping code is incrementing and inside a safe window (16)
//

DS00745A_C-page 24 Confidential  2001 Microchip Technology Inc.


AN745
byte ReqResync()
{
F2Chance= TRUE; // flag that a second (sequential) transmission
NextHop = Hop+1; // is needed to resynchronize receiver
return FALSE; // cannot accept for now
}

byte HopCHK()
{
FHopOK = FALSE; // Hopping Code is not verified yet
FSame = FALSE; // Hopping Code is not the same as previous

// make it a 16 bit signed integer


Hop = ((word)HopHi << 8) + HopLo;

if ( F2Chance)
if ( NextHop == Hop)
{
F2Chance = FALSE; // resync success
FHopOK = TRUE;
return TRUE;
}

// verify EEPROM integrity


if ( EHop != ETemp)
return ReqResync(); // memory corrupted need a resync

// main comparison
ETemp = Hop - EHop; // subtract last value from new one

if ( ETemp < 0) // locked region


return FALSE; // fail

else if ( ETemp > 16) // resync region


return ReqResync();

else // 0>= ETemp >16 ; open window


{
if ( ETemp == 0) // same code (ETemp == 0)
FSame = TRUE; // rise a flag

FHopOK = TRUE;
return TRUE;
}
} // HopCHK

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 25


AN745
APPENDIX H: FASTDECH C SOURCE CODE
//-------------------------------------------------------------------------
// LEGAL NOTICE
//
// The information contained in this document is proprietary and
// confidential information of Microchip Technology Inc. Therefore all
// parties are required to sign a non-disclosure agreement before
// receiving this document.
//-------------------------------------------------------------------------
// Keeloq Decryption Algorithm
//
// optimized for HITECH PIC C compiler v.7.93
//
// version 1.00 08/07/2000 Lucio Di Jasio
//
//=========================================================================

byte aux;

void Decrypt()
{
byte i, j, key;
sbyte p;

p = 1;

for (j=66; j>0; j--)


{
key = DKEY[p--];
if ( p < 0)
p += 8;
for (i=8; i>0; i--)
{
// NLF
if ( BIT_TEST( Buffer[3],6))
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b00111010; // 10
else
aux = 0b01011100; // 11
}
else
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b01110100; // 00
else
aux = 0b00101110; // 01
}

// move bit in position 7


if ( BIT_TEST( Buffer[2],3))
asm("swapf _aux,f");
if ( BIT_TEST( Buffer[1],0))
aux<<=2;
if (BIT_TEST( Buffer[0],0))
aux<<=1;

// xor with Buffer and Dkey


aux ^= Buffer[1] ^ Buffer[3] ^ key;

// shift in buffer
// shift_left( Buffer, 4, BIT_TEST( aux,7));
#asm

DS00745A_C-page 26 Confidential  2001 Microchip Technology Inc.


AN745
rlf _aux,w
rlf _Buffer,f
rlf _Buffer+1,f
rlf _Buffer+2,f
rlf _Buffer+3,F
#endasm

// rotate Dkey
// rotate_left( DKEY, 8);
key<<=1;
} // for i
} // for j
} // decrypt

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 27


AN745
APPENDIX I: FASTDECC C SOURCE CODE
//-------------------------------------------------------------------------
// LEGAL NOTICE
//
// The information contained in this document is proprietary and
// confidential information of Microchip Technology Inc. Therefore all
// parties are required to sign a non-disclosure agreement before
// receiving this document.
//-------------------------------------------------------------------------
// Keeloq Decryption Algorithm
//
// optimized for CCS PIC C compiler v. 2.535
//
// version 1.00 08/07/2000 Lucio Di Jasio
//
//=========================================================================
byte aux;

void Decrypt()
{
byte i, j, key;
sbyte p;

p = 1;

for (j=66; j>0; j--)


{
key = DKEY[p--];
if (p<0)
p+=8;

for (i=8; i>0; i--)


{
// NLF
if ( BIT_TEST( Buffer[3],6))
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b00111010; // 10
else
aux = 0b01011100; // 11
}
else
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b01110100; // 00
else
aux = 0b00101110; // 01
}

// move bit in position 7


if ( BIT_TEST( Buffer[2],3))
#asm
swapf aux,f
#endasm
if ( BIT_TEST( Buffer[1],0))
aux<<=2;
if (BIT_TEST( Buffer[0],0))
aux<<=1;

// xor with Buffer and Dkey


aux ^= Buffer[1] ^ Buffer[3] ^ key;

// shift in buffer

DS00745A_C-page 28 Confidential  2001 Microchip Technology Inc.


AN745
shift_left( Buffer, 4, BIT_TEST( aux,7));

key<<=1;
} // for i

} // for j
} // decrypt

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 29


AN745
NOTES:

DS00745A_C-page 30 Confidential  2001 Microchip Technology Inc.


AN745

“All rights reserved. Copyright © 2001, Microchip Trademarks


Technology Incorporated, USA. Information contained
in this publication regarding device applications and the The Microchip name, logo, PIC, PICmicro,
like is intended through suggestion only and may be PICMASTER, PICSTART, PRO MATE, KEELOQ,
superseded by updates. No representation or warranty SEEVAL, MPLAB and The Embedded Control
is given and no liability is assumed by Microchip Solutions Company are registered trademarks of
Technology Incorporated with respect to the accuracy Microchip Technology Incorporated in the U.S.A. and
or use of such information, or infringement of patents or other countries.
other intellectual property rights arising from such use
or otherwise. Use of Microchip’s products as critical Total Endurance, ICSP, In-Circuit Serial Programming,
components in life support systems is not authorized FilterLab, MXDEV, microID, FlexROM, fuzzyLAB,
except with express written approval by Microchip. No MPASM, MPLINK, MPLIB, PICDEM, ICEPIC,
licenses are conveyed, implicitly or otherwise, under Migratable Memory, FanSense, ECONOMONITOR,
any intellectual property rights. The Microchip logo and SelectMode and microPort are trademarks of
name are registered trademarks of Microchip Microchip Technology Incorporated in the U.S.A.
Technology Inc. in the U.S.A. and other countries. All
Serialized Quick Term Programming (SQTP) is a
rights reserved. All other trademarks mentioned herein
service mark of Microchip Technology Incorporated in
are the property of their respective companies. No
the U.S.A.
licenses are conveyed, implicitly or otherwise, under
any intellectual property rights.” All other trademarks mentioned herein are property of
their respective companies.
© 2001, Microchip Technology Incorporated, Printed in
the U.S.A., All Rights Reserved.

Microchip received QS-9000 quality system


certification for its worldwide headquarters,
design and wafer fabrication facilities in
Chandler and Tempe, Arizona in July 1999. The
Company’s quality system processes and
procedures are QS-9000 compliant for its
PICmicro® 8-bit MCUs, KEELOQ® code hopping
devices, Serial EEPROMs and microperipheral
products. In addition, Microchip’s quality
system for the design and manufacture of
development systems is ISO 9001 certified.

 2001 Microchip Technology Inc. Confidential DS00745A_C-page 31


WORLDWIDE SALES AND SERVICE
AMERICAS New York ASIA/PACIFIC (continued)
150 Motor Parkway, Suite 202
Corporate Office Korea
Hauppauge, NY 11788
2355 West Chandler Blvd. Microchip Technology Korea
Tel: 631-273-5305 Fax: 631-273-5335
Chandler, AZ 85224-6199 168-1, Youngbo Bldg. 3 Floor
Tel: 480-792-7200 Fax: 480-792-7277 San Jose Samsung-Dong, Kangnam-Ku
Technical Support: 480-792-7627 Microchip Technology Inc. Seoul, Korea
Web Address: http://www.microchip.com 2107 North First Street, Suite 590 Tel: 82-2-554-7200 Fax: 82-2-558-5934
San Jose, CA 95131
Rocky Mountain Singapore
Tel: 408-436-7950 Fax: 408-436-7955
2355 West Chandler Blvd. Microchip Technology Singapore Pte Ltd.
Chandler, AZ 85224-6199 Toronto 200 Middle Road
Tel: 480-792-7966 Fax: 480-792-7456 6285 Northam Drive, Suite 108 #07-02 Prime Centre
Mississauga, Ontario L4V 1X5, Canada Singapore, 188980
Atlanta
Tel: 905-673-0699 Fax: 905-673-6509 Tel: 65-334-8870 Fax: 65-334-8850
500 Sugar Mill Road, Suite 200B
Atlanta, GA 30350 Taiwan
Tel: 770-640-0034 Fax: 770-640-0307 Microchip Technology Taiwan
ASIA/PACIFIC 11F-3, No. 207
Austin
Analog Product Sales Australia Tung Hua North Road
8303 MoPac Expressway North Microchip Technology Australia Pty Ltd Taipei, 105, Taiwan
Suite A-201 Suite 22, 41 Rawson Street Tel: 886-2-2717-7175 Fax: 886-2-2545-0139
Austin, TX 78759 Epping 2121, NSW
Tel: 512-345-2030 Fax: 512-345-6085 Australia
Boston Tel: 61-2-9868-6733 Fax: 61-2-9868-6755 EUROPE
2 Lan Drive, Suite 120 China - Beijing Denmark
Westford, MA 01886 Microchip Technology Beijing Office Microchip Technology Denmark ApS
Tel: 978-692-3848 Fax: 978-692-3821 Unit 915 Regus Business Centre
New China Hong Kong Manhattan Bldg. Lautrup hoj 1-3
Boston
No. 6 Chaoyangmen Beidajie Ballerup DK-2750 Denmark
Analog Product Sales
Beijing, 100027, No. China Tel: 45 4420 9895 Fax: 45 4420 9910
Unit A-8-1 Millbrook Tarry Condominium
Tel: 86-10-85282100 Fax: 86-10-85282104
97 Lowell Road France
Concord, MA 01742 China - Shanghai Arizona Microchip Technology SARL
Tel: 978-371-6400 Fax: 978-371-0050 Microchip Technology Shanghai Office Parc d’Activite du Moulin de Massy
Room 701, Bldg. B 43 Rue du Saule Trapu
Chicago
Far East International Plaza Batiment A - ler Etage
333 Pierce Road, Suite 180
No. 317 Xian Xia Road 91300 Massy, France
Itasca, IL 60143
Shanghai, 200051 Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79
Tel: 630-285-0071 Fax: 630-285-0075
Tel: 86-21-6275-5700 Fax: 86-21-6275-5060
Dallas Germany
Hong Kong Arizona Microchip Technology GmbH
4570 Westgrove Drive, Suite 160
Microchip Asia Pacific Gustav-Heinemann Ring 125
Addison, TX 75001
RM 2101, Tower 2, Metroplaza D-81739 Munich, Germany
Tel: 972-818-7423 Fax: 972-818-2924
223 Hing Fong Road Tel: 49-89-627-144 0 Fax: 49-89-627-144-44
Dayton Kwai Fong, N.T., Hong Kong
Two Prestige Place, Suite 130 Germany
Tel: 852-2401-1200 Fax: 852-2401-3431
Miamisburg, OH 45342 Analog Product Sales
India Lochhamer Strasse 13
Tel: 937-291-1654 Fax: 937-291-9175
Microchip Technology Inc. D-82152 Martinsried, Germany
Detroit India Liaison Office Tel: 49-89-895650-0 Fax: 49-89-895650-22
Tri-Atria Office Building Divyasree Chambers
32255 Northwestern Highway, Suite 190 Italy
1 Floor, Wing A (A3/A4)
Farmington Hills, MI 48334 Arizona Microchip Technology SRL
No. 11, O’Shaugnessey Road
Tel: 248-538-2250 Fax: 248-538-2260 Centro Direzionale Colleoni
Bangalore, 560 025, India
Palazzo Taurus 1 V. Le Colleoni 1
Los Angeles Tel: 91-80-2290061 Fax: 91-80-2290062
20041 Agrate Brianza
18201 Von Karman, Suite 1090 Japan Milan, Italy
Irvine, CA 92612 Microchip Technology Intl. Inc. Tel: 39-039-65791-1 Fax: 39-039-6899883
Tel: 949-263-1888 Fax: 949-263-1338 Benex S-1 6F
United Kingdom
Mountain View 3-18-20, Shinyokohama
Arizona Microchip Technology Ltd.
Analog Product Sales Kohoku-Ku, Yokohama-shi
505 Eskdale Road
1300 Terra Bella Avenue Kanagawa, 222-0033, Japan
Winnersh Triangle
Mountain View, CA 94043-1836 Tel: 81-45-471- 6166 Fax: 81-45-471-6122
Wokingham
Tel: 650-968-9241 Fax: 650-967-1590
Berkshire, England RG41 5TU
Tel: 44 118 921 5869 Fax: 44-118 921-5820

01/30/01

All rights reserved. © 2001 Microchip Technology Incorporated. Printed in the USA. 3/01 Printed on recycled paper.
Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by
updates. It is your responsibility to ensure that your application meets with your specifications. No representation or warranty is given and no liability is
assumed by Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual
property rights arising from such use or otherwise. Use of Microchip’s products as critical components in life support systems is not authorized except with
express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, except as maybe explicitly expressed herein, under any intellec-
tual property rights. The Microchip logo and name are registered trademarks of Microchip Technology Inc. in the U.S.A. and other countries. All rights
reserved. All other trademarks mentioned herein are the property of their respective companies.

DS00745A_C-page 32 Confidential  2001 Microchip Technology Inc.

You might also like