************************************************
**  EMUTAG SDK v3 for creating user firmware  **
**   based on  NFC Forum Generic Type 2 Tag   **
**          Release date: 2017/07/15          **
************************************************

1. ARCHIVE CONTENTS

calltree.txt : function inclusion chart for NTAG213 to calculate required stack depth (resides in RAM but not included in resource usage at compile time)
Changelog    : version history and changes
common.eep   : EEPROM binary image required for all firmware versions, contains one of CRC tables
macros.h     : useful assembler macros to speed up array operations
main.h       : provided API and list of reserved AVR registers
main.o       : compiled main code handling radio frontend and timing
Makefile     : compiling / flashing directives
README       : this file
user*.c      : example user applications, see section 3 "USAGE" below
tools/       : additional compiler and programmer files for WinAVR-20100110

2. DEPENDENCIES

In order to use the SDK, the following software should be installed:
 - For Linux and other Unix-like systems: avr-gcc, avr-binutils, avr-libc, and programmer (avrdude by default).
 - For Windows: WinAVR and programmer, if not using avrdude built into WinAVR. "bin" directory of WinAVR needs to be in the system PATH.

3. USAGE

Note: If you are on Windows and using WinAVR-20100110, it does not support ATtiny4313 by default. The archive contains additional files needed to compile with that version of compiler and flash with the version of avrdude included.
File tools/iotn4313.h: place it into directory <WinAVR_dir>\avr\include\avr
File tools/avrdude-conf-t4313.txt: copy all the code from it and paste it into file <WinAVR_dir>\bin\avrdude.conf after the description of ATtiny2313 (by default at line 8918).

To compile the code, simply type "make" in a shell in project directory. The project will be compiled using the example user.c file, resulting in a working MIFARE Ultralight emulator.

Depending on the programmer, avrdude-based programmers can be used by typing "make flash". Prior to that, the programmer type and hardware port need to be configured in the Makefile on line 1.

The file user.c serves as a reference for developing own code, or modifying user.c. The user code has to be either all contained in one file user.c, or direct inclusion using quotes ("") should be used in case of multiple C files. In practice with small devices such as ATtiny4313, direct inclusion results in smaller code size and reduced execution time, compared to compiling to multiple object files and linking them.

Example code for various tag types is provided in:
- user.c                : MIFARE Ultralight
- user-ev1-20p-sniff.c  : MIFARE Ultralight EV1 (20-page version) with password sniffing modes
- user-ev1-41p-sniff.c  : MIFARE Ultralight EV1 (41-page version) with password sniffing modes
- user-ntag203.c        : NTAG203
- user-ntag213-sniff.c  : NTAG213 with password sniffing modes
- user-mikron.c         : tag similar to Ultralight from the Russian manufacturer "MIKRON"
- user-blank.c          : blank template for a generic NFC Forum Type 2 tag, containing the minimum required elements

4. DEVELOPMENT GUIDELINES

Because a part of code has already been compiled in order to ensure all time-critical instructions are compiled correctly, some AVR resources have to be shared between the compiled main code and the user code. These resources are listed in main.h header file and consist of reserved AVR registers, receive / transmit buffers, and two functions.

The principle of operation of the main code is the following:
 - During boot, the user_init() function is called once. It can be used to preload default values into registers and RAM buffers. Bits 0 - 2 and 4 - 5 in register "ctrl_flags" are initialized to 0 by main code.
 - When a packet is received, it is loaded into rx_buf[] along with a partial incomplete byte (if present), and RX flags are set to appropriate values.
 - Next, the user_proc() function is called, and incoming message length in bytes and bits is passed to it as parameters.
 - To send a reply to the reader, optionally set X flags and call the function reply() with pointers to start and end of the message to transmit, and with parameter how many bits to skip during transmission of byte 0. If nothing needs to be sent, simply return from user_proc(). If reply() is called more than once, the first call will be executed and the rest of the calls will be ignored.
   * Responses are automatically aligned to 9-bit frames timed from the request. After completion of user code, the main program waits for start of next 9-bit frame and synchronizes the response to it. Therefore, it is recommended that user_proc() returns as soon as possible after calling reply(). If user_proc() returns without calling reply(), the main program still waits for start of the next 9-bit frame, and then gets ready to receive the next frame from the NFC reader.
 - After sending an optional reply and before getting ready to receive the next frame from the NFC reader, user_frame_end() is called. This can be used to perform operations longer than tag response timeout, such as writing to Flash. Emutag will not be able to receive a frame during all the busy period, but at least this mechanism allows to send responses quickly without executing long operations in between the request and the response.
 - In the time between packets, if a loss of reader field of > 100 usec is detected, user_pwr_cycle() is called one or multiple times. Since the device is powered by batteries and keeps running between packets, this can be used to reset the anticollision state machine, as demonstrated in the examples. This function is also called on boot one or multiple times after user_init(), but only if NFC reader field is not present at boot time. It is therefore recommended to explicitely call user_pwr_cycle() at the end of user_init() to reset the tag state machine once more.

In terms of resources available to the user, here's a brief list of resources which can and cannot be used:
Registers - can reserve r7-r15 inclusively using "register" keyword.
RAM - up to about 220 bytes can be used, depending on stack usage by call tree. NOTE: at the end of compilation, "size" command output does not include required stack space in RAM usage! Please refer to listing file generated after compilation (*.lst) and calltree.txt.
Flash memory - MIFARE Ultralight code compiles to about 2.5 kB. ATtiny4313 has 4 kB of Flash.
EEPROM - all of it is used to store one of CRC tables needed by the compiled main code. Please use Flash to store non-volatile data.
SFR - strongly recommended not to access any SFR, especially write. Notes on particular modules are listed below.
  TIMER0 - used to generate timely responses from the end of incoming message. Safe to read TCNT0. TIMER0 is counting with prescaler set to 1024. Count and prescaler are reset when an incoming message is received.
  TIMER1 - not used, can be also used for user code.
  I/O ports: Connected pins should never be written, as well as the entire PORTB, as its contents 0xFF are used to quickly load into a register during an interrupt routine in the compiled main code. Reading should be OK in general.
  Serial port - already used to receive and send data to/from antenna.
  SPI - free, can be used for debugging.
  NO WARRANTY ON WRITING OTHER SFR.
Adding interrupts - an extra interrupt happening outside of user function runtime WILL disrupt the main code. All user interrupts should only be enabled during user function runtime and take < 40 machine cycles including vectoring / return time.

* During execution of user code an interrupt is consuming a maximum of 16 cycles per every 64 CPU cycles. This means the user application has to complete in (64 - 16) * 2 * (9 - 3) = 576 cycles in order to meet the timing requirement for READ command. 2 stands for number of Manchester encoding bits in a data bit, 9 is the number of bits in a byte including a parity bit, and 3 is a fixed overhead constant as in this implementation of main code.

Meanings of registers, buffers and functions used by main code is explained in detail in main.h comments.

5. SHARING

The main code has been initially compiled without low-power functionality, as for a DEMO-VERSION. After multiple requests and sales I'm releasing for the first time the low-power version that puts Emutag in standby and consumes 0.2 uA when the reader field is not present, as opposed to the demo version, always consuming 5-6 mA. Simply replace the file main.o with main-lowpwr.o. Feature requests for firmwares are accepted by email: alexey.lt@gmail.com. If you ever manage to create a full tag firmware using this SDK, even something custom for a specific application, please consider sharing as I've shared with you the low-power version!

**********************
**  www.emutag.com  **
**********************
