TWN4 API Reference DocRev23
TWN4 API Reference DocRev23
API Reference
Elatec GmbH
Contents
Contents
1 System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.1 SysCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.2 Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3 StartBootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.4 GetSysTicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5 GetVersionString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6 GetUSBType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 GetDeviceType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.8 Sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.9 GetDeviceUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.10 SetParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.11 GetLastError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2 I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.1 Set COM-Port Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.2 Get USB Device State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1.3 Get Host Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2 Miscellaneous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.1 Wake Up Host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3 Data I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.1 Query I/O Buffer Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.2 Get I/O Buffer Byte Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3.3 Test Empty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3.4 Test Full . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3.5 Send Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3.6 Send Multiple Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3.7 Read Byte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3.8 Read Multiple Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3 Memory Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1 Byte Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.1 Compare Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.2 Copy Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.3 Fill Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.1.4 Swap Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2 Bit Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.1 Read Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2.2 Write Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.3 Copy Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.4 Compare Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.2.5 Copy Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.2.6 Fill Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2.7 Swap Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2.8 Count Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Page 2 of 236
Contents
4 Peripheral Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1 General Purpose Inputs/Outputs (GPIOs) . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.1 Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1.2 Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.2 Basic Port Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2.1 Set GPIOs to Logical Level . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2.2 Toggle GPIOs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2.3 Waveform Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.1.2.4 Read GPIOs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.3 Higher Level Port Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.3.1 Send Data in Wiegand Format . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.3.2 Send Data in Omron Format . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2 Beeper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.3 LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.3.1 General Purpose LED Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.3.1.1 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.3.1.2 Set LEDs On/Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.3.1.3 Toggle LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.3.1.4 Blink LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.3.2 Diagnostic LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.3.2.1 Set Diagnostic LED On/Off . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.3.2.2 Toggle Diagnostic LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.3.2.3 Get LED State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5 Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.1 Hexadecimal ASCII to Binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.1.1 Scan Hexadecimal Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.1.2 Scan Hexadecimal String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.2 Binary to Hexadecimal ASCII . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6 I2C Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.1 Initialization/Deinitialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.1.1 I2CInit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.1.2 I2CDeInit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.1.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.2 Communication (Master) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.2.1 I2CMasterStart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.2.2 I2CMasterStop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2.3 I2CMasterTransmitByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2.4 I2CMasterReceiveByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2.5 I2CMasterBeginWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2.6 I2CMasterBeginRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.2.7 I2CMasterSetAck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.2.8 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.3 Communication (Slave) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.3.1 Slave to Master . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.3.2 Master to Slave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.3.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7 SPI Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.1 Slave Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.1.1 Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Page 3 of 236
Contents
Page 4 of 236
Contents
Page 5 of 236
Contents
Page 6 of 236
Contents
Page 7 of 236
Contents
Page 8 of 236
Contents
Page 9 of 236
Contents
Page 10 of 236
Contents
Page 11 of 236
1 System Functions
1 System Functions
1.1 SysCall
This function is useful for writing interfaces, which do a remote call of a system function,
bool SysCall(TEnvSysCall *Env);
Parameters:
TEnvSysCall *Env Pointer to a structure which specifies parameters of the functions to be
called.
Return: If the function has been called the return value is true, otherwise it is false.
In this case the specified function does not exist.
1.2 Reset
This functions is performing a reset of the firmware, which also includes a restart of the currently running
App.
void Reset(void);
Parameters: None.
Return: None.
1.3 StartBootloader
This function is performing a manual call of the boot loader. As a consequence the execution of the App is
stopped.
void StartBootloader(void);
Parameters: None.
Return: None.
1.4 GetSysTicks
Retrieve number of system ticks, specified in multiple of 1 milliseconds, since startup of the firmware.
unsigned long GetSysTicks(void);
Page 12 of 236
1 System Functions
Parameters: None.
Return: Number of system ticks since startup of the firmware. The returned value
will restart at 0 after 232 system ticks (around 1193 hours).
1.5 GetVersionString
Parameters:
char *VersionString Pointer to an array of characters, which will receive the version information.
int MaxLen Maximum number of characters, the specified byte array can receive exclud-
ing the 0-termination.
Return: Length of the returned string excluding the 0-termination.
Example:
// This sample demonstrates, how to send the version string
// to the host
void WriteChar(char Char)
{
HostWriteByte(Char);
}
void WriteString(const char *String)
{
while (*String)
WriteChar(*String++);
}
void WriteVersion(void)
{
char Version[30+1];
GetVersionString(Version,sizeof(Version)-1);
WriteString(Version);
}
1.6 GetUSBType
Retrieve type of USB communication. This could by keyboard emulation or CDC emulation or some other
value for future or custom implementations.
int GetUSBType(void);
Page 13 of 236
1 System Functions
Parameters: None.
Return: USBTYPE_NONE: No USB stack,
USBTYPE_CDC: CDC device (virtual COM port),
USBTYPE_KEYBOARD: HID keyboard,
USBTYPE_CCID_HID: CCID + HID (compound device),
USBTYPE_REPORTS: CCID + HID reports,
USBTYPE_CCID_CDC: CCID + CDC (compound device),
USBTYPE_CCID: CCID
1.7 GetDeviceType
Parameters: None.
Return: DEVTYPE_LEGICNFC: TWN4 LEGIC, DEVTYPE_MIFARENFC: TWN4 MIFARE
1.8 Sleep
The device enters the sleep state for a specified time. During sleep state, the device reduces the current
consumption to a value, which depends on the mode of sleep.
int Sleep(unsigned long Ticks,unsigned long Flags)
Parameters:
unsigned long Ticks Time, specified in milliseconds, the device should enter the sleep state.
unsigned long Flags Events, which cause the function immediately to return. The parameter is a
bitwise OR of all events to be handled.
Return: See table return values below
The sleep mode can optionally be cancelled by events. The events are bitwise or-combined and are
specified as parameters in the call of the function Sleep. Following events are defined:
Page 14 of 236
1 System Functions
Depending on the source, which woke up the device, Sleep returns following values:
1.9 GetDeviceUID
This function returns a UID, which is unique to the specific TWN4 device.
void GetDeviceUID(byte *UID)
Parameters:
byte *UID Pointer ro an array of bytes, which receives 12 bytes. These 12 bytes repre-
sent the UID of the device.
Return: None.
1.10 SetParameters
This function allows to set parameters, which influence the behaviour of the TWN4 firmware. See also
chapter System Parameters for a description of the TLV list and all available paramaters.
bool SetParameters(const byte *TLV,int ByteCount)
Parameters:
const byte *TLV Pointer to an array of bytes, which contains the TLV list.
int ByteCount Length counted in bytes, the TLV list contains.
Return: The function returns true, if the parameters was set to the new value. Oth-
erwise the function returns false.
Example:
Page 15 of 236
1 System Functions
int main(void)
{
// ...
SetParameters(TLVBytes,sizeof(TLVBytes));
// ...
}
1.11 GetLastError
This function allows to read the last error code, which was generated by any system function. For a list of
available error code see chapter System Errors.
unsigned int GetLastError(void)
Parameters: None.
Return: The error code.
Page 16 of 236
2 I/O Functions
2 I/O Functions
2.1 Configuration
This function can be used to configure the asynchronous serial communication ports COM1 and COM2.
bool SetCOMParameters
(
int Channel,
TCOMParameters* COMParameters
);
Parameters:
int Channel Specify the communication port which shall be configured. Use one of the
predefined constants CHANNEL_COM1 or CHANNEL_COM2.
TCOMParameters* Reference to the structure that holds the communication parameters. See
COMParameters the description of TCOMParameters for details.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 17 of 236
2 I/O Functions
This function returns the functional state of the USB-controller in case the reader is running as USB-device.
int GetUSBDeviceState(void);
Parameters: None.
Return: Depending on the functional state, the return value is one of the prede-
fined constants USB_DEVICE_STATE_NOTINIT, USB_DEVICE_STATE_DEFAULT,
USB_DEVICE_STATE_ADDRESSED, USB_DEVICE_STATE_CONFIGURED or
USB_DEVICE_STATE_SUSPENDED.
This function returns the channel, which is actually configured for host communication.
int GetHostChannel(void);
Parameters: None.
Return: The return value is one of the predefined constants CHANNEL_NONE,
CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_I2C CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4 Mini
Reader.
Note: TWN4 Mini Reader has connected the internal communication lines of USB, COM1 and SPI to one
physical port. This means, only one of these communication channels can be active at the same time. The
resulting communication channel is CHANNEL_HOST.
This function allows to remotely wake up a host, which is connected via USB. This function is supported
by USB keyboard only.
void USBRemoteWakeup(void);
Parameters: None.
Return: None.
Use this function to retrieve the input/output buffer size of a specific communication channel.
Page 18 of 236
2 I/O Functions
int GetBufferSize
(
int Channel,
int Dir
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
int Dir Specify the direction. Use one of the predefined constants DIR_OUT or
DIR_IN.
Return: The buffer size in bytes.
Use this function to retrieve the number of bytes that are actually stored in the respective I/O buffer. In
case of querying the output direction, the functions returns the number of bytes that have not been sent
yet, in case of the input direction the number of available bytes that can be read is returned.
int GetByteCount
(
int Channel,
int Dir
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
int Dir Specify the direction. Use one of the predefined constants DIR_OUT or
DIR_IN.
Return: The number of bytes that are stored in the buffer.
bool TestEmpty
(
int Channel,
int Dir
);
Page 19 of 236
2 I/O Functions
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
int Dir Specify the direction. Use one of the predefined constants DIR_OUT or
DIR_IN.
Return: If the buffer is empty, the return value is true, otherwise it is false.
Check if the specified I/O buffer can receive any further data.
bool TestFull
(
int Channel,
int Dir
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
int Dir Specify the direction. Use one of the predefined constants DIR_OUT or
DIR_IN.
Return: If the buffer is full, the return value is true, otherwise it is false.
Use this function to send one byte through a specific communication channel. If the respective output
buffer is completely occupied, the function blocks until there is enough space.
void WriteByte
(
int Channel,
byte Byte
);
Page 20 of 236
2 I/O Functions
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_SPI or CHANNEL_HOST. Note that
CHANNEL_HOST is only available on TWN4 Mini Reader.
byte Byte The byte to be sent.
Return: None.
Use this function to send multiple bytes through a specific communication channel. If there is not enough
space in the respective output buffer, the function sends the number of bytes that fit into the buffer and
returns this value.
int WriteBytes
(
int Channel,
const byte* Bytes,
int ByteCount
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_SPI or CHANNEL_HOST. Note that
CHANNEL_HOST is only available on TWN4 Mini Reader.
const byte* Bytes The bytes to be sent.
Return: Number of bytes sent.
Use this function to read a byte from the input buffer of a specific communication channel. If there is no
byte available, the function blocks until there is one.
byte ReadByte
(
int Channel
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
Return: The byte which was read from the input buffer.
Page 21 of 236
2 I/O Functions
Use this function to read a desired number of bytes from the input buffer of a specific communication
channel. If there is less data available than desired, the function reads the available number of bytes.
int ReadBytes
(
int Channel,
byte* Bytes,
int ByteCount
);
Parameters:
int Channel Specify the communication channel. Use one of the predefined con-
stants CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2, CHANNEL_CCID_DATA,
CHANNEL_CCID_CTRL, CHANNEL_I2C, CHANNEL_RNG, CHANNEL_SPI or
CHANNEL_HOST. Note that CHANNEL_HOST is only available on TWN4
Mini Reader.
byte* Bytes The received data is stored in this buffer.
int ByteCount Specify the number of bytes to be read.
Return: The byte which was read from the input buffer.
Page 22 of 236
3 Memory Functions
3 Memory Functions
bool CompBytes
(
const byte* Data1,
const byte* Data2,
int ByteCount
);
Parameters:
const byte* Data1 Reference to an array of bytes.
const byte* Data1 Reference to an array of bytes.
int ByteCount Number of bytes (beginning from index 0) to be compared.
Return: If the two arrays are identical, the return value is true, otherwise it is false.
Copy bytes from a source to a destination. Source and destination may be identical and the source section
may overlap the destination. Depending on that, the correct method for copying will be chosen.
void CopyBytes
(
byte* DestBytes,
const byte* SourceBytes,
int ByteCount
);
Parameters:
byte* DestBytes Reference to an array of bytes which is the destination of the copy operation.
const byte* SourceBytes Reference to an array of bytes which is the source of the copy operation.
int ByteCount Number of bytes to be copied.
Return: None.
Page 23 of 236
3 Memory Functions
void FillBytes
(
byte* Dest,
byte Value,
int ByteCount
);
Parameters:
byte* Dest Reference to an array of bytes which is the destination for the operation.
byte Value The byte value with which the array will be filled.
int ByteCount Number of bytes to be filled.
Return: None.
void SwapBytes
(
byte* Data,
int ByteCount
);
Parameters:
byte* Data Reference to an array of bytes which is the destination for the operation.
int ByteCount Number of bytes to be swapped.
Return: None.
Bit operations are working on bit fields. A bit field is represented by an array of bytes. The diagram below
shows how bit operations are interpreting a given bit offset within an array of bytes:
Page 24 of 236
3 Memory Functions
bool ReadBit
(
const byte* Byte,
int BitNr
);
Parameters:
const byte* Byte Reference to an array of bytes which represents the bit field where one bit
shall be read.
int BitNr Position of the bit within the bit field.
Return: The bit value: true means 1, false means 0.
void WriteBit
(
byte* Byte,
int BitNr,
bool Value
);
Parameters:
byte* Byte Reference to an array of bytes which represents the bit field where one bit
shall be written.
int BitNr Position within the bit field, where the bit is to be written.
bool Value The bit value: true means 1, false means 0.
Return: None.
Copy one single bit from a source to a destination. Source and destination may be identical.
void CopyBit
(
byte* Dest,
int DestBitNr,
const byte* Source,
int SourceBitNr
);
Page 25 of 236
3 Memory Functions
Parameters:
byte* Dest Reference to an array of bytes which is the destination for the operation.
int DestBitNr Position within the destination bit field, where the bit is copied to.
const byte* Source Reference to an array of bytes which is the source for the operation.
int SourceBitNr Position within the source bit field, where the bit is copied from.
Return: None.
bool CompBits
(
const byte* Data1,
int Data1StartBit,
const byte* Data2,
int Data2StartBit,
int BitCount
);
Parameters:
const byte* Data1 Reference to an array of bytes which represents a bit field.
int Data1StartBit Start-index (beginning from 0) of the first bit field.
const byte* Data2 Reference to an array of bytes which represents a bit field.
int Data1StartBit Start-index (beginning from 0) of the second bit field.
int BitCount Number of bits to be compared.
Return: If the two bit-sets are identical, the return value is true, otherwise it is false.
Copy bits from a source to a destination. Source and destination may be identical and the source section
may overlap the destination. Depending on that, the correct method for copying will be chosen.
void CopyBits
(
byte* DestBits,
int StartDestBit,
const byte* SourceBits,
int StartSourceBit,
int BitCount
);
Page 26 of 236
3 Memory Functions
Parameters:
byte* DestBits Reference to an array of bytes which represents a bit field which is the des-
tination of the copy operation.
int StartDestBit First bit within the destination bit field where the bits are copied to.
const byte* SourceBits Reference to an array of bytes which represents a bit field which is the
source of the copy operation.
int StartSourceBit First bit within the source bit field where the bits are copied from.
int BitCount Number of bits to be copied.
Return: None.
void FillBits
(
byte* Dest,
int StartBit,
bool Value,
int BitCount
);
Parameters:
byte* Dest Reference to an array of bytes which represents a bit field which is the des-
tination for the operation.
int StartBit First bit within the bit field where the bits are filled.
bool Value The bit value: true means 1, false means 0.
int BitCount Number of bits to be filled.
Return: None.
void SwapBits
(
byte* Data,
int StartBit,
int BitCount
);
Page 27 of 236
3 Memory Functions
Parameters:
byte* Data Reference to an array of bytes which represents a bit field which is the des-
tination for the operation.
int StartBit First bit within the bit field where bits are swapped.
int BitCount Number of bits to be swapped.
Return: None.
int CountBits
(
const byte* Data,
int StartBit,
bool Value,
int BitCount
);
Parameters:
const byte* Data Reference to an array of bytes which represents a bit field.
int StartBit First bit within the bit field where counting shall start.
bool Value The bit value: true means count ones, false means count zeros.
int BitCount Size of the bit field.
Return: Number of counted bits.
Page 28 of 236
4 Peripheral Functions
4 Peripheral Functions
4.1.1 Configuration
4.1.1.1 Outputs
Use this function to configure one or several GPIOs as output. Each output can be configured to have an
integrated pull-up or pull-down resistor. The output driver characteristic is either Push-Pull or Open Drain.
void GPIOConfigureOutputs
(
int Bits,
int PullUpDown,
int OutputType
);
Parameters:
int Bits Specify the GPIOs that shall be configured for output. Several GPIOs can
be configured simultaneously by using the bitwise or-operator (|). Use the
predefined constants GPIO0 through GPIO7 for specifying the GPIOs.
int PullUpDown Specify the behaviour of the internal weak pull-up/down resistor. Use
one of the predefined constants GPIO_PUPD_NOPULL, GPIO_PUPD_PULLUP or
GPIO_PUPD_PULLDOWN.
int OutputType Specify the output driver characteristic. Use one the predefined constants
GPIO_OTYPE_PUSHPULL or GPIO_OTYPE_OPENDRAIN.
Return: None.
4.1.1.2 Inputs
Use this function to configure one or several GPIOs as input. Each output can be configured to have an
integrated pull-up or pull-down resistor, alternatively it can be left floating.
void GPIOConfigureInputs
(
int Bits,
int PullUpDown
);
Page 29 of 236
4 Peripheral Functions
Parameters:
int Bits Specify the GPIOs that shall be configured for input. Several GPIOs can
be configured simultaneously by using the bitwise or-operator (|). Use the
predefined constants GPIO0 through GPIO7 for specifying the GPIOs.
int PullUpDown Specify the behaviour of the internal weak pull-up/down resistor. Use
one of the predefined constants GPIO_PUPD_NOPULL, GPIO_PUPD_PULLUP or
GPIO_PUPD_PULLDOWN.
Return: None.
Use this function to set one or several GPIOs to logical high or low level. The respective ports must have
been configured to output in advance.
Parameters:
int Bits Specify the GPIOs that shall be set to a logical level. Several GPIOs can
be handled simultaneously by using the bitwise or-operator (|). Use the
predefined constants GPIO0 through GPIO7 for specifying the GPIOs.
Return: None.
Use this function to toggle the logical level of one or several GPIOs. The respective ports must have been
configured to output in advance.
void GPIOToggleBits
(
int Bits
);
Parameters:
int Bits Specify the GPIOs that shall be toggled. Several GPIOs can be handled
simultaneously by using the bitwise or-operator (|). Use the predefined con-
stants GPIO0 through GPIO7 for specifying the GPIOs.
Return: None.
Use this function to generate a pulse-width modulated square waveform with constant frequency on one
or several GPIOs. The respective ports must have been configured to output in advance.
Page 30 of 236
4 Peripheral Functions
void GPIOBlinkBits
(
int Bits,
int TimeHi,
int TimeLo
);
Parameters:
int Bits Specify the GPIOs that shall generate the waveform. Several GPIOs can
be handled simultaneously by using the bitwise or-operator (|). Use the
predefined constants GPIO0 through GPIO7 for specifying the GPIOs.
int TimeHi Specify the duration for logical high level in milliseconds.
int TimeLo Specify the duration for logical low level in milliseconds.
Return: None.
Use this function to read the logical level of one GPIO that has been configured as input.
int GPIOTestBit
(
int Bit
);
Parameters:
int Bits Specify the GPIO that shall be read. Use one of the predefined constants
GPIO0 through GPIO7 for specifying the GPIO.
Return: If the GPIO has logical high level, the return value is 1, otherwise it is 0.
Use this function to send a bitstream via a software emulated Wiegand interface. A Wiegand interface
uses two data lines, one line is used to transmit ones, the other one is used to transmit zeros. Each GPIO
can be individually configured to act as data line. Note that the integrated API LED-functions are working
with GPIO0 to GPIO2 by default, so the Wiegand data lines should be selected carefully.
Page 31 of 236
4 Peripheral Functions
Parameters:
int GPIOData0 Specify the GPIO that shall be used to transmit zeros. Use one of the pre-
defined constants GPIO0 through GPIO7 for specifying the GPIO.
int GPIOData1 Specify the GPIO that shall be used to transmit ones. Use one of the prede-
fined constants GPIO0 through GPIO7 for specifying the GPIO.
int PulseTime Specify the pulse duration in microseconds.
int IntervalTime Specify the duration in microseconds between consecutive pulses.
byte* Bits Reference to an array of bytes which represents a bit field which holds the
data to be sent.
int BitCount Specify the number of bits to be sent.
Return: None.
See timing diagram below for details about how the timing values are used:
Example:
Here is an example which shows minimum code for doing a Wiegand output:
// Init Section:
// Use GPIO2 and GPIO3 for Wiegand interface
GPIOConfigureOutputs(GPIO2 | GPIO3,GPIO_PUPD_NOPULL,GPIO_OTYPE_PUSHPULL);
// Enter idle level. In this case we have active low outputs
GPIOSetBits(GPIO2 | GPIO3);
// Prepare some Wiegand data:
byte Bits[4];
Bits[0] = 0x12;
Bits[1] = 0x34;
Bits[2] = 0x56;
Bits[3] = 0x78;
// Now send the bits
SendWiegand(GPIO2,GPIO3,100,1000,Bits,32);
Note:
• It is up to the App to complete Wiegand data with parity bits and decide number of bits. In this way
the App is fully flexible regarding data to be sent.
• The idle level of the Wiegand interface is determined by state of the outputs before calling SendWiegand.
It must be setup by a separate call to GPIOSetBits or GPIOClearBits depending on the require-
ments of the underlying hardware.
• The GPIOs might need additional circuitry against shortcut or voltage level depending on the in-
tended application.
Page 32 of 236
4 Peripheral Functions
Use this function to send a bit stream via a software-emulated Omron interface. An Omron interface
uses two lines for data transmission, one for clock and one for the data bit stream. Each GPIO can be
individually configured to act as data or clock line. Note that the integrated API LED-functions are working
with GPIO0 to GPIO2 by default, so the Omron interface lines should be selected carefully.
void SendOmron(int GPIOClock,int GPIOData,int T1,int T2,int T3,
byte* Bits,int BitCount);
Parameters:
int GPIOClock Specify the GPIO that shall be used for generating the clock signal. Use one
of the predefined constants GPIO0 through GPIO7 for specifying the GPIO.
int GPIOData Specify the GPIO that shall be used for data transmission. Use one of the
predefined constants GPIO0 through GPIO7 for specifying the GPIO.
int T1
int T2
int T3
byte* Bits Reference to an array of bytes which represents a bit field which holds the
data to be sent.
int BitCount Specify the number of bits to be sent.
Return: None.
See timing diagram below for details about how the timing values are used:
Example:
Here is an example which shows minimum code for doing a clock/data output:
// Init Section:
// Use GPIO2 and GPIO3 for the clock/data interface
GPIOConfigureOutputs(GPIO2 | GPIO3,GPIO_PUPD_NOPULL,GPIO_OTYPE_PUSHPULL);
// Enter idle level. In this case we have active low outputs
GPIOSetBits(GPIO2 | GPIO3);
// Prepare some data:
byte Bits[4];
Bits[0] = 0x12;
Bits[1] = 0x34;
Bits[2] = 0x56;
Bits[3] = 0x78;
// Now send the bits
SendOmron(GPIO2,GPIO3,500,1000,500,Bits,32);
Note:
Page 33 of 236
4 Peripheral Functions
• It is up to the App to complete data with parity bits and decide number of bits. In this way the App is
fully flexible regarding data to be sent.
• The idle level of the clock/data interface is determined by state of the outputs before calling SendOmron.
It must be setup by a separate call to GPIOSetBits or GPIOClearBits depending on the require-
ments of the underlying hardware.
• The GPIOs might need additional circuitry against shortcut or voltage level depending on the in-
tended application.
4.2 Beeper
void Beep
(
int Volume,
int Frequency,
int OnTime,
int OffTime
);
Parameters:
int Volume Specify the volume in percent from 0 to 100.
int Frequency Specify the frequency in Hertz.
int OnTime Specify the duration of the beep in milliseconds.
int OffTime Specify the length of the pause after the beep. This is useful for generating
melodies. If this is not required, the parameter may have the value 0.
Return: None.
4.3 LEDs
These functions are related for usage with TWN4 Desktop where the different LEDs have a dedicated
connection scheme. The LEDs are connected as follows:
• GPIO0 → Red
• GPIO1 → Green
• GPIO2 → Yellow
4.3.1.1 Initialization
Page 34 of 236
4 Peripheral Functions
Parameters:
int LEDs Specify the GPIOs that shall be configured for LED operation. Several
GPIOs can be configured simultaneously by using the bitwise or-operator
(|). Use the predefined constants REDLED, GREENLED or YELLOWLED for speci-
fying the GPIOs.
Return: None.
Parameters:
int LEDs Specify the LEDs that shall be set on/off. Several LEDs can be handled
simultaneously by using the bitwise or-operator (|). Use the predefined con-
stants REDLED, GREENLED or YELLOWLED for specifying the LEDs.
Return: None.
Parameters:
int LEDs Specify the LEDs that shall be toggled. Several LEDs can be handled simul-
taneously by using the bitwise or-operator (|). Use the predefined constants
REDLED, GREENLED or YELLOWLED for specifying the LEDs.
Return: None.
Page 35 of 236
4 Peripheral Functions
Parameters:
int LEDs Specify the LEDs that shall blink. Several LEDs can be handled simulta-
neously by using the bitwise or-operator (|). Use the predefined constants
REDLED, GREENLED or YELLOWLED for specifying the LEDs.
int TimeOn Specify the on-time in milliseconds.
int TimeOff Specify the off-time in milliseconds.
Return: None.
The TWN4 Core Module has one integrated LED that can be used for diagnostic purposes. There is no
initialization necessary.
void DiagLEDOn(void);
void DiagLEDOff(void);
Parameters: None.
Return: None.
void DiagLEDToggle(void);
Parameters: None.
Return: None.
bool DiagLEDIsOn(void);
Parameters: None.
Return: If the diagnostic LED is on, the return value is true, otherwise it is false.
Page 36 of 236
5 Conversion Functions
5 Conversion Functions
Convert an ASCII-character which represents a hexadecimal number into its binary representation.
int ScanHexChar
(
byte Char
);
Parameters:
byte Char ASCII-coded hexadecimal character. The input value may be one of the
characters ’0’-’9’, ’a’-’f’ or ’A’-’F’.
Return: If the character is a valid hexadecimal expression, the return value is the
binary representation (a number between 0 and 15), else it is -1.
Convert an array of bytes containing ASCII characters which represents hexadecimal numbers into their
binary representation. The conversion is done in place. This means that after successful conversion,
number of valid bytes is half of the given count of ASCII characters (two hex digits represent one binary
byte).
int ScanHexString
(
byte* ASCII,
int ByteCount
);
Parameters:
byte* ASCII Reference to an array of ASCII-coded hexadecimal characters. The array
may contain the characters ’0’-’9’, ’a’-’f’ or ’A’-’F’. The array is also the desti-
nation for the operation.
int ByteCount Number of (ASCII-) bytes to be converted.
Return: Number of successfully converted bytes.
Page 37 of 236
5 Conversion Functions
Convert a number, which is given as a bit field into ASCII format, and store it in an array of bytes. The
conversion is made in the following sequence:
1. Convert the binary data to a number of digits, which is determined by the parameter MaxDigits. If
MaxDigits is 0, then the number of digits is determined by the binary data itself.
2. If the result of the conversion is less than the number of digits specified by MinDigits, precede the
converted number with zeros according to MinDigits.
int ConvertBinaryToString
(
const byte* SourceBits,
int StartBit,
int BitCnt,
char* String,
int Radix,
int MinDigits,
int MaxDigits
);
Parameters:
const byte* SourceBits A reference to an array of bytes, which contains the bit field.
int StartBit Index of the first bit to be converted.
int BitCnt The number of bits, which are valid within the array of bytes.
char* String A reference to an array of bytes, which receives the result of the conversion.
int Radix Base for conversion, use:
• 2 for binary conversion
• 8 for octal conversion
• 10 for decimal conversion
• 16 for hexadecimal conversion
int MinDigits Specifies the minimum number of digits, the output should contain. If
MinDigits is 0, then at least 1 digit is sent. If MinDigits is greater than the
actual width of the number to be converted, then the number is preceded by
zeros.
int MaxDigits Specifies the maximum number of digits, the output may contain. MaxDigits
has higher priority than MinDigits.
Return: The actual number of ASCII bytes, which has been stored in the array
String.
Page 38 of 236
6 I2C Functions
6 I2C Functions
This chapter describes functions for accessing the I2C interface of TWN4. I2C is also known as TWI
(Two-Wire Interface).
6.1 Initialization/Deinitialization
6.1.1 I2CInit
Parameters:
int Mode This value specifies the mode of operation.
Return: If the operation was successful, the return value is true, otherwise it is
false.
6.1.2 I2CDeInit
void I2CDeInit(void);
Parameters: None.
Return: None.
6.1.3 Examples
// Initialize as master
I2CInit(I2CMODE_MASTER);
// Initialize as slave.
// I2CMODE_SLAVE: Setup interface as slave
// 0x30: Address of of this slave
// I2CMODE_CHANNEL: Do communication via channels (this is the
// only currently available option, therefore
// a must to be specified)
I2CInit(I2CMODE_SLAVE | 0x30 | I2CMODE_CHANNEL);
6.2.1 I2CMasterStart
Parameters: None.
Return: None.
Page 39 of 236
6 I2C Functions
6.2.2 I2CMasterStop
Parameters: None.
Return: None.
6.2.3 I2CMasterTransmitByte
Parameters:
byte Byte The byte to be transmitted to the slave.
Return: None.
6.2.4 I2CMasterReceiveByte
Parameters: None.
Return: The byte read from the slave.
6.2.5 I2CMasterBeginWrite
Begin a write sequence. This will send the target slave address together with R/W-bit set to write.
void I2CMasterBeginWrite(int Address);
Parameters:
int Address The target slave address, a value from 0 to 127.
Return: None.
6.2.6 I2CMasterBeginRead
Begin a read sequence. This will send the target slave address together with R/W-bit set to read.
void I2CMasterBeginRead(int Address);
Parameters:
int Address The target slave address, a value from 0 to 127.
Return: None.
Page 40 of 236
6 I2C Functions
6.2.7 I2CMasterSetAck
Set ACK state of the master. This ACK will be sent after receiption of one byte from the slave.
void I2CMasterSetAck(bool SetOn);
Parameters:
bool SetOn Set this value to true to turn acknowledge on or false to turn acknowledge
off. Definitions ON or OFF may be used for better readability.
Return: None.
6.2.8 Examples
Communication as a I2C slaves works with well-defined I2C packets, which must be sent between master
and slave (TWN4).
The communication is performed via normal communication channels. Therefore, for transmitting and
receiving data, the normal IO-functions must be used. These are WriteByte, ReadByte and so on. In
case of communication via I2C, the channel 4 must be used. There is a definition for this channel, which
is CHANNEL_I2C.
As a conclusion, TWN4 offers a easy method of changing communication from USB or RS232 to I2C just
by changing the communication channel. Only care must be taken to avoid buffer overflow. This can be
Page 41 of 236
6 I2C Functions
achieved by calling appropriate IO-functions TestEmpty and TestFull. On the other hand many commu-
nication protocols avoid a buffer overflow by their inherent flow of communication (e.g. command/response
protocol).
The specification for the format of the packets sent/reveived on the I2C bus is as follows:
1 Byte Address/Read
1 Byte Buffer status: Bits 7..4 hold the number of bytes, which are available to be
read from the slave. Bits 3..0 hold the maximum number of bytes, which
may be sent to slave.
n Bytes Payload, where n is 0..15. Note: Due to the fact, that ACK must be turned
off one byte before the master receives last byte, it is useful to check buffer
status and receive bytes in separate read operations.
1 Byte Address/Write
n Bytes Payload, where n is 1..15
6.3.3 Examples
This is a implementation of a I2C master communication, which routes USB- or RS232-interface to the
I2C-interface of a TWN4 Core Module. In order to test this example, two TWN4 Core Modules are re-
quired:
• 1 TWN4 Core Module, which is running as I2C slave
• 1 TWN4 Core Module, which is running as I2C master.
//
// TWN4 App: I2C master, which routes USB or RS232-traffic to I2C
//
#include "twn4.sys.h"
#include "apptools.h"
int main(void)
{
const int I2CAddress = 0x30;
// USB or RS232 depends on which cable is connected
int HostChannel = GetHostChannel();
I2CInit(I2CMODE_MASTER);
while (true)
{
int I2CRXTXCount;
int TransferCount;
I2CMasterStart();
I2CMasterBeginRead(I2CAddress);
I2CMasterSetAck(OFF);
Page 42 of 236
6 I2C Functions
I2CRXTXCount = I2CMasterReceiveByte();
I2CMasterStop();
// **********************************************************
// ****** Direction Host -> I2C *****************************
// **********************************************************
TransferCount = MIN(GetByteCount(HostChannel,DIR_IN),
I2CRXTXCount & 0x0F);
if (TransferCount > 0)
{
I2CMasterStart();
I2CMasterBeginWrite(I2CAddress);
while (TransferCount-- > 0)
I2CMasterTransmitByte(ReadByte(HostChannel));
I2CMasterStop();
}
// **********************************************************
// ****** Direction I2C -> Host *****************************
// **********************************************************
TransferCount = MIN(GetBufferSize(HostChannel,DIR_OUT)-
GetByteCount(HostChannel,DIR_OUT),
I2CRXTXCount >> 4);
if (TransferCount > 0)
{
I2CMasterStart();
I2CMasterBeginRead(I2CAddress);
I2CMasterSetAck(ON);
// Flush RX/TX byte count
I2CMasterReceiveByte();
// Read data except last byte
while (TransferCount-- > 1)
WriteByte(HostChannel,I2CMasterReceiveByte());
// Turn off ACK before reading last byte
I2CMasterSetAck(OFF);
WriteByte(HostChannel,I2CMasterReceiveByte());
I2CMasterStop();
}
}
}
Page 43 of 236
7 SPI Functions
7 SPI Functions
This chapter describes functions for accessing the SPI interface of TWN4. The SPI interface can be
operated as master or slave.
To operate the SPI interface in slave mode, it is only necessary to configure SPI for slave mode using
the function SPIInit. All data transfer is done using the respective I/O functions via channel CHANNEL_SPI
(Core/Nano based readers) or CHANNEL_HOST (Mini Reader).
7.1.1 Timing
1 11
SS
9 10
2
SCK
3 4 6 7 8
MOSI
MSB LSB
5
12
MISO
MSB LSB X X
Page 44 of 236
7 SPI Functions
Communication with a TWN4 in SPI slave mode is conducted with well-defined SPI packets, which must
be exchanged between master and slave. After a falling edge of the SS line, a communication frame can
be initiated. The first exchanged byte is a buffer status byte which gives information about the communi-
cation buffer of the master and the slave respectively, see the sections below for details. A rising edge on
SS signals the end of the communication frame.
1 Byte Buffer status: Bits 7..4 hold the number of bytes, which are available to be
read from the slave. Bits 3..0 hold the maximum number of bytes, which
may be sent to slave.
n Bytes Payload, where n is 0..15.
Page 45 of 236
7 SPI Functions
{
if (Byte & 0x80)
GPIO_MOSI_HIGH();
else
GPIO_MOSI_LOW();
GPIO_SCK_HIGH();
Byte <<= 1;
if (GPIO_MISO_TEST())
Byte |= 1;
GPIO_SCK_LOW();
}
return Byte;
}
int main(void)
{
GPIOConfigureOutputs(GPIO_MOSI | GPIO_SCK | GPIO_SS, GPIO_PUPD_NOPULL, GPIO_OTYPE_PUSHPULL);
GPIOConfigureInputs(GPIO_MISO, GPIO_PUPD_NOPULL);
while (true)
{
// Query buffer status of SPI slave
GPIO_SS_LOW();
byte SPIRXTXCount = SPIReadWrite(0x00);
GPIO_SS_HIGH();
7.2 Initialization/Deinitialization
7.2.1 SPIInit
Page 46 of 236
7 SPI Functions
Parameters:
const TSPIParameters Pointer to a structure, which specifies mode of operation.
*SPIParameters
Return: If the operation was successful, the return value is true, otherwise it is
false.
The members of structure TSPIParameters are defined as follows:
7.2.2 SPIDeInit
Parameters: None.
Return: None.
7.3 Communication
7.3.1 SPIMasterBeginTransfer
Begin a transfer via SPI interface in master mode. This function sets signal SPI_SS- to active, thus
low.
void SPIMasterBeginTransfer(void);
Page 47 of 236
7 SPI Functions
Parameters: None.
Return: None.
7.3.2 SPIMasterEndTransfer
End a transfer via SPI interface in master mode. This function sets signal SPI_SS- to inactive, thus
high.
void SPIMasterEndTransfer(void);
Parameters: None.
Return: None.
7.3.3 SPITransceive
Send and receive a number of bytes to/from the slave. Background: SPI is a full duplex communication
link. This allows to send and receive data at the same time. With every clock pulse, a bit is sent to the
slave, another bit is received from the slave.
bool SPITransceive(const byte *TXData,byte *RXData,int ByteCount);
Parameters:
const byte *TXData Pointer to an array of bytes being transmitted to the slave.
byte *RXData Pointer to an array of bytes being received from the slave.
int ByteCount Number of bytes transferred in each direction.
Return: If the operation was successful, the return value is true, otherwise it is
false.
7.3.4 SPITransmit
Parameters:
const byte *TXData Pointer to an array of bytes being transmitted to the slave.
int ByteCount Number of bytes transmitted.
Return: If the operation was successful, the return value is true, otherwise it is
false.
7.3.5 SPIReceive
Receive a number of bytes from the slave. Transmitted bits are set to zero.
bool SPIReceive(byte *RXData,int ByteCount);
Page 48 of 236
7 SPI Functions
Parameters:
byte *RXData Pointer to an array of bytes being received from the slave.
int ByteCount Number of bytes received.
Return: If the operation was successful, the return value is true, otherwise it is
false.
7.4 Examples
#include "twn4.sys.h"
void FuncSPIInitMaster(void)
{
const TSPIParameters Mode =
{
SPI_MODE_MASTER,
SPI_CPOL_LOW,
SPI_CPHA_EDGE1,
SPI_CLOCKRATE_15_MHZ,
SPI_FIRSTBIT_MSB
};
SPIInit(&Mode);
}
void FuncSPITransmitPacket(void)
{
SPIMasterBeginTransfer();
static const byte TXData[4] = { ’A’,’B’,’C’,’D’ };
SPITransmit(TXData,4);
SPIMasterEndTransfer();
}
void FuncSPIReceivePacket(void)
{
SPIMasterBeginTransfer();
byte RXData[4];
SPIReceive(RXData,4);
SPIMasterEndTransfer();
}
void FuncSPITransceivePacket(void)
{
SPIMasterBeginTransfer();
static const byte TXData[4] = { ’A’,’B’,’C’,’D’ };
byte RXData[4];
SPITransceive(TXData,RXData,4);
SPIMasterEndTransfer();
}
Page 49 of 236
8 RF Functions
8 RF Functions
8.1 SearchTag
Use this function to search a transponder in the reading range of TWN4. TWN4 is searching for all types
of transponders, which have been specified via function SetTagTypes. If a transponder has been found,
tag type, length of ID and ID data itself are returned.
bool SearchTag(int *TagType,int *IDBitCount,byte *ID,int MaxIDBytes);
Parameters: None.
int *TagType Pointer to an integer, which receives the type of tag, which has been found.
int *IDBitCount Pointer to an integer, which receives the number of bits(!), the ID consists of.
byte *ID Pointer to an array of bytes, which contain ID data, if a transponder has been
found.
int MaxIDBytes A value, which specifies the buffer size of ID. No more than this specified
number of bytes will be copied to the location specified by ID.
Return: If a transponder has been found, the function returns true, otherwise it
returns false.
8.2 SetRFOff
Turn off RF field. If no further operations are required on a transponder found via function SearchTag you
may use this command to minimize power consumption of TWN4.
void SetRFOff(void);
Parameters: None.
Return: None.
8.3 SetTagTypes
Use this function to configure the transponders, which are searched by function SearchTag.
void SetTagTypes(unsigned int LFTagTypes,unsigned int HFTagTypes);
Parameters:
unsigned int LFTagTypes Specifies transponder types at the frequency 125.0 kHz - 134.2 kHz.
unsigned int HFTagTypes Specifies transponder types at the frequency 13.56 MHz.
Return: None.
Page 50 of 236
8 RF Functions
Page 51 of 236
8 RF Functions
In order to search for more than one type of transponder, several types can be combined.
Note:
The use of the predefined macro TAGMASK is mandatory, even if only one type of tag is specified. Here is
an example which is searching for EM4102 and HITAG 1 at LF and for MIFARE at HF:
Example:
SetTagTypes(TAGMASK(LFTAG_EM4102) | TAGMASK(LFTAG_HITAG1S),
TAGMASK(HFTAG_MIFARE));
8.4 GetTagTypes
This function returns the transponder types currently being searched for by function SearchTag separated
by frequency (LF and HF).
void GetTagTypes(unsigned int *LFTagTypes,unsigned int *HFTagTypes);
Parameters:
unsigned int *LFTagTypesPointer to a value, which receives the LF tag types.
unsigned int *HFTagTypesPointer to a value, which receives the HF tag types.
Return: None.
8.5 GetSupportedTagTypes
This function returns the transponder types, which are actually supported by the individual TWN4 sepa-
rated by frequency (LF and HF). Also the P-option is taken into account. This means, if the specific TWN4
has no option P, the appropriate transponders are not returned as supported type of transponder.
Page 52 of 236
8 RF Functions
Parameters:
unsigned int *LFTagTypesPointer to a value, which receives the LF tag types.
unsigned int *HFTagTypesPointer to a value, which receives the HF tag types.
Return: None.
Page 53 of 236
9 EM4x02-Specific Transponder Operations
This chapter describes one function for accessing EM4x02 transponders. EM4x02 is a broadly known
type of transponder, which is known under several names, such as EM4002, EM4102, Unique and several
other brands.
9.1 Function
9.1.1 EM4102_GetTagInfo
Get detailed information regarding transponder type LFTAG_EM4102 being found by function SearchTag.
int EM4102_GetTagInfo(void)
Parameters: None.
Return: One of the following pre-defined values: EM4102_BITRATE_UNKNOWN or
EM4102_BITRATE_F64 or EM4102_BITRATE_F32.
Page 54 of 236
10 HITAG 1- and HITAG S-Specific Transponder Operations
This chapter describes functions for accessing HITAG 1 and HITAG S transponders. HITAG 1 and HITAG
S are very similar. Therefore, same set of functions can be used for both types.
HITAG 1 and HITAG S transponder are available with different memory sizes. Due to this, the maximum
address, which can be specified depends also on the specific type of transponder:
10.1.1 Hitag1S_ReadPage
Parameters:
int PageAddress Specifies the address of the page to be read.
byte *Page Pointer to an array of 4 bytes where page data is stored after a successful
operation.
Return: If the operation was successful, the return value is true, otherwise it is
false.
10.1.2 Hitag1S_WritePage
Page 55 of 236
10 HITAG 1- and HITAG S-Specific Transponder Operations
Parameters:
int PageAddress Specifies the address of the page to be written.
byte *Page Pointer to an array of 4 bytes which are written to the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
10.1.3 Hitag1S_ReadBlock
Read 1 to 4 consecutive pages (4 to 16 bytes) from the transponder. The number of pages depends on the
specified address: The read process is stopped as soon as the read address reaches a block boundary,
which is a multiple of 4. If BlockAddress already specifies a block boundary, the maximum of 4 pages will
be read.
bool Hitag1S_ReadBlock(int BlockAddress,
byte *Block,int *BytesRead);
Parameters:
int BlockAddress Specifies the first page address of the block to be read.
byte *Page Pointer to an array of 4 to 16 bytes which are read from the transponder.
int *BytesRead Pointer to an integer, which receives the number of actually read bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
10.1.4 Hitag1S_WriteBlock
Write 1 to 4 consecutive pages (4 to 16 bytes) to the transponder. The number of pages depends on the
specified address: The write process is stopped as soon as the write address reaches a block boundary,
which is a multiple of 4. If BlockAddress already specifies a block boundary, the maximum of 4 pages will
be written.
bool Hitag1S_WriteBlock(int BlockAddress,const byte *Block,
int *BytesWritten);
Parameters:
int BlockAddress Specifies the first page address of the block to be written.
byte *Page Pointer to an array of 4 to 16 bytes which are written to the transponder.
int *BytesWritten Pointer to an integer, which receives the number of actually written bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
10.2 Hitag1S_Halt
This functions will halt a currently selected transponder. The transponder will not participate in any further
transponder communication till the RF field is turned off and on again.
bool Hitag1S_Halt(void);
Page 56 of 236
10 HITAG 1- and HITAG S-Specific Transponder Operations
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 57 of 236
11 HITAG 2-Specific Transponder Operations
11.1.1 Hitag2_ReadPage
Parameters:
byte PageAddress Specifies the address of the page to be read.
byte *Page Pointer to an array of 4 bytes where page data is stored after a successful
operation.
Return: If the operation was successful, the return value is true, otherwise it is
false.
11.1.2 Hitag2_WritePage
Parameters:
byte PageAddress Specifies the address of the page to be written.
byte *Page Pointer to an array of 4 bytes which are written to the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 58 of 236
11 HITAG 2-Specific Transponder Operations
11.1.3 Hitag2_SetPassword
During search for HITAG 2, TWN4 is using a password for doing a login to the transponder. The default
password after a reset is 0x4D,0x49,0x4B,0x52. This is the well-known default password for HITAG 2.
void Hitag2_SetPassword(const byte *Password);
Parameters:
const byte *Password Pointer to an array of 4 bytes, which contains the new password.
Return: None.
11.2 Hitag2_Halt
This functions will halt a currently selected transponder. The transponder will not participate in any further
transponder communication till the RF field is turned off and on again.
bool Hitag2_Halt(void);
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 59 of 236
12 EM4x50-Specific Transponder Operations
This chapter describes functions for accessing EM4x50 transponders. There are several chips, which are
compatible to each other within this family. These are: EM4050, EM4150, EM4450, EM4550. According
to the datasheet of the EM4x50 transponder, one word is meant to be 4 bytes.
12.1 Functions
12.1.1 EM4150_Login
Parameters:
const byte *Password Pointer to an array of 4 bytes which contains the password.
Return: If the operation was successful, the return value is true, otherwise it is
false.
12.1.2 EM4150_ReadWord
Parameters:
int Address Specifies the address of the page to be read. The valid address range is
from 0 to 33.
byte *Word Pointer to an array of 4 bytes which contains data read from the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
12.1.3 EM4150_WriteWord
Page 60 of 236
12 EM4x50-Specific Transponder Operations
Parameters:
int Address Specifies the address of the page to be written.
const byte *WordData Pointer to an array of 4 bytes which contains data to be written to the
transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
12.1.4 EM4150_WritePassword
Parameters:
const byte Pointer to an array of 4 bytes which specifies the current password of the
*ActualPassword transponder.
const byte Pointer to an array of 4 bytes which specifies the password to be written to
*NewPassword the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
12.1.5 EM4150_GetTagInfo
Get detailed information regarding transponder type LFTAG_EM4150 being found by function SearchTag.
int EM4150_GetTagInfo(void)
Parameters: None.
Return: One of the following pre-defined values: EM4150_BITRATE_UNKNOWN or
EM4150_BITRATE_F64 or EM4150_BITRATE_F40.
Page 61 of 236
13 AT55xx-Specific Transponder Operations
This chapter describes functions for accessing AT55xx transponders. There are several chips, which are
compatible to each other within this family. These are: e5550, e5551, T5555, T5555B, T5556, T5557,
ATA5567, ATA5577. Note: T5552 and T5558 are not supported by this API.
13.1.1 AT55_Begin
The function AT55_Begin must be used before subsequent read or write access to the transponder in
question.
void AT55_Begin(void);
Parameters: None.
Return: None.
Background:
Normally, in order to begin any read/write access to a transponder, the TWN4 system provides the function
SearchTag. This function searches for a transponder and keeps the RF in appropriate condition to allow
subsequent read- and write access.
This sequence is not applicable for the AT55xx family of transponders for two reasons:
• The transponder does not contain a serial number
• The transponder does not send data in a well-known standard format
The way out of this situation is the function AT55_Begin, which does not return any transponder data but
turns on RF field for subsequent read-/write operations.
Requirements:
The firmware of TWN4 supports read of data only, if the modulation of the transponder is configured to
manchester coding with a bitrate of RF/128 up to RF/8.
Furthermore, TWN4 can be set up to support sequence terminator turned on or off.
The default setup is RF/64 with sequence terminator turned off. In order to choose a different configuration
the function SetParameters must be used. Here is an example of how use of RF/32 is programmed:
const byte MyRF32Config[] = { AT55_BITRATE, 1, 32, TLV_END };
SetParameters(MyRF32Config,sizeof(MyRF32Config));
Page 62 of 236
13 AT55xx-Specific Transponder Operations
13.2.1 AT55_ReadBlock
Parameters:
int Address Specifies the address of the page to be read.
byte *Data Pointer to an array of 4 bytes which contains data read from the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
13.2.2 AT55_ReadBlockProtected
Parameters:
int Address Specifies the address of the page to be read.
byte *Data Pointer to an array of 4 bytes which contains data read from the transponder.
const byte *Password Pointer to an array of 4 bytes which contains the password.
Return: If the operation was successful, the return value is true, otherwise it is
false.
13.3.1 AT55_WriteBlock
Parameters:
int Address Specifies the address of the page to be written.
const byte *Data Pointer to an array of 4 bytes which contains data to be written to the
transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 63 of 236
13 AT55xx-Specific Transponder Operations
13.3.2 AT55_WriteBlockProtected
Parameters:
int Address Specifies the address of the page to be written.
const byte *Data Pointer to an array of 4 bytes which contains data to be written to the
transponder.
const byte *Password Pointer to an array of 4 bytes which contains the password.
Return: If the operation was successful, the return value is true, otherwise it is
false.
13.3.3 AT55_WriteBlockAndLock
Write one block (4 bytes) to a transponder and lock the written data. Locking data means, that it is not
possible to modify data contained in this block.
bool AT55_WriteBlockAndLock(int Address,const byte *Data);
Parameters:
int Address Specifies the address of the page to be written.
const byte *Data Pointer to an array of 4 bytes which contains data to be written to the
transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
13.3.4 AT55_WriteBlockProtectedAndLock
Write one block (4 bytes) to a password-protected transponder and lock the written data. Locking data
means, that it is not possible to modify data contained in this block.
bool AT55_WriteBlockProtectedAndLock(int Address,const byte *Data,const byte *Password);
Parameters:
int Address Specifies the address of the page to be written.
const byte *Data Pointer to an array of 4 bytes which contains data to be written to the
transponder.
const byte *Password Pointer to an array of 4 bytes which contains the password.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 64 of 236
14 TILF (TIRIS) Functions
This chapter describes functions for accessing Texas Instruments Low Frequency transponders (TILF).
This type of transponder was formerly also known as TIRIS.
Note:
It is highly recommended to also study datasheets of according transponders. Datasheets are available
from Texas Instruments.
14.1.1 TILF_SearchTag
Search for a TILF tag. This function can be used directly instead of the general search function SearchTag.
The function doing a search for a TILF tag in two different ways: First, a tag is search via a call of func-
tion TILF_ChargeOnlyRead. Second, a tag is searched via function TILF_MUGeneralReadPage, address
3.
bool TILF_SearchTag(int *IDBitCount,byte *ID,int MaxIDBytes);
Parameters:
int *IDBitCount A pointer to an integer, which receives the number of actually read
bits(!). Due to the nature of the functions TILF_ChargeOnlyRead and
TILF_MUGeneralReadPage, the number of received bits is either 32 or 64.
byte *ID A pointer to an array of bytes, which receives the read ID. Due to the nature
of the functions TILF_ChargeOnlyRead and TILF_MUGeneralReadPage, the
number of received bytes is either 4 or 8.
int MaxIDBytes The maximum number of bytes, which will be copied to ID
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.2.1 TILF_ChargeOnlyRead
Search for a single page transponder. This might be a read-only or a read/write transponder. Only
transponders are detected, where ID is stored under use of a CCITT CRC. If a transponder is pro-
grammed in a different way, consider using TILF_ChargeOnlyReadLo, which allows to read entire content
of transponder W/O CRC check.
bool TILF_ChargeOnlyRead(byte *ReadData);
Page 65 of 236
14 TILF (TIRIS) Functions
Parameters:
byte *ReadData A pointer to an array of 8 bytes, which receives checked ID data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.2.2 TILF_ChargeOnlyReadLo
Search for a single page transponder. This might be a read-only or a read/write transponder. No CRC
check is performed, thus allowing to read also custom programmed tags. The interpretation of data should
be known by the solution builder.
bool TILF_ChargeOnlyReadLo(byte *ReadData);
Parameters:
byte *ReadData A pointer to an array of 16 bytes, which receives unchecked ID data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.2.3 TILF_SPProgramPage
Parameters:
const byte A pointer to an array of 8 bytes, which will be written to the transponder.
*WriteData
byte *ReadData A pointer to an array of 8 bytes, which receives checked response from the
transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.2.4 TILF_SPProgramPageLo
Parameters:
const byte A pointer to an array of 10 bytes, which will be written to the transponder.
*WriteData
byte *ReadData A pointer to an array of 16 bytes, which receives unchecked response from
the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 66 of 236
14 TILF (TIRIS) Functions
14.3.1 TILF_MPGeneralReadPage
Parameters:
int Address The page address, where data will be read from.
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.2 TILF_MPSelectiveReadPage
Parameters:
int Address The page address, where data will be read from.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.3 TILF_MPProgramPage
Parameters:
int Address The page address, where data will be programmed to.
const byte A pointer to an array of 8 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.4 TILF_MPSelectiveProgramPage
Page 67 of 236
14 TILF (TIRIS) Functions
bool TILF_MPSelectiveProgramPage(
int Address,const byte *SelectiveAddress,
const byte *WriteData,byte *ReadData);
Parameters:
int Address The page address, where data will be programmed to.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
const byte A pointer to an array of 8 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.5 TILF_MPLockPage
Parameters:
int Address The page address, which will be locked.
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.6 TILF_MPSelectiveLockPage
Parameters:
int Address The page address, which will be locked.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
byte *ReadData A pointer to an array of 8 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.7 TILF_MPGeneralReadPageLo
Page 68 of 236
14 TILF (TIRIS) Functions
Parameters:
int Address The page address, where data will be read from.
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.8 TILF_MPSelectiveReadPageLo
Selective read of data from a multi-page transponder (SAMPT or SAMPTS) W/O CRC-check.
bool TILF_MPSelectiveReadPageLo(
int Address,const byte *SelectiveAddress,byte *ReadData);
Parameters:
int Address The page address, where data will be read from.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.9 TILF_MPProgramPageLo
Parameters:
int Address The page address, where data will be programmed to.
const byte A pointer to an array of 10 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.10 TILF_MPSelectiveProgramPageLo
Selective program of one page to a multi-page transponder (SAMPT or SAMPTS) W/O CRC-check.
bool TILF_MPSelectiveProgramPageLo(
int Address,const byte *SelectiveAddress,
const byte *WriteData,byte *ReadData);
Page 69 of 236
14 TILF (TIRIS) Functions
Parameters:
int Address The page address, where data will be programmed to.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
const byte A pointer to an array of 10 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.11 TILF_MPLockPageLo
Parameters:
int Address The page address, which will be locked.
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.3.12 TILF_MPSelectiveLockPageLo
Selective lock one page on a multi-page transponder (SAMPT or SAMPTS) W/O CRC-check.
bool TILF_MPSelectiveLockPageLo(
int Address,const byte *SelectiveAddress,byte *ReadData);
Parameters:
int Address The page address, which will be locked.
const byte Pointer to an array of 3 bytes (24 bits) which provides the selective address.
*SelectiveAddress
byte *ReadData A pointer to an array of 16 bytes, which receives data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.1 TILF_MUGeneralReadPage
Page 70 of 236
14 TILF (TIRIS) Functions
Parameters:
int Address The page address, where data will be read from.
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.2 TILF_MUSelectiveReadPage
Parameters:
int Address The page address, where data will be read from.
int SelectiveAddress A value which specifies the 8-bit selective address.
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.3 TILF_MUSpecialReadPage
Parameters:
int Address The page address, where data will be read from.
const byte Pointer to an array of 5 bytes (40 bits) which provides the special address 1.
*SpecialAddress1
const byte Pointer to an array of 3 bytes (24 bits) which provides the special address 2.
*SpecialAddress2
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.4 TILF_MUProgramPage
Page 71 of 236
14 TILF (TIRIS) Functions
Parameters:
int Address The page address, where data will be programmed to.
const byte A pointer to an array of 5 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.5 TILF_MUSelectiveProgramPage
Parameters:
int Address The page address, where data will be programmed to.
int SelectiveAddress A value which specifies the 8-bit selective address.
const byte A pointer to an array of 5 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.6 TILF_MUSpecialProgramPage
Parameters:
int Address The page address, where data will be programmed to.
const byte Pointer to an array of 5 bytes (40 bits) which provides the special address 1.
*SpecialAddress1
const byte Pointer to an array of 3 bytes (24 bits) which provides the special address 2.
*SpecialAddress2
const byte A pointer to an array of 5 bytes, which will be programmed.
*WriteData
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 72 of 236
14 TILF (TIRIS) Functions
14.4.7 TILF_MULockPage
Parameters:
int Address The page address, which will be locked.
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.8 TILF_MUSelectiveLockPage
Parameters:
int Address The page address, which will be locked.
int SelectiveAddress A value which specifies the 8-bit selective address.
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
14.4.9 TILF_MUSpecialLockPage
Parameters:
int Address The page address, which will be locked.
const byte Pointer to an array of 5 bytes (40 bits) which provides the special address 1.
*SpecialAddress1
const byte Pointer to an array of 3 bytes (24 bits) which provides the special address 2.
*SpecialAddress2
byte *ReadData A pointer to an array of 7 bytes, which receives page data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 73 of 236
15 ISO14443 Transponder Operations
This chapter handles specific operations for transparent access of ISO14443A/B compliant transpon-
ders. Before these functions can be used, the transponder must have been selected using the function
SearchTag(...).
15.1 ISO14443A
This function delivers the ATQA (Answer To Request TypeA) of the last detected ISO14443A compliant
transponder.
Parameters:
byte* ATQA After successful completion of this function, the buffer referred by this pa-
rameter holds the ATQA of the transponder. The function returns two bytes
of data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function delivers the SAK (Select Acknowledge) of the last detected ISO14443A compliant transpon-
der.
Parameters:
byte* SAK After successful completion of this function, the buffer referred by this pa-
rameter holds the SAK of the transponder. The function returns one byte of
data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function delivers the ATS (Answer To Select) of a ISO14443A layer 4 transponder.
Page 74 of 236
15 ISO14443 Transponder Operations
bool ISO14443A_GetATS
(
byte* ATS,
int* ATSByteCnt,
int MaxATSByteCnt
);
Parameters:
byte* ATS After successful completion of this function, the buffer referred by this pa-
rameter holds the ATS which was read from the transponder. Take care for
adequate dimensioning.
int* ATSByteCnt After successful completion of this function, this parameter holds the number
of bytes, the ATS contains.
int MaxATSByteCnt This parameter holds the array-size of ATS in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
15.2 ISO14443B
This function delivers the ATQB (Answer To Request TypeB) of the last detected ISO14443B compliant
transponder.
Note: This function cannot be called on TWN4 MultiTech Legic.
bool ISO14443B_GetATQB(byte* ATQB, int* ATQBByteCnt, int MaxATQBByteCnt);
Parameters:
byte* ATQB After successful completion of this function, the buffer referred by this pa-
rameter holds the ATQB of the transponder. Take care for adequate dimen-
sioning, the ATQB usually has 12 or 13 bytes in length.
int* ATQBByteCnt After successful completion of this function, this parameter holds the number
of bytes of ATQB.
int MaxATQBByteCnt This parameter holds the array-size of ATQB in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function delivers the transponder’s answer to the ATTRIB command, which is sent automatically
during selection process by the reader.
Note: This function cannot be called on TWN4 MultiTech Legic.
bool ISO14443B_GetAnswerToATTRIB
(
byte* AnswerToATTRIB,
int* AnswerToATTRIBByteCnt,
int MaxAnswerToATTRIBByteCnt
);
Page 75 of 236
15 ISO14443 Transponder Operations
Parameters:
byte* AnswerToATTRIB After successful completion of this function, the buffer referred by this pa-
rameter holds the AnswerToATTRIB of the transponder. Take care for ade-
quate dimensioning, AnswerToATTRIB can have one or more bytes in length.
int* After successful completion of this function, this parameter holds the number
AnswerToATTRIBByteCnt of bytes of AnswerToATTRIB.
int This parameter holds the array-size of AnswerToATTRIB in bytes.
MaxAnswerToATTRIBByteCnt
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used to probe if a ISO14443-4 transponder is still in reading range. The internal state
of the transponder remains unchanged.
Note: This function cannot be called on TWN4 MultiTech Legic.
bool ISO14443_4_CheckPresence(void);
Parameters: None.
Return: If the transponder is still in range, the return value is true, otherwise it is
false.
This function can be used for transparent exchange of data between reader and ISO14443-3 transpon-
ders. The function does not calculate any CRC or other overhead by itself, so if necessary this has to be
conducted on host side.
bool ISO14443_3_TDX
(
byte* TXRX,
int TXByteCnt,
int* RXByteCnt,
int MaxRXByteCnt
);
Page 76 of 236
15 ISO14443 Transponder Operations
Parameters:
byte* TXRX This buffer holds the byte-string that shall be transmitted to the transponder.
The response of the transponder is also returned by this parameter. Take
care for adequate dimensioning.
int TXByteCnt This parameter holds the number of bytes that shall be transmitted to the
transponder.
int* RXByteCnt After successful completion of this function, this parameter holds the number
of bytes that the transponder response contains.
int MaxRXByteCnt This parameter holds the array-size of TXRX in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used for transparent exchange of data between reader and ISO14443-4 transpon-
ders. All framing of layer 4 subset is already done by the reader, so only the payload needs to be passed
to the function.
bool ISO14443_4_TDX
(
byte* TXRX,
int TXByteCnt,
int* RXByteCnt,
int MaxRXByteCnt
);
Parameters:
byte* TXRX This buffer holds the byte-string that shall be transmitted to the transponder.
The response of the transponder is also returned by this parameter. Take
care for adequate dimensioning.
int TXByteCnt This parameter holds the number of bytes that shall be transmitted to the
transponder.
int* RXByteCnt After successful completion of this function, this parameter holds the number
of bytes that the transponder response contains.
int MaxRXByteCnt This parameter holds the array-size of TXRX in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
TWN4 is capable of handling multiple ISO14443A tags that are simultaneously present in the RF field.
Use the following functions to inventorize the field and select one of the discovered transponders for sub-
sequent operations.
Page 77 of 236
15 ISO14443 Transponder Operations
Use this function to search the RF field for ISO14443A transponders. The result is a list of the UID of the
respective transponders.
bool ISO14443A_SearchMultiTag
(
int* UIDCnt,
int* UIDListByteCnt,
byte* UIDList,
int MaxUIDListByteCnt
);
Parameters:
int* UIDCnt This parameter holds the number of found transponder UIDs.
int* UIDListByteCnt This parameter holds the number of valid bytes of the UID list.
byte* UIDList This parameter holds the list of found UIDs. Every entry is preceeded
by a single byte representing the respective UID length, e.g. the two
transponder IDs 11223344 and 00010203040506 would be coded as fol-
lows: 0411223340700010203040506.
int MaxUIDListByteCnt This parameter holds the array-size of UIDList in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to select one of the discovered transponders for further operations.
Parameters:
const byte* UID Specify the UID of the transponder to be selected.
int UIDByteCnt This parameter holds the byte count of the specified UID.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 78 of 236
16 MIFARE Classic Specific Transponder Operations
Sector 0
Sector 1
Sector 2
Sector 3
Sector 4
Sector 5
Sector 6
Sector 7
Sector 8
Sector 9
Sector 10
Sector 11
Sector 12
Sector 13
Sector 14
Sector 15
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Block 0
Block 1
Block 2
Page 79 of 236
16 MIFARE Classic Specific Transponder Operations
The memory of MIFARE Classic transponders is organized in sectors and blocks. In case of MIFARE
Classic 1K, the memory is divided into 16 sectors, each sector holds 4 blocks. Each block holds 16 bytes
of data. Each sector is secured by two keys, Key A and Key B which are always located in the last block of
a sector (sector trailer). In order to access the respective sector, a login using one of the two keys has to be
performed. Once logged in, the data blocks are accessible for read-, write- or value-operations. Each key
may be equipped with certain access rights, the access rights are coded in byte 6, 7 and 8 of the sector
trailer. Byte 9 is available for data storage.
In case of MIFARE Classic 4K, the memory layout of sector addresses 0 to 31 is compatible to the 1K
version, from sector 32 to 39, each sector holds 16 data blocks.
In any case, block 0 of sector 0 is called manufacturer block, and cannot be overwritten. Within this block,
the UID is stored and some manufacturer specific data.
16.1 Login
In order to do any operation on a sector of a MIFARE Classic transponder, a login to the respective sector
has to be performed. Each sector holds two keys, Key A and Key B. Depending on the access conditions
of the sector, the appropriate key shall be used for the desired operation. Both the keys and the access
conditions are stored in the sector trailer.
bool MifareClassic_Login
(
const byte* Key,
byte KeyType,
int Sector
);
Parameters:
const byte* Key Pointer to an array of bytes, which has to contain six bytes. These bytes
represent the key for the login process.
byte KeyType Specifies, with which key the operation has to be performed. This is one of
the defined constants KEYA or KEYB.
int Sector Specifies the sector for the login.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 80 of 236
16 MIFARE Classic Specific Transponder Operations
Read 16 bytes of data from a data-block of the transponder. Please note: If a sector trailer is read, the
respective key which was used for login is represented by zeros.
bool MifareClassic_ReadBlock
(
int Block,
byte* Data
);
Parameters:
int Block Specify the address of the block to be read. The valid range of this parame-
ter is between 0 and 255.
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 16 bytes of data, so the
minimum array size of Data must be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Write 16 bytes of data to a data-block of the transponder. Special care must be taken when writing to a
sector trailer as a faulty setting of the access conditions can make the sector unaccessible.
bool MifareClassic_WriteBlock
(
int Block,
const byte* Data
);
Parameters:
int Block Specify the address of the block to be written. The valid range of this pa-
rameter is between 0 and 255.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 16 bytes of data, so the minimum array size of
Data shall be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 81 of 236
16 MIFARE Classic Specific Transponder Operations
bool MifareClassic_ReadValueBlock
(
int Block,
int* Value
);
Parameters:
int Block Specify the address of the block to be read. The valid range of this param-
eter is between 0 and 255. Note that this function does not work with sector
trailers.
int* Value This parameter holds the value which was read from the tag if the operation
was successful.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: This function checks if the block has a valid value block format. If this is not the case, the
function returns false.
Format a data block to a MIFARE Classic compliant value block and assign an initial value.
bool MifareClassic_WriteValueBlock
(
int Block,
int Value
);
Parameters:
int Block Specify the address of the block to be formatted. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the initial value of the value block.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 82 of 236
16 MIFARE Classic Specific Transponder Operations
bool MifareClassic_IncrementValueBlock
(
int Block,
int Value
);
Parameters:
int Block Specify the address of the block to be incremented. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the increment value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
bool MifareClassic_DecrementValueBlock
(
int Block,
int Value
);
Parameters:
int Block Specify the address of the block to be decremented. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the decrement value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
bool MifareClassic_CopyValueBlock
(
int SourceBlock,
int DestBlock
);
Parameters:
int SourceBlock Specify the address of the source block.
int DestBlock Specify the address of the destination block.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 83 of 236
17 MIFARE Plus Specific Transponder Operations
MIFARE Plus is mostly compatible to MIFARE Classic, but comes with several enhancements regarding
security and functionality. The memory layout is compatible to MIFARE Classic. MIFARE Plus transpon-
ders incorporate four different levels of operation, these are called Security Level (SL).
Blank transponders are usually sold in SL0, which is used for personalisation of the transponder. Within
this level, the keys and data blocks can be written. When the personalisation process has finished, the
transponder has to be switched to a higher security level.
In usual cases, this is SL1 where the transponder is compatible to Mifare Classic, this means the login
process, memory layout and read/write operations are the same. In this case refer to the API description
of MIFARE Classic.
In case of MIFARE Plus X, the transponder may be switched from SL1 to SL2 where an additional AES
authentication becomes necessary before any memory operation is possible. All subsequent Crypto1 op-
erations are then depending on this authentication, as a session key is calculated and the Crypto1 key is
diversified for this session. So, after AES authentication, the API functions for MIFARE Classic have to be
used for accessing the memory.
MIFARE Plus S or X can be switched to SL3, where a AES authentication is necessary to access the
transponder memory. In case of MIFARE Plus X all operations are done fully encrypted, in case of MI-
FARE Plus S all operations are done in plain but with computation of an additional MAC. For memory
operations in SL3, the API functions described in the following chapters shall be used.
Please note, once a MIFARE Plus transponder has been switched to a higher security level, it cannot be
switched back again.
17.1 Personalisation
Personalisation can only be done if the transponder is operating in SL0. As all communication is done
in plain, this process should be conducted at a secure place. When all personalisation data has been
written, the personalisation must be finished by issuing the function Commit Personalisation. After that,
the personalisation becomes valid and the transponder is switched to SL1.
Use this function to write any personalisation data to a specific block of the transponder.
Page 84 of 236
17 MIFARE Plus Specific Transponder Operations
Parameters:
int BlockNr Specify the block number to be written. This can either be the number of a
sector block or a AES key.
const byte* Data Specify the data to be written with this parameter. The function expects
always 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used to switch the transponder to SL1 when all personalisation has been finished.
After calling this function, the transponder has to be reselected in order to access it again.
bool MFP_CommitPerso(void);
Parameters: None
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to do a mutual authentication in AES with the transponder. The key may either be a
sector key or a special one like a level switch key. In case of MIFARE Plus running in SL2, a preceding
AES authentication is necessary before any following memory operations which are conducted in Crypto1.
A typical transaction flow looks like this:
Search Tag
⇓
Authenticate AES
⇓
Mifare Classic Login
⇓
Mifare Classic Read/Write Data
bool MFP_Authenticate(int CryptoEnv, int KeyBNr, const byte* Key);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. All
consecutive operations with the transponder shall be done using the speci-
fied environment.
int KeyBNr Specify the key number that shall be used for authentication. This can either
be a sector key or a special key like a level switch key.
const byte* Key Specify the key that shall be used for authentication. For AES, the key must
have a key length of 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 85 of 236
17 MIFARE Plus Specific Transponder Operations
In Security Level 3 all memory related operations require a preceding AES authentication with the respec-
tive key. Please note, MIFARE Plus S does not support all the functionality of a MIFARE Plus X, e.g.
handling of value blocks is not supported here.
Use this function to read a data block from a MIFARE Plus transponder.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the number of the block that shall be read.
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 16 bytes of data, so the
minimum array size of Data must be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the number of the block that shall be written.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 16 bytes of data, so the minimum array size of
Data must be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 86 of 236
17 MIFARE Plus Specific Transponder Operations
Use this function to read the value stored in a MIFARE compliant value block.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the address of the block to be read. The valid range of this param-
eter is between 0 and 255. Note that this function does not work with sector
trailers.
int* Value This parameter holds the value which was read from the tag if the operation
was successful.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: This function checks if the block has a valid value block format. If this is not the case, the
function returns false.
Format a data block to a MIFARE compliant value block and assign an initial value.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the address of the block to be formatted. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the initial value of the value block.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 87 of 236
17 MIFARE Plus Specific Transponder Operations
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the address of the block to be incremented. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the increment value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int Block Specify the address of the block to be decremented. The valid range of this
parameter is between 0 and 255. Note that this function does not work with
sector trailers.
int Value This parameter holds the decrement value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int SourceBlock Specify the address of the source block.
int DestBlock Specify the address of the destination block.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 88 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Depending on the security settings of the transponder, a login with the valid transponder key might be
necessary prior performing any further operation.
Use this function to authenticate at a Mifare Ultralight C transponder with a given key.
Parameters:
const byte* Key Pointer to an array of bytes, which has to contain 16 bytes. These bytes
represent the key for the authentication process.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 89 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Use this function to authenticate at a Mifare Ultralight C transponder with a key stored on a SAM card.
Depending on the security settings of the SAM card, an additional authentication between reader an SAM
might be necessary prior issuing this command.
bool MifareUltralightC_SAMAuthenticate
(
int KeyNo,
int KeyVersion,
const byte* DIVInput,
int DIVByteCnt
);
Parameters:
int KeyNo Specify the number of the SAM key entry that shall be used for authentica-
tion.
int KeyVersion Specify the key version of the SAM key entry that shall be used for authen-
tication.
const byte* DIVInput Specify optional diversification input used for authentication.
int DIVByteCnt Specify the number of bytes for diversification input. Valid values are 0 to
31.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to transfer a key from a SAM card to the key storage area of a Mifare Ultralight C transpon-
der. Please note that the key stored on the SAM card must be dumpable. Depending on the security
settings of the SAM card, an additional authentication between reader an SAM might be necessary prior
issuing this command.
bool MifareUltralightC_WriteKeyFromSAM
(
int KeyNo,
int KeyVersion,
const byte* DIVInput,
int DIVByteCnt
);
Page 90 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Parameters:
int KeyNo Specify the number of the SAM key entry that shall be transfered.
int KeyVersion Specify the key version of the SAM key entry.
const byte* DIVInput Specify optional diversification input.
int DIVByteCnt Specify the number of bytes for diversification input. Valid values are 0 to
31.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Though the page size of this transponder family is 4 bytes, the transponder always returns 16 bytes of data.
This is achieved by reading four consecutive data pages, e.g. if page 4 is to be read, the transponder also
returns the content of page 5, 6 and 7. The transponder incorporates an integrated roll-back mechanism
if reading is done beyond the last physical available page address. E.g., in case of reading page 14 of
MIFARE Ultralight this would result in reading page 14, 15, 0, 1.
bool MifareUltralight_ReadPage
(
int Page,
byte* Data
);
Parameters:
int Page Specify the address of the page to be read. The valid range of this parameter
is between 0 and 15 (Ultralight) or 0 and 43 (Ultralight C).
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 16 bytes of data, so the
minimum array size of Data must be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Write 4 bytes of data to a data-page of the transponder. Compared to the read-function, this function pro-
cesses only one page at once.
bool MifareUltralight_WritePage
(
int Page,
const byte* Data
);
Page 91 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Parameters:
int Page Specify the address of the page to be written. The valid range of this param-
eter is between 2 and 15 (Ultralight) or 2 and 47 (Ultralight C).
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 4 bytes of data, so the minimum array size of Data
must be at least 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
The Fast Read function reads a number of pages beginning at a starting page from the transponder.
Parameters:
int StartPage Specify the address of the starting page.
int NumberOfPages Specify the number of pages to be read.
byte* Data This buffer holds the received data from the tag. Take care for proper di-
mensioning, the buffer size must be at least NumberOfPages * 4.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int CounterAddr Specify the address of the counter to be incremented.
int IncrValue Specify the increment value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read the value of one of the 3 one-way counters.
Page 92 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Parameters:
int CounterAddr Specify the address of the counter to be read.
int* CounterValue This parameter holds the returned counter value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read the factory programmed 32 byte ECC signature, to verify NXP Semiconductors
as the silicon vendor.
Parameters:
byte* ECCSig This buffer holds the returned ECC signature. The required buffer size is 32
bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to retrieve information about the transponder such as product version or storage size.
Parameters:
byte* Version This buffer holds 8 bytes of version information.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function for password authentication. For authentication, a 4 bytes password and a 2 bytes ac-
knowledge are required.
Parameters:
const byte* Password The 4 bytes password is specified by this parameter.
const byte* PwdAck This buffer holds 2 bytes of Password Acknowledge.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 93 of 236
18 MIFARE Ultralight/Ultralight C/Ultralight EV1 Specific Transponder Operations
Use this function to check if a tearing event has happened at a specific counter.
Parameters:
int CounterAddr Specify the address of the counter to be checked.
byte* ValidFlag The ValidFlag is returned by this parameter. If no tearing event has hap-
pened, the returned value is 0xBD.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 94 of 236
19 NTAG Specific Transponder Operations
Though the page size of this transponder family is 4 bytes, the transponder always returns 16 bytes of data.
This is achieved by reading four consecutive data pages, e.g. if page 4 is to be read, the transponder also
returns the content of page 5, 6 and 7. The transponder incorporates an integrated roll-back mechanism if
reading is done beyond the last physical available page address. The function is available for all members
of the NTAG transponder family.
Parameters:
int Page Specify the address of the page to be read. The valid range of this parameter
depends on the transponder type.
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 16 bytes of data, so the
minimum array size of Data must be at least 16 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Write 4 bytes of data to a data-page of the transponder. Compared to the read-function, this function pro-
cesses only one page at once. The function is available for all members of the NTAG transponder family.
Parameters:
int Page Specify the address of the page to be written. The valid range of this param-
eter depends on the transponder type.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 4 bytes of data, so the minimum array size of Data
must be at least 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 95 of 236
19 NTAG Specific Transponder Operations
The Fast Read function reads a number of pages beginning at a starting page from the transponder. The
function is supported by NTAG21x and NT3H1xxx transponders.
Parameters:
int StartPage Specify the address of the starting page.
int NumberOfPages Specify the number of pages to be read.
byte* Data This buffer holds the received data from the tag. Take care for proper di-
mensioning, the buffer size must be at least NumberOfPages * 4.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function reads the value of the one-way counter. The function is supported by NTAG21x transponders.
Please note that the NFC_CNT_EN bit in ACCESS configuration byte must be set in order to make this function
work.
Parameters:
int* CounterValue This parameter holds the returned counter value.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read the factory programmed 32 byte ECC signature, to verify NXP Semiconductors
as the silicon vendor. The function is supported by NTAG21x transponders.
Parameters:
byte* ECCSig This buffer holds the returned ECC signature. The required buffer size is 32
bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 96 of 236
19 NTAG Specific Transponder Operations
Use this function to retrieve information about the transponder such as product version or storage size.
The function is supported by NTAG21x and NT3H1xxx transponders.
Parameters:
byte* Version This buffer holds 8 bytes of version information.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function for password authentication. For authentication, a 4 bytes password and a 2 bytes ac-
knowledge are required. The function is supported by NTAG21x transponders.
Parameters:
const byte* Password The 4 bytes password is specified by this parameter.
const byte* PwdAck This buffer holds 2 bytes of Password Acknowledge.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to perform a sector select in order o switch between different memory sectors of a
NT3H1XXX.
Parameters:
int Sector Specify the sector to be selected.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Page 97 of 236
20 DESFire Specific Transponder Operations
The memory of a DESFire transponder is organized as a flexible file system. The transponder can hold
up to 28 applications and each application may contain up to 32 files of different type and size. Each
application can be secured by up to 14 cryptographic keys which are stored in the applications’s internal
key file. Applications are identified by a number, which must be unambiguous on the transponder. The
same rule applies to files within applications, these are identified by numbers which must be unambiguous
within the application.
By default, there exists a root-application with the identifier 0x000000 which defines the so-called transpon-
der level. This application cannot hold any files, it is intended to be used for basic administration of the
transponder.
Card
Application 1
Application 2
Application 3
Data File 1
Data File 2
Data File 3
Key File
A simple use-case could be: Search for a transponder, select the desired application, perform an authen-
tication with the respective key (if required), access data file for read or write operation.
Page 98 of 236
20 DESFire Specific Transponder Operations
Search
Transponder
Select Application
Authentication
necessary ?
Yes
No
Authenticate
Read/Write Data
20.1.1 Authenticate
This function shall be used to perform a mutual three pass authentication between reader and transponder.
The function supports both 3DES, 3K3DES and AES cryptography. In order to support both the DESFire
EV1 transponder family and the older DESFire MF3ICD40, the function incorporates a so-called Compati-
ble Mode.
After successful authentication, a session-key is generated which is used for all further cryptographic op-
erations. The authenticated state is invalidated in case of selecting an application, changing the key which
was used for the current authentication or a failed authentication.
Page 99 of 236
20 DESFire Specific Transponder Operations
On transponder level, depending on the security configuration, an authentication with the transponder
master key may be required to perform specific operations:
• Gather information on the transponder
• Change the transponder master key
• Change the transponder master key settings
• Create/delete applications
On application level, depending on the configuration, an authentication may be required to perform specific
operations:
• Gather information about the application
• Change the keys of the application
• Create/delete files within the application
• Change access rights
• Access data files
bool DESFire_Authenticate
(
int CryptoEnv,
int KeyNoTag,
const byte* Key,
int KeyByteCount,
int KeyType,
int Mode
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. All
consecutive operations with the transponder shall be done using the speci-
fied environment.
int KeyNoTag Specify the key number that shall be used for authentication. On transpon-
der level, only key 0 is valid for authentication. On application level, one
can specify up to 14 keys which can be used for authentication. Both on
transponder and application level, key 0 identifies the respective master key.
const byte* Key Specify the key that shall be used for authentication. For 3DES/AES, the
key must have a key length of 16 bytes, for 3K3DES the key must have a
key length of 24 bytes.
int KeyByteCount Specify the key length of the key. Use one of the predefined constants
DESF_KEYLEN_3DES, DESF_KEYLEN_3K3DES or DESF_KEYLEN_AES.
int KeyType Specify the type of the specified key. Use one of the predefined constants
DESF_KEYTYPE_3DES, DESF_KEYTYPE_3K3DES or DESF_KEYTYPE_AES. The au-
thentication will be performed according to the specified key type.
int Mode Select either DESFire EV1 ISO-mode authentication or the compatible na-
tive DESFire authentication scheme. Use one of the predefined constants
DESF_AUTHMODE_COMPATIBLE or DESF_AUTHMODE_EV1. Note that 3K3DES or
AES cryptography cannot be used in compatible mode.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: By default, the initial value of any key is all zeros. E.g. after creation of an application, all
keys have this initial value.
Example:
if (DESFire_Authenticate(
CRYPTO_ENV0,
0,
Key,
DESF_KEYLEN_AES,
DESF_KEYTYPE_AES,
DESF_AUTHMODE_EV1))
{
DoSomething();
}
This function can be used to read the current key version of any key that is stored on the transponder. If
the selected application is 0x000000, the command applies to the transponder master key and therefore
only key number 0 is valid for querying the key version.
bool DESFire_GetKeyVersion
(
int CryptoEnv,
int KeyNo,
byte* KeyVer
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int KeyNoTag Specify the key number that shall be queried.
byte* KeyVer The key version information is returned as one byte by this parameter.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
if (DESFire_GetKeyVersion(CRYPTO_ENV0,0,&KeyVer))
{
DoSomething();
}
This function allows to get information on the transponder- or application key settings. Depending on the
key settings, a preceding authentication with the respective master key may be required.
bool DESFire_GetKeySettings
(
int CryptoEnv,
TDESFireMasterKeySettings* MasterKeySettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
TDESFireMasterKey This structure receives the queried master key settings.
Settings*
MasterKeySettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
TDESFireMasterKeySettings MasterKeySettings;
if (DESFire_SelectApplication(0x123456))
{
if (DESFire_GetKeySettings(CRYPTO_ENV0,&MasterKeySettings))
{
DoSomething(MasterKeySettings);
}
}
This function allows to change the transponder- or application master key settings. The respective master
key settings can only be changed, if the bit ConfigurationChangeable of the current key settings was not
cleared before. In order to change the key settings, a preceding authentication with the respective master
key is required in general.
bool DESFire_ChangeKeySettings
(
int CryptoEnv,
const TDESFireMasterKeySettings* MasterKeySettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
const TDESFireMasterKey This structure holds the new master key settings. See chapter Get Key
Settings* Settings for details.
MasterKeySettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to change a key. The respective key settings define (see chapter Get Key Settings)
whether changing of a key is permitted or not and which key must be used for authentication before calling
this function.
bool DESFire_ChangeKey
(
int CryptoEnv,
int KeyNo,
const byte* OldKey,
int OldKeyByteCount,
const byte* NewKey,
int NewKeyByteCount,
byte KeyVersion,
const TDESFireMasterKeySettings* MasterKeySettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int KeyNo Specify the key number that shall be changed.
const byte* OldKey Specify the old key.
int OldKeyByteCount Specify the length of the old key in bytes.
const byte* NewKey Specify the new key.
int NewKeyByteCount Specify the length of the new key in bytes.
byte KeyVersion Specify the key version of the new key.
const TDESFireMasterKey This structure holds the current master key settings. See chapter Get Key
Settings* Settings for details.
MasterKeySettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
if (!DESFire_SelectApplication(0x123456))
{
return; // Error selecting application
}
if (!DESFire_GetKeySettings(CRYPTO_ENV0, &MasterKeySettings))
{
return; // Error gathering key settings
}
if (MasterKeySettings.KeySettings.ChangeKeyAccessRights == 0)
{
// Authenticate with master key
if (!DESFire_Authenticate(
CRYPTO_ENV0,
0,
oldKey,
DESF_KEYLEN_AES,
DESF_AUTHMODE_EV1))
{
return; // Authentication error
}
if (!DESFire_ChangeKey(
CRYPTO_ENV0,
1,
oldKey,
DESF_KEYLEN_AES,
newKey,
DESF_KEYLEN_AES,
0x20,
&MasterKeySettings))
{
return; // Error changing key 1
}
}
This function allows to create a new application on the transponder. Depending on the security settings of
the transponder, a preceding authentication with the transponder master key may be required, see chapter
Get Key Settings for details.
bool DESFire_CreateApplication
(
int CryptoEnv,
int AID,
const TDESFireMasterKeySettings* MasterKeySettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int AID Specify the Application ID of the new application to be created. The AID
consists of 24 bit, its value must be unique on the transponder. The value
0x000000 is reserved for the root application.
const TDESFireMasterKey This structure holds the master key settings of the new application. See
Settings* chapter Get Key Settings for details.
MasterKeySettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
TDESFireMasterKeySettings MasterKeySettings;
MasterKeySettings.KeySettings.AllowChangeMasterKey = true;
MasterKeySettings.KeySettings.FreeDirectoryList = true;
MasterKeySettings.KeySettings.FreeCreateDelete = true;
MasterKeySettings.KeySettings.ConfigurationChangeable = true;
MasterKeySettings.KeySettings.ChangeKeyAccessRights = 0x0;
MasterKeySettings.NumberOfKeys = 2;
MasterKeySettings.KeyType = DESF_KEYTYPE_AES;
if (DESFire_CreateApplication(
CRYPTO_ENV0,
0x123456,
&MasterKeySettings))
{
DoSomething();
}
This function allows to delete an existing application on the transponder. Depending on the security set-
tings of the transponder, a preceding authentication with the transponder master key may be required, see
chapter Get Key Settings for details.
bool DESFire_DeleteApplication
(
int CryptoEnv,
int AID
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int AID Specify the Application ID of the application that shall be deleted. The AID
consists of 24 bit. The value 0x000000 is reserved for the root application
hence this AID cannot be deleted.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to list all application IDs that exist on the transponder. Depending on the security
settings of the transponder, a preceding authentication with the transponder master key may be required,
see chapter Get Key Settings for details.
bool DESFire_GetApplicationIDs
(
int CryptoEnv,
int* AIDs,
int* NumberOfAIDs,
int MaxAIDCnt
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int* AIDs After successful completion of this function, this parameter holds a list of the
retrieved application IDs.
int* NumberOfAIDs This parameter holds the number of retrieved application IDs.
int MaxAIDCnt Specify the maximum number of application IDs, that can be stored in the ar-
ray AIDs. Note: Up to 28 applications can be stored on a DESFire transpon-
der, so take care for proper dimensioning of the array AIDs.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
int AIDList[28];
int NumberOfAIDs;
if (DESFire_GetApplicationIDs(
CRYPTO_ENV0,
AIDList,
&NumberOfAIDs,
sizeof(AIDList)/sizeof(int)))
{
DoSomething(AIDList,NumberOfAIDs);
}
This function is used to select an application in order to perform further operations such as reading or
writing. Depending on the security settings of the selected application, an authentication with one of the
application’s keys may be required after selection.
bool DESFire_SelectApplication
(
int CryptoEnv,
int AID
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int AID This parameter holds the application ID of the application to be selected.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Calling this function results in formatting the transponder. This means, all applications including their files
and keys are destroyed and the occupied memory space is released for future use. For proper usage, a
preceding authentication with the transponder master key is required.
bool DESFire_FormatTag
(
int CryptoEnv
);
This function can be used to gather detailed information about the DESFire transponder regarding hard-
ware and software version.
bool DESFire_GetVersion
(
int CryptoEnv,
TDESFireVersion* Version
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
TDESFireVersion* This structure receives the queried manufacturing related information.
Version
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to gather the available memory space of the transponder. A preceding authentication
is not required.
bool DESFire_FreeMem
(
int CryptoEnv,
int* FreeMemory
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int* FreeMemory After successful completion of this function, the available memory size in
bytes is returned by this parameter.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to retrieve the card UID in case of random ID. A preceding authentication with any key
is required prior calling this function.
bool DESFire_GetUID
(
int CryptoEnv,
byte* UID,
int* Length,
int BufferSize
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
byte* UID After successful completion of this function, the real card UID is returned by
this parameter. Note: The UID usually occupies 7 bytes, so take care for
proper dimensioning of the array UID.
int* Length The length in bytes of the UID is returned by this parameter.
int BufferSize This parameter specifies the size of the array UID in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
When this function is called, formatting the transponder is not possible any more (see chapter Format
Transponder). A preceding authentication with the transponder master key is required prior calling this
function. Note: Disabling tag formatting cannot be reset any more.
bool DESFire_DisableFormatTag
(
int CryptoEnv
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
Return: If the operation was successful, the return value is true, otherwise it is
false.
When this function is called, the transponder is turned into Random ID mode, this means the real UID can
only be retrieved by authenticating to the transponder and calling the function Get Card UID. A preceding
authentication with the transponder master key is required prior calling this function. Note: Setting the
transponder to Random ID mode cannot be reset any more.
bool DESFire_EnableRandomID
(
int CryptoEnv
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used to specify the default key, which is applied when e.g. a new application is
created on the transponder. By default, keys are initialized to 0x00. A preceding authentication with the
transponder master key is required prior calling this function.
bool DESFire_SetDefaultKey
(
int CryptoEnv,
const byte* Key,
int KeyByteCount,
byte KeyVersion
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
const byte* Key This parameter specifies the new default key.
int KeyByteCount This parameter specifies the length of the new default key in bytes. Use
one of the predefined constants DESF_KEYLEN_3DES, DESF_KEYLEN_3K3DES or
DESF_KEYLEN_AES.
byte KeyVersion This parameter specifies the default key version.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used to specify a user-defined Answer To Select (ATS) which is returned by the
transponder after RATS. Changing the ATS to a non-default value shall only be carried out by experts as
a ATS longer than 16 bytes could cause problems with readers that support only frame sizes of max. 16
bytes. The ATS must be formatted as follows: TL T0 TA TB TC + Historical bytes. The default ATS of
DESFire EV1 is TL=0x06, T0=0x75, TA=0x77, TB=0x81, TC=0x02, Historical Bytes=0x80.
bool DESFire_SetATS
(
int CryptoEnv,
const byte* ATS,
int Length
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
const byte* ATS This parameter specifies the new ATS.
int Length This parameter specifies the length of the new ATS in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This section deals with file handling within an application of a DESFire transponder. An application can
hold three different basic file types: Data files, Value files and Record Files. Data files are available either
with or without integrated backup-mechanism, Value files and Record files always incorporate integrated
backup. There exist two types of record files: Linear record files and Cyclic Record Files.
Some functions for file handling are using the data structure TDESFireFileSettings which defines all
relevant file settings. See the following tables for reference:
Coding of access rights:
Every file holds four different access rights, each access right is coded in one nibble. These four nibbles
are concatenated and form the 16 bit variable AccessRights.
One nibble codes 16 possible values. If it codes a number between 0 and 13, this references a certain key
number within the application.
If the number is 14, this means "free" access so there is no authentication necessary to perform the
respective operation on the file. In case of coding the number 15, this means "deny" access.
This section deals with the creation of new files within applications. Depending on the specified file type,
the file is either created with or without integrated backup-mechanism. Each file requires an unambiguous
identifier which is coded in one byte in the range from 0x00 to 0x1F. During creation of the file, the level of
security is defined in the communication settings. Communication can be either plain, secured by MAC or
fully enciphered. Furthermore, the access rights are assigned to certain keys held by the application.
Depending on the security settings of the application, a preceding authentication with the application mas-
ter key may be required, see chapter Get Key Settings for details.
bool DESFire_CreateDataFile
(
int CryptoEnv,
int FileNo,
const TDESFireFileSettings* FileSettings
);
bool DESFire_CreateValueFile
(
int CryptoEnv,
int FileNo,
const TDESFireFileSettings* FileSettings
);
bool DESFire_CreateRecordFile
(
int CryptoEnv,
int FileNo,
const TDESFireFileSettings* FileSettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the file ID. If the ID already exists within the application, this results
in an error.
const This member holds the file settings. See description of
TDESFireFileSettings* TDESFireFileSettings for details.
FileSettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
TDESFireFileSettings FileSettings;
int FileID;
if (DESFire_SelectApplication(0x123456))
{
// We create a standard data file
FileSettings.FileType = DESF_FILETYPE_STDDATAFILE;
// Communication between reader and tag is fully enciphered
FileSettings.CommSet = DESF_COMMSET_FULLY_ENC;
// Read Access : Key 1
// Write Access : Key 2
// Read/Write : Key 3
// Change Settings : Key 4
FileSettings.AccessRights = 0x1234;
// File size shall be 512 bytes
FileSettings.SpecificFileInfo.DataFileSettings.FileSize = 512;
// Assign an identifier to the file
FileID = 0x12;
if (DESFire_CreateDataFile(CRYPTO_ENV0, FileID, &FileSettings))
{
DoSomething();
}
}
This function allows to permanently deactivate a file within an application. This means, the allocated mem-
ory is not released for further usage, only the file number can be re-used for creating a new file. In order
to re-use the memory of deleted files, this requires formatting the transponder but this leads to permanent
loss of any application data. Depending on the security settings of the application, a preceding authenti-
cation with the application master key may be required, see chapter Get Key Settings for details.
bool DESFire_DeleteFile
(
int CryptoEnv,
int FileNo
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file which shall be deleted. If the ID doesn’t exist within
the application, this results in an error.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to list all file IDs that exist within the currently selected application. Each file ID is
coded in one byte in the range from 0x00 to 0x1F. Duplicate values are not possible as each file must have
an unambiguous identifier. Depending on the security settings of the application, a preceding authentica-
tion with the application master key may be required, see chapter Get Key Settings for details.
bool DESFire_GetFileIDs
(
int CryptoEnv,
byte* FileIDList,
int* FileIDCount,
int MaxFileIDCount
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
byte* FileIDList After successful completion of this function, this parameter holds a list of the
retrieved file IDs.
int* FileIDCount This parameter holds the number of retrieved file IDs.
int MaxFileIDCount Specify the maximum number of file IDs, that can be stored in the array
FileIDList. Note: Up to 32 files can be stored within an application, so take
care for proper dimensioning of the array FileIDList.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
See chapter Get File Settings for a comprehensive example.
This function allows to query the file settings of an existing file within an application. The returned infor-
mation depends on the type of the file. Depending on the security settings of the application, a preceding
authentication with the application master key may be required, see chapter Get Key Settings for details.
bool DESFire_GetFileSettings
(
int CryptoEnv,
int FileNo,
TDESFireFileSettings* FileSettings
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the file ID which shall be queried.
TDESFireFileSettings* This member holds the returned file settings. See description of
FileSettings TDESFireFileSettings for details.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
TDESFireFileSettings FileSettings;
int i;
if (DESFire_SelectApplication(0x123456))
{
// Gather a list of present file IDs
if (DESFire_GetFileIDs(
CRYPTO_ENV0,
FileIDList,
&FileIDCount,
sizeof(FileIDList)))
{
for (i=0; i<FileIDCount; i++)
{
// Query the settings of each file
if (DESFire_GetFileSettings(
CRYPTO_ENV0,
FileIDList[i],
&FileSettings))
{
switch(FileSettings.FileType)
{
case DESF_FILETYPE_STDDATAFILE:
DoSomething();
break;
case DESF_FILETYPE_VALUEFILE:
DoSomethingElse();
break;
}
}
}
}
}
This function allows to change the access parameters such as communication settings and access rights
of an existing file. Depending on the actual change access rights of the file, authentication with the respec-
tive key has to be performed before calling this function. Furthermore, the change access right must be
different from "deny". See Coding of Access Rights for details.
bool DESFire_ChangeFileSettings
(
int CryptoEnv,
int FileNo,
int NewCommSet,
int OldAccessRights,
int NewAccessRights
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the file ID whose settings shall be changed.
int NewCommSet Specify the new communication settings. Possible val-
ues are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
int OldAccessRights Specify the current Access Rights of the file.
int NewAccessRights Specify the new Access Rights of the file.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used to access a standard or backup data file in order to read from it. Depending
on the file’s access rights, a preceding authentication with the read or read/write key has to be done, see
Coding of Access Rights for details. The function allows segmented access, this means the user is able to
either read the entire file or only a part starting at a user-defined offset.
bool DESFire_ReadData
(
int CryptoEnv,
int FileNo,
byte* Data,
int Offset,
int Length,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file that shall be read.
byte* Data After successful completion of this function, the buffer referred by this pa-
rameter holds the data which was read from the transponder. Take care for
adequate dimensioning.
int Offset Specify the starting address for reading. The valid range of this parameter
is 0x000000 to FileSize - 1. In case of address-range violation, the function
returns with an error.
int Length Specify the length of data that shall be read. The valid range of this pa-
rameter is FileSize - Offset. In case of address-range violation, the function
returns with an error.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Example:
TDESFireFileSettings FileSettings;
int ReadAccess;
if (!DESFire_SelectApplication(CRYPTO_ENV0, 0x123456))
return; // Error
switch (ReadAccess)
{
case 15: // Access denied
return;
case 14: // Free access
break;
default:
// Authenticate with the "reading-key"
if (!DESFire_Authenticate(
CRYPTO_ENV0,
ReadAccess,
KeyRead,
DESF_KEYLEN_AES,
DESF_KEYTYPE_AES,
DESF_AUTHMODE_EV1))
return; // Error
}
This function shall be used to access a standard or backup data file in order to write to it. Depending on the
file’s access rights, a preceding authentication with the write or read/write key has to be done, see Coding
of Access Rights for details. The function allows segmented access, this means the user is able to either
rewrite the entire file or only a part starting at a user-defined offset.
bool DESFire_WriteData
(
int CryptoEnv,
int FileNo,
const byte* Data,
int Offset,
int Length,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file that shall be written.
const byte* Data The buffer referred by this parameter holds the data which is written to the
file.
int Offset Specify the starting address for writing. The valid range of this parameter
is 0x000000 to FileSize - 1. In case of address-range violation, the function
returns with an error.
int Length Specify the length of data that shall be written. The valid range of this pa-
rameter is FileSize - Offset. In case of address-range violation, the function
returns with an error.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: If data is written to a Backup Data File, it is necessary to validate the written data with
the function Commit Transaction. Calling the function Abort Transaction will invalidate all
changes.
Example:
TDESFireFileSettings FileSettings;
int WriteAccess;
if (!DESFire_SelectApplication(CRYPTO_ENV0, 0x123456))
return; // Error
switch (WriteAccess)
{
case 15: // Access denied
return;
case 14: // Free access
break;
default:
// Authenticate with the "writing-key"
if (!DESFire_Authenticate(
CRYPTO_ENV0,
WriteAccess,
KeyWrite,
DESF_KEYLEN_AES,
DESF_KEYTYPE_AES,
DESF_AUTHMODE_EV1))
return; // Error
}
This function allows to read the current value from a Value File. Depending on the file’s access rights,
a preceding authentication with the read, write or read/write key has to be done, see Coding of Access
Rights for details.
bool DESFire_GetValue
(
int CryptoEnv,
int FileNo,
int* Value,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the Value File whose value shall be queried.
int* Value After successful completion of this function, this parameter holds the value
which was read from the file.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
20.4.2.2 Debit
This function allows to decrease a value stored in a Value File. The function requires a preceding au-
thentication with the read, write or read/write key, see Coding of Access Rights for details. The value
modifications of Credit, Debit and Limited Credit functions are cumulated until the function Commit Trans-
action is called.
If the Limited Credit feature is enabled, the new limit for a subsequent Limited Credit function call is set
to the sum of Debit modifications within one transaction before calling Commit Transaction. This assures,
that a Limited Credit can not re-book more values than a debiting transaction deducted before.
bool DESFire_Debit
(
int CryptoEnv,
int FileNo,
const int Value,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the Value File that shall be debited.
const int Value The value stored in the value file will be decreased by this parameter.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: After modifying value files, it is necessary to validate the transaction with the function Commit
Transaction. Calling the function Abort Transaction will invalidate all changes.
20.4.2.3 Credit
This function allows to increase a value stored in a Value File. The function requires a preceding authenti-
cation with the read/write key, see Coding of Access Rights for details. The value modifications of Credit,
Debit and Limited Credit functions are cumulated until the function Commit Transaction is called.
If the Limited Credit feature is enabled, this function cannot be used. Use the function Limited Credit in-
stead.
bool DESFire_Credit
(
int CryptoEnv,
int FileNo,
const int Value,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the Value File that shall be credited.
const int Value The value stored in the value file will be increased by this parameter.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: After modifying value files, it is necessary to validate the transaction with the function Commit
Transaction. Calling the function Abort Transaction will invalidate all changes.
This function allows a limited increase of a value stored in a Value File without having full read/write per-
missions to the file. This feature can only be used if it has been enabled during file creation. The function
requires a preceding authentication with the write or read/write key, see Coding of Access Rights for de-
tails. The value modifications of Credit, Debit and Limited Credit functions are cumulated until the function
Commit Transaction is called.
After calling this function, the new limit is set to 0, regardless of the amount which has been re-booked.
Hence, this function can only be used once after a Debit transaction.
bool DESFire_LimitedCredit
(
int CryptoEnv,
int FileNo,
const int Value,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the Value File that shall be credited.
const int Value The value stored in the value file will be increased by this parameter. It is
limited to the sum of Debit operations on this value file within the most recent
transaction containing at least one Debit.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: After modifying value files, it is necessary to validate the transaction with the function Commit
Transaction. Calling the function Abort Transaction will invalidate all changes.
Use this function to read out a set of complete records from a Record File. The function requires a preced-
ing authentication with the read or read/write key, see Coding of Access Rights for details.
bool DESFire_ReadRecords
(
int CryptoEnv,
int FileNo,
byte* RecordData,
int* RecDataByteCnt,
int Offset,
int NumberOfRecords,
int RecordSize,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file that shall be read.
byte* RecordData After successful completion of this function, the buffer referred by this pa-
rameter holds the data which was read from the transponder. Take care for
adequate dimensioning.
int* RecDataByteCnt The total number of bytes read from the transponder is represented by this
parameter.
int Offset Specify the offset of the newest record to be read out. The valid range of
this parameter is 0x000000 to number of existing records - 1. In case of
0x000000 the latest record is read out.
int NumberOfRecords Specify the number of records to be read out.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write data to a Record File. The function requires a preceding authentication with
the write or read/write key, see Coding of Access Rights for details. In order to validate writing, a call of
Commit Transaction becomes necessary. If writing is not validated, a new WriteRecord command writes
to the already created record.
bool DESFire_WriteRecord
(
int CryptoEnv,
int FileNo,
const byte* Data,
int Offset,
int Length,
int CommSet
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file that shall be read.
const byte* Data This buffer holds the record data to be written.
int Offset Specify the offset in bytes within one single record. The valid range of this
parameter is 0x000000 to record size - 1.
int Length Specify the length of data to be written. The parameter has to be in the
range from 0x000001 to record size - offset.
int CommSet Specify the communication settings. The communication set-
tings must match to the actual settings of the file. Possi-
ble values are: DESF_COMMSET_PLAIN, DESF_COMMSET_PLAIN_MACED,
DESF_COMMSET_FULLY_ENC.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to reset a Record File to the empty state. The function requires a preceding authentica-
tion with the read/write key, see Coding of Access Rights for details. After execution of the function, a call
of Commit Transaction becomes necessary.
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
int FileNo Specify the ID of the file that shall be cleared.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to validate all previous modifications on files with integrated backup mechanism such
as Backup Data Files, Value Files and Record Files. When a transaction has been finished, this is usually
the last called function; if this step was omitted, any changes would be lost if a different application is
selected or the transponder is removed from the RF-field.
bool DESFire_CommitTransaction
(
int CryptoEnv
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function allows to discard all previous modifications on files with integrated backup mechanism such
as Backup Data Files, Value Files and Record Files.
bool DESFire_AbortTransaction
(
int CryptoEnv
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants. Usu-
ally the same environment is specified that was used for authentication.
Return: If the operation was successful, the return value is true, otherwise it is
false.
21 SAM AV1/AV2
Before using one of the following functions, a NXP SAM AV1/AV2 card must have been inserted into one of
the available SAM slots. When powering up, TWN4 scans the slots for SAM cards, so a correctly inserted
SAM card is detected automatically for later use.
This function shall be used to perform a mutual three pass authentication between host (reader) and the
SAM AV1/AV2 card. The function supports both 3DES and AES cryptography. Depending on security set-
tings of the SAM card, the authentication might be necessary in order to perform different security related
actions afterwards.
bool SAMAVx_AuthenticateHost
(
int CryptoEnv,
int KeyNo,
const byte* Key,
int KeyByteCount,
int KeyType
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int KeyNo Specify the key number that shall be used for authentication.
const byte* Key Specify the key that shall be used for authentication. For 3DES/AES, the
key must have a key length of 16 bytes.
int KeyByteCount Specify the key length of the key. Use one of the predefined constants
DESF_KEYLEN_3DES or DESF_KEYLEN_AES.
int KeyType Specify the type of the specified key. Use one of the predefined constants
DESF_KEYTYPE_3DES or DESF_KEYTYPE_AES. The authentication will be per-
formed according to the specified key type.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to query information about a key entry on the SAM card.
Parameters:
int KeyNo Specify the key number that shall be used for authentication.
TSAMAVxKeyEntryData* The key entry is returned by this parameter.
KeyEntryData
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used for ISO15693 specific transponder operations which are not covered by high-
level system functions.
bool ISO15693_GenericCommand
(
byte Flags,
byte Command,
byte* Data,
int* Length,
int BufferSize
);
Parameters:
byte Flags Specify the ISO15693 flags. Note: The flags regarding RF-communication
are set automatically, so by default one may assign 0x00 to this parameter.
byte Command Command code.
byte* Data This parameter works as Input/Output-buffer. All additional parameters
which are sent to the transponder are passed within this buffer. This buffer
is also used for data returned from the transponder.
int* Length This parameter works as Input/Output-variable. It holds the payload-length
of Data in the directions Reader→Tag and Tag→Reader.
int BufferSize This parameter holds the array-size of Data in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function returns more in-depth information of the tag. The function is available in two versions (Proto-
col Extension flag set or reset), as some tag types like ST 24LR16/64 require the Protocol Extension flag
to be set for proper operation.
bool ISO15693_GetSystemInformation
(
TISO15693_SystemInfo* SystemInfo
);
bool ISO15693_GetSystemInformationExt
(
TISO15693_SystemInfo* SystemInfo
);
Parameters:
TISO15693_SystemInfo* Pointer to the structure which receives the System Information.
SystemInfo
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: As the GetSystemInformation command is no mandatory ISO15693 command, it is not im-
plemented in all tag types available on the market.
The ISO15693 API incorporates two methods to determine the tag type, either by analysing the UID or the
System Information structure.
This function can be used to determine the tag type of ISO15693 compliant transponders if only the UID
is available.
int ISO15693_GetTagTypeFromUID
(
byte* UID
);
Parameters:
byte* UID This parameter holds the UID. Watch for the correct byte order; UID[0] shall
have the value 0xE0
Return: The return-value is the determined tag-type which is represented by one of
the constants in the table below.
This function can be used to determine the tag type of ISO15693 compliant transponders if the System
Information is available.
int ISO15693_GetTagTypeFromSystemInfo
(
TISO15693_SystemInfo* SystemInfo
);
Parameters:
TISO15693_SystemInfo* Pointer to the structure which holds the System Information.
SystemInfo
Return: The return-value is the determined tag-type which is represented by one of
the constants in the table below.
Read a single data block from the transponder. The function is available in two versions (Protocol Exten-
sion flag set or reset), as some tag types like ST 24LR16/64 require the Protocol Extension flag to be set
for proper operation.
bool ISO15693_ReadSingleBlock
(
int BlockNumber,
byte* BlockData,
int* Length,
int BufferSize
);
bool ISO15693_ReadSingleBlockExt
(
int BlockNumber,
byte* BlockData,
int* Length,
int BufferSize
);
Parameters:
int BlockNumber This parameter holds the number of the block to be read.
byte* BlockData This parameter holds the data which was read from the tag if the operation
was successful. Note that the block size varies between different tag types,
so the array size of BlockData should be set to a reasonable value.
int* Length This parameter holds the length of data which was read from the tag in bytes.
int BufferSize This parameter holds the array-size of BlockData in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Write to a single data block of the transponder. The function is available in two versions (Protocol Exten-
sion flag set or reset), as some tag types like ST 24LR16/64 require the Protocol Extension flag to be set
for proper operation.
bool ISO15693_WriteSingleBlock
(
int BlockNumber,
const byte* BlockData,
int Length
);
bool ISO15693_WriteSingleBlockExt
(
int BlockNumber,
const byte* BlockData,
int Length
);
Parameters:
int BlockNumber This parameter holds the number of the block to be written.
const byte* BlockData This parameter holds the data which shall be written to the tag.
int Length This parameter holds the length of data which shall be written to the tag in
bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
23 LEGIC-Specific Functions
TWN4 MultiTech LEGIC has a built-in LEGIC chip type SM4200 or SM4500. There are functions available
to directly communicate with this chipset.
Note:
Due to license restrictions, this documentation only mentions the functions itself. In order to use full
functionality of the LEGIC chip, appropriate documentation is required, which is available under NDA
(none-disclosure agreement) only.
23.1.1 SM4X00_GenericRaw
Send a command and receive the response from SM4X00. Command and response are expected to
include CRC. This function is intended to be used for end-to-end communication between SM4X00 and a
host.
bool SM4X00_GenericRaw(const byte *TXData,int TXDataLength,
byte *RXData,int *RXDataLength,
int MaxRXDataLength,int Timeout);
Parameters:
const byte *TXData Pointer to an array of bytes, which contains the command to be sent to
SM4X00.
int TXDataLength Number of bytes to be sent to SM4X00.
byte *RXData Pointer to an array of bytes, which receives response from SM4X00
int *RXDataLength Pointer to an integer, which receives the actually read number of bytes.
int MaxRXDataLength A value, which specifies the maximum number of bytes, which can be re-
ceived byte RXData, thus the buffer size.
int Timeout Maximum time, the function should wait for a response from SM4X00. This
value is specified in milliseconds.
Return: If the operation was successful, the return value is true, otherwise it is
false.
23.1.2 SM4X00_Generic
Send a command and receive the response from SM4X00. This function is intended to be used by
standand-along applications.
bool SM4X00_Generic(const byte *TXData,int TXDataLength,
byte *RXData,int *RXDataLength,
int MaxRXDataLength,int Timeout);
Parameters:
const byte *TXData Pointer to an array of bytes, which contains the command to be sent to
SM4X00. The command has to be specified W/O leading length byte and
W/O closing CRC value.
int TXDataLength Number of bytes contained in TXData.
byte *RXData Pointer to an array of bytes, which receives response from SM4X00. Re-
ceived data is W/O length byte and W/O CRC value.
int *RXDataLength Pointer to an integer, which receives length of the actually received payload.
int MaxRXDataLength A value, which specifies the maximum number of bytes, which can be re-
ceived byte RXData, thus the buffer size.
int Timeout Maximum time, the function should wait for a response from SM4X00. This
value is specified in milliseconds.
Return: If the operation was successful, the return value is true, otherwise it is
false.
23.1.3 SM4X00_StartBootloader
Parameters:
byte *TLV
int *TLVLength
int MaxTLVLength
Return: If the operation was successful, the return value is true, otherwise it is
false.
23.1.4 SM4X00_EraseFlash
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
false.
23.1.5 SM4X00_ProgramBlock
Parameters:
byte *Data Pointer to an array of bytes.
bool *Done Pointer to a boolean variable, which receives the status, if the last block was
flashed.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This chapter handles specific operations with iCLASS transponders. Prerequisites for this functionality are:
• The reader must be the TWN4 MultiTech/MultiTech Nano version, LEGIC is not supported.
• An iCLASS SIO card must be inserted into one of the SAM slots.
• The I-Option must be activated.
• For iCLASS Seos support, the SIO card must have firmware 1.19 or higher.
This function can be used to read the PAC (Physical Access Control) bits from an iCLASS transponder.
The transponder must have been selected before this function can be called.
bool ICLASS_GetPACBits
(
byte* PACBits,
int* PACBitCnt,
int MaxPACBytes
);
Parameters:
byte* PACBits After successful completion of this function, the buffer referred by this pa-
rameter holds the PAC bits read from the transponder. Take care for ade-
quate dimensioning.
int* PACBitCnt After successful completion of this function, this parameter holds the number
of bits, the PAC contains.
int MaxPACBytes This parameter holds the maximum number of bytes which the buffer
PACBits can hold.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Remark: There are transponders available, that have not been configured to deliver the PAC bits. In
this case, if an attempt is made to read these bits, the function returns false.
24.1.1 Example
The following example shows how to manually read the PAC from an iCLASS transponder using the built-in
system functions.
byte ID[8];
int TagType;
int IDBitCnt;
byte PACBits[8];
int PACBitCnt;
while (true)
{
// Search for transponders
if (!SearchTag(&TagType,&IDBitCnt,ID,sizeof(ID)))
continue;
Use this function to select a transponder book and page. In case of success, the Configuration Block is
returned. Note that this function is not supported by some iCLASS transponders, e.g. iCLASS 2k/2.
bool ICLASS_SelectPage
(
int Book,
int Page,
TICLASS_ConfigBlock* ConfigBlock
);
Parameters:
int Book Specify the book number to be selected.
int Page Specify the page number to be selected.
TICLASS_ConfigBlock* The content of the Configuration Block of the selected page is returned by
ConfigBlock this buffer.
Return: If the operation was successful, the return value is true, otherwise it is
false.
24.3 Authenticate
Use this function to perform the mutual authentication procedure. Authentication may be required to have
read-/write access to protected data blocks. Either a Debit or a Credit key can be used for Application Area
1 or 2 respectively. Before this function can be used, book and page have to be selected in advance.
bool ICLASS_Authenticate
(
const byte* KeyReferenceOID,
int KeyType
);
Parameters:
const byte* Specify the OID of the key to be used for authentication. The OID is always
KeyReferenceOID 3 bytes in length, the first byte must be 0x03.
int KeyType Specify the type of key, use one of the predefined constants
ICLASS_KEYTYPE_CREDIT or ICLASS_KEYTYPE_DEBIT.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read a single 8 byte block of an iCLASS transponder. If a read operation to a protected
block is carried out, the function returns all 0xFF as data. So it is necessary to select a page and perform
authentication prior read access.
bool ICLASS_ReadBlock
(
int Block,
byte* BlockData
);
Parameters:
int Block Specify the block number to be read.
byte* BlockData This buffer holds the block data read from the tranponder. The block size is
always 8 bytes so take care for proper dimensioning of the buffer size.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write a 8 byte data block to an iCLASS transponder. Before a write operation can be
carried out, a page must be selected and authenticated.
bool ICLASS_WriteBlock
(
int Block,
const byte* BlockData
);
Parameters:
int Block Specify the block number to be written.
const byte* BlockData This buffer holds the block data to be written to the tranponder. The block
size is always 8 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
25 FeliCa
This chapter handles specific operations of contactless transponders that support FeliCa technology. Be-
fore one of the following functions can be used, the transponder must have been selected using the function
SearchTag(...).
25.1 Polling
Use this function to acquire a card by specifying a System Code. The transponder only answers if the
specified System Code matches to a system stored on the card. By specifying a wildcard (0xFF) for either
the upper or lower byte, a particular match of System Code can be achieved.
Parameters:
uint16_t SystemCode Specify the two-byte System Code by this parameter.
byte* IDm The Manufacture ID is returned by this buffer. The function always returns 8
bytes.
byte* PMm The Manufacture Parameter is returned by this buffer. The function always
returns 8 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to aquire a list of System Codes which are available on the card. This function does not
work with FeliCa Lite or FeliCa Plug ICs.
bool FeliCa_RequestSystemCode
(
int* NumberOfSystemCodes,
uint16_t* SystemCodeList,
int MaxNumberOfSystemCodes
);
Parameters:
int* This parameter holds the number of retrieved System Codes.
NumberOfSystemCodes
uint16_t* This parameter holds the list of System Codes which are available on the
SystemCodeList card.
int Specify the maximum number of System Codes, that can be stored in the
MaxNumberOfSystemCodes array SystemCodeList.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to verify the existance of Area and Service Codes. The function returns the Key Version
of existing Area and System Codes. If the specified Area or System does not exist, the respective Key
Version is 0xFFFF. This function does not work with FeliCa Lite or FeliCa Plug ICs.
bool FeliCa_RequestService
(
int NumberOfServices,
const uint16_t* ServiceCodeList,
uint16_t* KeyVersionList
);
Parameters:
int NumberOfServices This parameter specifies the size of ServiceCodeList.
const uint16_t* This array holds the list of Service Codes that shall be queried.
ServiceCodeList
uint16_t* The queried KeyVersions are returned by this array. It has the same size as
KeyVersionList ServiceCodeList, each KeyVersion is assigned to the order of appearance
of ServiceCodeList.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read blocks of data from a authentication-not-required service. This function works
with all transponders supporting FeliCa technology.
bool FeliCa_ReadWithoutEncryption
(
int NumberOfServices,
const uint16_t* ServiceCodeList,
int NumberOfBlocks,
const uint16_t* BlockList,
byte* Data
);
Parameters:
int NumberOfServices This parameter specifies the size of ServiceCodeList.
const uint16_t* This array holds the list of Service Codes. Currently, one Service Code can
ServiceCodeList be specified.
int NumberOfBlocks This parameter specifies the number of blocks that shall be read. The cur-
rent implementation allows reading of four blocks at a time.
const uint16_t* This array holds the list of blocks that shall be read.
BlockList
byte* Data Block data which was read from the card is returned by this buffer. A block
has always 16 bytes of data, so the buffer must be dimensioned depending
on the number of blocks that shall be read. The block data is returned in the
order of appearance of the values of BlockList.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write blocks of data to a authentication-not-required service. This function works with
all transponders supporting FeliCa technology.
bool FeliCa_WriteWithoutEncryption
(
int NumberOfServices,
const uint16_t* ServiceCodeList,
int NumberOfBlocks,
const uint16_t* BlockList,
const byte* Data
);
Parameters:
int NumberOfServices This parameter specifies the size of ServiceCodeList.
const uint16_t* This array holds the list of Service Codes. Currently, one Service Code can
ServiceCodeList be specified.
int NumberOfBlocks This parameter specifies the number of blocks that shall be written. The
current implementation allows writing of four blocks at a time.
const uint16_t* This array holds the list of blocks that shall be written.
BlockList
const byte* Data Block data which shall be written to the card. A block has always 16 bytes of
data, so the buffer must hold NumberOfBlocks multiplied by 16 bytes of data.
The block data must be arranged in the order of appearance of the values
of BlockList.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function can be used for transparent exchange of data between reader and FeliCa transponders, e.g.
for transponder commands which are not covered by the current implementation of the reader API.
bool FeliCa_TDX
(
byte* TXRX,
int TXByteCnt,
int* RXByteCnt,
int MaxRXByteCnt,
byte MaximumResponseTime,
byte NumberOfBlocks
);
Parameters:
byte* TXRX This buffer holds the byte-string that shall be transmitted to the transponder.
The response of the transponder is also returned by this parameter. Take
care for adequate dimensioning.
int TXByteCnt This parameter holds the number of bytes that shall be transmitted to the
transponder.
int* RXByteCnt After successful completion of this function, this parameter holds the number
of bytes that the transponder response contains.
int MaxRXByteCnt This parameter holds the array-size of TXRX in bytes.
byte This parameter holds the parameter byte which shall be used for calculation
MaximumResponseTime of the Maximum Response Time according to the calculation formula.
byte NumberOfBlocks This parameter holds the value n which shall be used for calculation of the
Maximum Response Time according to the calculation formula.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to manually read byte 0 to 3 of the UID and the header ROM. The remaining bytes 4 to 6
of the UID can be read e.g. by using the function Topaz_ReadByte.
Parameters:
byte* HR0 The byte HR0 of the Header ROM is returned by this parameter.
byte* HR1 The byte HR1 of the Header ROM is returned by this parameter.
byte* UID The UID bytes 0 to 3 are returned by this buffer.
Return: If the operation was successful, the return value is true, otherwise it is
false.
In order to read data from memory of Topaz transponders, there are two functions available. You may
choose between reading one single byte or even read the entire memory space.
Use this function to read one single byte from the memory of the transponder.
Parameters:
const byte* UID Specify byte 0 to 3 of the UID by this parameter.
byte ADD Specify the address in memory to be read from.
byte* Byte This parameter holds the byte which was read from the transponder.
Return: If the operation was successful, the return value is true, otherwise it is
false.
bool Topaz_ReadAllBlocks(const byte* UID, byte* HR0, byte* HR1, byte* Data);
Parameters:
const byte* UID Specify byte 0 to 3 of the UID by this parameter.
byte* HR0 The byte HR0 of the Header ROM is returned by this parameter.
byte* HR1 The byte HR1 of the Header ROM is returned by this parameter.
byte* Data The transponder memory data is returned by this buffer. The function returns
120 bytes, so take care for proper dimensioning.
Return: If the operation was successful, the return value is true, otherwise it is
false.
In order to write data to the memory of Topaz transponders, there are two functions available. You may
chose between programming of data with preceding erase or without erase. So if the variant without erase
is selected, this results in logical ORing of data bits. In the initial state, all writeable data bytes of Topaz
are 0x00.
Use this function to write one byte to the memory of the transponder. A preceding erase cycle is performed
prior programming takes place.
Parameters:
const byte* UID Specify byte 0 to 3 of the UID by this parameter.
byte ADD Specify the address in memory to be written to.
byte Byte This parameter holds the byte to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write one byte to the memory of the transponder. As no preceding erase cycle is
performed prior programming, the overall operation results in logical ORing of the existing data byte on the
transponder and the byte to be written.
Parameters:
const byte* UID Specify byte 0 to 3 of the UID by this parameter.
byte ADD Specify the address in memory to be written to.
byte Byte This parameter holds the byte to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
TWN4 offers support of CTS256B and CTS512B transponders. In order to read data from the memory,
the respective transponder must be selected by issuing the function SearchTag(). After successful search,
the transponder memory is ready for read and write operations. CTS transponders are organized in 16 or
32 blocks, each block contains 2 bytes of data.
Please note: CTS256B transponders remain silent after a write operation has been issued. As a conse-
quence, the respective write function returns an error. In order to handle this, it is recommended to perform
a verification read of the respective data block.
Use this function in order to read a block of data from the transponder memory.
Parameters:
int Block Specify the address of the block to be read. The valid range of this parame-
ter depends on the transponder type.
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 2 bytes of data, so the
minimum array size of Data must be at least 2 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write data to a block of the transponder memory. This function performs a logical OR-
ing of already present block data and new data to be written. If the block shall be overwritten regardless of
its current content, the function CTS_UpdateBlock shall be used instead.
Parameters:
int Block Specify the address of the block to be written. The valid range of this pa-
rameter depends on the transponder type.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 2 bytes of data, so the minimum array size of Data
must be at least 2 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write data to a block of the transponder memory. Data is written regardless of the
current content of the specified data block. Please note: Prior execution of this function, the transponder
system bits have to be refreshed in order to make this function work. This can be achieved by reading
block 1 of the transponder.
Parameters:
int Block Specify the address of the block to be written. The valid range of this pa-
rameter depends on the transponder type.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 2 bytes of data, so the minimum array size of Data
must be at least 2 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
TWN4 offers support of the ST SR transponder family like SRI, SRT or SRIX, called here SRX. In order to
read data from the memory, the respective transponder must be selected by issuing the function Search-
Tag(). After successful search, the transponder memory is ready for read and write operations. SRX
transponders are organized in blocks, each block contains 4 bytes of data.
Use this function in order to read a block of data from the transponder memory.
Parameters:
int Block Specify the address of the block to be read. The valid range of this parame-
ter depends on the transponder type.
byte* Data This parameter holds the data which was read from the tag if the operation
was successful. Note that this function always reads 4 bytes of data, so the
minimum array size of Data must be at least 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int Block Specify the address of the block to be written. The valid range of this pa-
rameter depends on the transponder type.
const byte* Data This parameter holds the data which shall be written to the tag. Note that
this function always writes 4 bytes of data, so the minimum array size of Data
must be at least 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This chapter handles transmission of NDEF (NFC Data Exchange Format) messages between a TWN4
reader and a NFC enabled device using the Simple NDEF Exchange Protocol. For message exchange, a
NFC Peer-to-Peer connection must have been established.
The SNEP service provides both a logical In-Box and a logical Out-Box for receiving and transmitting mes-
sages. Each message box works as FIFO, which enables reader and host-software to exchange even large
messages as a stream of data. This functionality is also useful to reduce outbound buffering on host side.
Each message box can manage only one message at the same time, so message-queuing is currently not
supported. Large messages that do not fit into the internal FIFO must be transmitted fragmented, so the
sending side must break up the message into smaller parts that fit into the FIFO, the receiving side must
reassemble the parts as a consequence. When dealing with large messages, it might become necessary
to read data from the FIFO fast enough during a ongoing transmission in order to prevent any tailbacks.
Note: This functionality is only available on TWN4 MultiTech based on Core Module.
Use this function for initialization and starting of the built-in SNEP service. The function should be called at
last once before issuing SearchTag() with TagType HFTAG_NFCP2P enabled. Depending on the implemen-
tation of the counterpart NFC device, there might be a delay until the SNEP service is activated on both
communication peers. This time usually ranges around 100 ms up to 500 ms.
bool SNEP_Init(void);
Parameters: None.
Return: If the SNEP service was successfully started, the return value is true, oth-
erwise it is false.
Use this function to query the current connection state of the SNEP service. This can be used for checking
e.g. any loss of the physical NFC Peer-to-Peer connection.
int SNEP_GetConnectionState(void);
Parameters: None.
Return: SNEP_STATE_DEINIT: The SNEP service has not been started.
SNEP_STATE_SLEEP: The SNEP service has been started, but there is no
active connection.
SNEP_STATE_IDLE: The SNEP service is running, but there is currently no
active exchange of messages.
SNEP_STATE_CONNCLIENT: The SNEP service is running in client mode.
SNEP_STATE_CONNSERVER: The SNEP service is running in server mode.
Parameters:
int Direction Specify the message box to be queried by this parameter. Valid values are
DIR_OUT (Out-Box) or DIR_IN (In-Box), use one of these predefined con-
stants.
Return: If the In-Box is queried, the return value is the current number of bytes which
are available for reading from host side. If the Out-Box is queried, the return
value is the number of bytes that can be written to the FIFO.
This section handles transmission of NDEF messages. A typical communication flow for transmitting a
NDEF message looks like this:
Use this function to setup the total message length. A message can reach up to 4 GBytes.
Parameters:
uint32_t MsgByteCnt Specify the total message length by this parameter.
Return: If the operation was successful, the return value is true. If a previously set
up message has not been transmitted completely, the return value is false.
Use this function to store a fragment of a message in the Out-Box FIFO. The message must be transmitted
completely in order to make the FIFO available for new outgoing messages.
Parameters:
const byte* MsgFrag Specify the buffer that holds the message fragment by this parameter.
int FragByteCnt This parameter holds the length the message fragment.
Return: If the operation was successful, the return value is true, otherwise it is
false.
29.4.3 Example
The following example demonstrates transmission of a NDEF message from a TWN4 MultiTech reader to
another NFC device running SNEP:
const byte NDEF_Message[] = { /* Your NDEF message */ };
void TransmitNDEFMessage(void)
{
// Wait for SNEP service is running
unsigned long SNEPConnectionStartTime = GetSysTicks();
// SNEP service must be at least in IDLE state
while (SNEP_GetConnectionState() < SNEP_STATE_IDLE)
{
if (GetSysTicks() - SNEPConnectionStartTime > 500)
return;
}
// Transmit NDEF message as long as a NFC connection is established
int FragmentOffset = 0;
int NDEF_MessageByteCnt = sizeof(NDEF_Message);
while (true)
{
if (SNEP_GetConnectionState() < SNEP_STATE_IDLE)
return;
// Get available buffer size from operating system for message fragmenting
FragmentSize = SNEP_GetFragmentByteCount(DIR_OUT);
if (FragmentSize > 0)
{
// Is this the first fragment?
if (FragmentOffset == 0)
{
// Yes, Setup message
if (!SNEP_BeginMessage(NDEF_MessageByteCnt))
return;
}
// Calculate fragment size
if (NDEF_MessageByteCnt - FragmentOffset <= FragmentSize)
FragmentSize = NDEF_MessageByteCnt - FragmentOffset;
// Send a fragment of the message
if (!SNEP_SendMessageFragment(&NDEF_Message[FragmentOffset], FragmentSize))
return;
FragmentOffset += FragmentSize;
}
// Was the message completely tansmitted?
if (FragmentOffset == NDEF_MessageByteCnt)
return;
}
}
#define MAXIDBYTES 10
byte ID[MAXIDBYTES];
int IDBitCnt;
int TagType;
int main(void)
{
// Enable NFC Peer-to-Peer mode
SetTagTypes(0, TAGMASK(HFTAG_NFCP2P));
while (true)
{
// Search a transponder
if (SearchTag(&TagType, &IDBitCnt, ID, sizeof(ID)))
{
if (TagType == HFTAG_NFCP2P)
{
// Transmit NDEF message
TransmitNDEFMessage();
}
}
}
}
This section handles reception of NDEF messages. A typical communication flow for receiving a NDEF
message looks like this:
Use this function to test if there is a new message available in the In-Box. The function returns the total
length of the message. A message can reach up to 4 GBytes.
Parameters:
uint32_t* MsgByteCnt The total message length is returned by this parameter.
Return: If a message is available, the return value is true, otherwise it is false.
Use this function to receive a fragment of a message stored in the In-Box FIFO. A message must be read
completely from the FIFO in order to make it available for new incoming messages.
Parameters:
byte* MsgFrag Specify the buffer that holds the message fragment by this parameter.
int FragByteCnt This parameter holds the length the message fragment to be read.
Return: If the operation was successful, the return value is true, otherwise it is
false.
29.5.3 Example
The following example demonstrates reception of a NDEF message from another NFC device running
SNEP:
void ReceiveNDEFMessage(void)
{
// Wait for SNEP service is running
unsigned long SNEPConnectionStartTime = GetSysTicks();
// SNEP service must be at least in IDLE state
while (SNEP_GetConnectionState() < SNEP_STATE_IDLE)
{
if (GetSysTicks() - SNEPConnectionStartTime > 500)
return;
}
// Receive all NDEF messages as long as a NFC connection is established
while (true)
{
uint32_t MessageSize;
byte Message[4096];
// Wait for a incoming NDEF message or loss of connection
while (!SNEP_TestMessage(&MessageSize))
{
if (SNEP_GetConnectionState() < SNEP_STATE_IDLE)
return;
}
// A NDEF message was announced. Now read it.
int FragmentOffset, FragmentSize;
for (FragmentOffset = 0; FragmentOffset < MessageSize; FragmentOffset += FragmentSize)
{
// Wait, till fragment of the message arrives
do
{
if (SNEP_GetConnectionState() < SNEP_STATE_IDLE)
return;
FragmentSize = SNEP_GetFragmentByteCount(DIR_IN);
}
while (FragmentSize == 0);
SNEP_ReceiveMessageFragment(&Message[FragmentOffset],FragmentSize);
}
// We read the entire NDEF message
}
}
#define MAXIDBYTES 10
byte ID[MAXIDBYTES];
int IDBitCnt;
int TagType;
int main(void)
{
// Enable NFC Peer-to-Peer mode
SetTagTypes(0, TAGMASK(HFTAG_NFCP2P));
while (true)
{
// Search a transponder
if (SearchTag(&TagType, &IDBitCnt, ID, sizeof(ID)))
{
if (TagType == HFTAG_NFCP2P)
{
// Receive NDEF message
ReceiveNDEFMessage();
DoSomething();
}
}
}
}
30 BLE Functions
The reader TWN4 MultiTech 2 / 3 BLE supports LF / HF transponders and additionally BLE (Bluetooth Low
Energy). This allows to connect to all devices with the Bluetooth Standard 4.0 or greater: Android mobile
phones with Version 4.3 or greater, iPhones 4S, 5 or greater and PCs with Windows 8.1 / 10 and Bluetooth
hardware.
The App in the TWN4 MultiTech 2 / 3 BLE control the BLE module. There are commands for initialization,
setting connection parameters, do connection and e.g. reading / writing GATT data fields.
First of all initialize the BT Module. To make the extensive setting easier, simply call the function BLEInit
to set the wished configuration for starting the Module. The Mode parameter fills the environment variables
for the selected mode.
To set an own environment, use the functions BLEPresetConfig and BLEPresetUserData followed with
BLEInit(0).
After initialization call the function BLECheckEvent for checking events of Bluetooth. It’s good to use a call
frequency of about 100ms. This would be fine. Slower calling slows the BLE functionality. Faster is not
necessary but no problem.
Environmet information are called by BLEGetAddress for the address of the reader, the address for the
connected device and the type of this address. Information of the firmware ask with BLEGetVersion and
at least connection environment with BLEGetEnvironment.
To request the latest RSSI call the function BLERequestRssi if a connection has established. The RSSI
value is returned by the event BLE_EVENT_CONNECTION_RSSI. Closing a connection is thrown with
BLERequestEndpointClose. But also an automatic closing is carried out by the set timeout at initializa-
tion.
Server functions:
The GATT (Generic Attribute Profile) on the BLE module can be read with BLEGetGattServerAttribute-
Value and written with BLESetGattServerAttributeValue.
Client functions:
For the client reader mode, the GATT server is e.g. on a mobile phone. Use the BLEDiscover() func-
tion to start, stop, discover services and characteristics. The BLEConnectToDevice() and BLEDiscon-
nectFromDevice() functions make a connection. Invoke BLEGattGetAttribute(), BLEGattGetValue() and
BLEGattSetValue() for read and write GATT server fields on a remote device.
The BLE Module on the TWN4 MultiTech BLE communicates serial with the main core. COM2 is reserverd
for the communication with the BLE Modul and GPIO7 is the reset of the BLE Module. So do not use COM2
and GPIO7 for other things on the hardware TWN4 MultiTech 2 / 3 BLE.
30.2 BLEPresetConfig
This function presets the individual configuration structure for the BLE module. The initialization command
BLEInit is necessary after this - optional also the BLEPresetUserData.
bool BLEPresetConfig
(
TBLEConfig* BLEConfig
);
Parameters:
TBLEConfig* Reference to the structure that holds the BLE configuration parameters. See
the description of TBLEConfig for details.
Return: If the operation was successful, the return value is true, otherwise it is
false.
byte ConnectMode 8 Connectable Modes for the LE (Low Energy) GAP (Generic
Access Profile):
0 = non connectable,
1 = directed connectable,
2 = undirected connectable,
3 = scannable / non connectable.
byte SecurityFlags 8 Security requirement bitmask:
Bit 0 = 0: Allow bonding without MITM protection,
Bit 0 = 1: Bonding requires MITM protection,
Bit 1 = 0: Allow encryption without bonding,
Bit 1 = 1: Encryption requires bonding,
Bit 2 to 7: Reserved, Default value: 0x00.
byte IOCapabilities 8 Security Management related I/O capabilities:
0 = display only,
1 = display yes/no,
2 = keyboard only,
3 = no input / no output,
4 = keyboard / display
uint32_t Passkey 32 Passkey: If security is configured, the application needs to
display or ask user to enter a passkey during the bonding
process. See:
BLE_EVENT_SM_PASSKEY_DISPLAY or
BLE_EVENT_SM_PASSKEY_REQUEST.
30.3 BLEPresetUserData
This function sets the user data string for advertising. F.e. the Apple company has introduced iBeacons to
broadcast their identifier to nearby portable electronic devices. If you discover an iBeacon or common a
Beacon, you get his UUID, Major and Minor values. With the TWN4 MultiTech 2 BLE, you can configure
the reader to be a Beacon.
bool BLEPresetUserData
(
byte ScanResp,
const byte* UserData,
int UserDataLength
);
Parameters:
byte ScanResp Selection the type showing user data:
0 = advertise packets,
1 = scan packets.
const byte* UserData Reference to the byte buffer that holds the UserData parameters. See the
description of UserData for details.
int UserDataLength Length of the UserData. Maximum data length is 30 Bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
UserData[25] 8 0x00 The Major high value, which is used to group re-
lated beacons.
UserData[26] 8 0x00 The Major low value.
UserData[27] 8 0x00 The Minor high value, which is used to specify in-
dividual beacon within a group.
UserData[28] 8 0x00 The Minor low value.
UserData[29] 8 0xC3 Signal power (calibrated RSSI) - See the iBeacon
specification for measurement guidelines.
30.4 BLEInit
This function initialize the Bluetooth BLE Module on the reader. Different modes are possible: The
custom mode makes individual operating modes possible - pre configured with BLEPresetConfig and
BLEPresetUserData. The other modes are predefined modes for advertisment and Beacon.
bool BLEInit
(
int Mode
);
Parameters:
int Mode Specify the initialization mode. See the definition of Mode for meaning of
each member.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.5 BLECheckEvent
This function returns the actual event of the BLE module. The returned event tells different status mes-
sages of the Bluetooth environment either information or user action.
int BLECheckEvent
(
void
);
Parameters: None.
Return: Specify the event. See the definition in the table below
30.6 BLEGetAddress
This function returns the device address from the BLE module, the remote address from the connected
device and the address type of the remote address.
bool BLEGetAddress
(
byte* DeviceAddress,
byte* RemoteAddress,
byte* Type
);
Parameters:
byte* DeviceAddress The device address of the BLE module in 6 bytes hex is returned by this
parameter.
byte* RemoteAddress The remote address of the connected device in 6 bytes hex is returned, if
the remote device is successfull connected. For additional information of
the remote address see the Type parameter.
byte* Type The type of the remote address is returned by this parameter. Possible
values are:
0 = public address,
1 = random address,
2 = public identity address resolved by stack,
3 = random identity address resolved by stack,
4 = Classic Bluetooth address.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.7 BLEGetVersion
This function returns on the one hand the version string of the BLE module firmware in ASCII format and
on the other the boot string of the BLE hardware. Requirement: BLEInit() with any parameter is called
first.
bool BLEGetVersion
(
byte* HWVersion,
byte* BootString
);
Parameters:
byte* HWVersion The firmware version string (16 bytes) in ASCII code is returned by this pa-
rameter. Example: "V1.03,14.11.2016"
byte* BootString The boot string of the BLE hardware is returned. The information is binary
coded in 12 bytes with the following information:
Byte 0 - 1: Major release version,
Byte 2 - 3: Minor release version,
Byte 4 - 5: Patch release number,
Byte 6 - 7: Build number,
Byte 8 - 9: Bootloader version,
Byte 10 - 11: Hardware type.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.8 BLEGetEnvironment
This function can be used to ask for connection enviroment on a connected device.
bool BLEGetEnvironment
(
byte* DeviceRole,
byte* SecurityMode,
byte* Rssi
);
Parameters:
byte* DeviceRole The device role of the connection is returned:
0 = Slave,
1 = Master.
byte* SecurityMode The security mode of the established connection is returned. Possible val-
ues are:
0 = No security.
1 = Unauthenticated pairing with encryption.
2 = Authenticated pairing with encryption.
3 = Authenticated Secure Connections pairing with encryption using a 128-
bit strength encryption key.
byte* Rssi RSSI (field strength) of the BLE connection
Range: -127 to +20. Units: dBm.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.9 BLEGetGattServerAttributeValue
This function returns the data of a GATT attribute handle. If the event
"BLE_EVENT_GATT_SERVER_ATTRIBUTE_VALUE" is called, call the function with the AttrHandle and
Bit 15 set to 1.
bool BLEGetGattServerAttributeValue
(
int AttrHandle,
byte *Data,
int *Len,
int MaxLen
);
Parameters:
int AttrHandle Specify the attribute handle of the GATT who is se-
lected to read. Additional set Bit15 to 1 if the event
"BLE_EVENT_GATT_SERVER_ATTRIBUTE_VALUE" is called.
byte *Data The read data of the given attribute handle is returned by this parameter.
int *Len This parameter holds the length of data which was read from the GATT.
int MaxLen Maximum number of characters, the specified byte array can receive exclud-
ing the 0-termination.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.10 BLESetGattServerAttributeValue
This function writes data to an attribute handle. Notice that the GATT attribute must be writeable.
bool BLESetGattServerAttributeValue
(
int AttrHandle,
int Offset,
const byte *Data,
int Len
);
Parameters:
int AttrHandle Specify the attribute handle of the GATT for writing data. If Bit 15 of the
AttrHandle is set, the GATT field is written and a notification is sent to the
connected slave.
int Offset Specify the starting address for writing to data. The valid range of this pa-
rameter is 0 to Len-1.
byte *Data The write data buffer to the attribute handle with the specifyed offset.
int Len This parameter holds the length of data which shall be written to the GATT.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.11 BLERequestRssi
This function calls a request for the latest RSSI of a Bluetooth connection. The value of the RSSI is
returned by an event BLE_EVENT_CONNECTION_RSSI with function BLECheckEvent. The function makes
only sense if there is a established connection with a remote device. If the module is in discovery mode,
the function BLECheckEvent returns the current RSSI of the scanned device.
bool BLERequestRssi
(
void
);
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.12 BLERequestEndpointClose
This function closes a connection with the remote device. If the connection is closed, the function BLECheckEvent
returns the event BLE_EVENT_CONNECTION_CLOSED for successfull closing.
bool BLERequestEndpointClose
(
void
);
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.13 BLEGetGattServerCharacteristicStatus
Parameters:
int *AttrHandle GATT characteristic handle.
int *AttrStatusFlag Describes whether Client Characteristic Configuration was changed or if
confirmation was received:
1 = Characteristic client configuration has been changed.
2 = Characteristic confirmation has been received.
int *AttrConfigFlag This field carries the new value of the Client Characteristic Configuration:
0 = Disable notifications and indications.
1 = Notification.
2 = Indication.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.14 BLEFindGattServerAttribute
This command can be used to find attributes of certain type from a local GATT database. Type is usually
given as 16-bit (2 byte) or 128-bit (16 byte) UUID.
bool BLEFindGattServerAttribute
(
const byte *UUID,
int UUIDLength,
int *AttrHandle
);
Parameters:
const byte *UUID 16-bit or 128-bit UUID of the local GATT database.
int UUIDLength Length of the UUID in bytes (e.g. 2 or 16).
int *AttrHandle The GATT characteristic attribute handle is returned by this parameter.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.15 BLEDiscover
This function starts with discovering devices, services and characteristics - depending on the Discover-
Mode parameter. Unnecessary parameters of the function are assigned zero.
bool BLEDiscover
(
int DiscoverMode,
unsigned long GattHandle,
const TBLEUUID *BLEUUID
);
Parameters:
int DiscoverMode Mode parameter to discover devices, services and characteristics. See the
DiscoverMode table below.
unsigned long GattHandleDepending on parameter DiscoverMode the handle of a GATT field.
const TBLEUUID *BLEUUID Depending on parameter DiscoverMode the UUID of a GATT filed.
Return: If the operation was successful, the return value is true, otherwise it is
returned false.
30.16 BLECheckDiscoveredString
Parameters:
int CheckMode Mode parameter for different comparisons. See the CheckMode table be-
low.
Compare string for different CheckModes.
const byte *CompareString
int Length Length of the CompareString in bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.17 BLEConnectToDevice
This function connects a device with Address (MAC) and AdressType. The Address and Type can be
requested with the function BLEGetAddress(..) described above.
bool BLEConnectToDevice
(
const byte *Address,
byte AddressType
);
Parameters:
const byte *Address The address of a device to connect to with 6 bytes Hex.
byte AddressType The type of the address. Possible values are:
0 = public address,
1 = random address,
4 = Classic Bluetooth address.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.18 BLEDisconnectFromDevice
Parameters: None.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.19 BLEGattGetAttribute
Parameters:
TBLEUUID *BLEUUID Returns the UUID of the discovered field.
byte *Handle Returns the handle of the GATT field that was found.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.20 BLEGattGetValue
Parameters:
int ReadMode Mode parameter for different read modes. See table ReadMode below.
unsigned long GattHandleDepending on the read mode, specify a charcteristic or service handle of the
GATT field.
const TBLEUUID *BLEUUID Depending on the read mode, specify the UUID of the GATT field.
byte *AttrOpcode Returns the Attribute Opcode of the read GATT field. See table AttrOpcode
below.
byte *Data The read data is returned by this parameter.
int *Len This parameter contains the length of data from the read GATT field. If the
length is 0, the Data are not valid.
int MaxLen The max length of the read data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.21 BLEGattSetValue
Parameters:
int WriteMode Mode parameter for different write modes. See table WriteMode below.
unsigned long GattHandleSpecify the characteristic handle of the GATT for writing data.
int Offset Specify the starting address for writing data. The valid range of this param-
eter is 0 to Len-1.
const byte *Data The passed write data buffer.
int DataLength This parameter holds the length of data which shall be written to the GATT.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.22 BLECommand
int BLECommand
(
int CommandCode,
int Parameter
)
Parameters:
int CommandCode Mode parameter for a connection. See table CommandCode below.
int Parameter For more information, see the CommandCode table.
Return: The return value is specified in the CommandCode table.
30.23 BLESecurity
Parameters:
int SMMode Mode parameter for different security modes. See table SMMode below.
unsigned long Flag1 For more information, see the SMMode table.
unsigned long Flag2 For more information, see the SMMode table.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.24 BLESecuritySetOob
Parameters:
int SMOOBMode Mode parameter for different OOB modes. See table SMOOBMode below.
const byte *OobData OOB data to be written. For more information, see the SMOOBMode table.
int DataLength This parameter holds the length of OobData which shall be written. For more
information, see the SMOOBMode table.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.25 BLESecurityUseScOob
This command can be used to enable the use of OOB data (out-of-band encryption data) for a device for
secure connections pairing. The enabling will genarate new OOB data and confirm values which can be
sent to the remote device. After enabling the secure connections OOB data, the remote devices OOB data
can be set with BLESecuritySetOob(BLE_SM_SET_SC_REMOTE_OOB_DATA, ...). Calling this function
will erase any set remote device OOB data and confirm values. The device will not allow any other kind
of bonding if OOB data is set. The secure connections OOB data cannot be enabled simultaneously with
legacy pairing OOB data.
bool BLESecurityUseScOob
(
int Enable,
byte *OobData,
int *Length,
int MaxLength
)
Parameters:
int Enable Enable OOB with secure connections pairing. Values:
0: disable
1: enable
byte *OobData Returned OOB data. 32-byte array. The first 16-bytes contain randomly
generated OOB data and the last 16-bytes confirm value.
int *Length This parameter contains the length of OOB data.
int MaxLength The max length of OOB data.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.26 BLESetStreamingMode
This function initialize the streaming mode for byte or block data transfer. The data are read from and
written to CHANNEL_BLE.
bool BLESetStreamingMode
(
int ConnMode,
int GattMode,
int TransferMode
)
Parameters:
int ConnMode Mode parameter for different connection modes. See table ConnMode be-
low.
int GattMode Mode parameter for different GATT modes. See table GattMode below.
int TransferMode Mode parameter for different transfer modes. See table TransferMode be-
low.
Return: If the operation was successful, the return value is true, otherwise it is
false.
30.27 BLESetStreamingUUID
This function set the UUIDs for the data streaming (see function BLESetStreamingMode(..)).
bool BLESetStreamingUUID(
const byte *ServiceUUID,
int ServiceUUIDLength,
const byte *CharacUUID,
int CharacUUIDLength
)
Parameters:
const byte *ServiceUUID 16-bit or 128-bit Service UUID of the GATT (Client or Server) for Streaming.
int ServiceUUIDLength Length of the Service UUID in bytes (e.g. 2 or 16 bytes).
const byte *CharacUUID 16-bit or 128-bit Characteristic UUID of the GATT (Client or Server) for
Streaming.
int CharacUUIDLength Length of the Characteristic UUID in bytes (e.g. 2 or 16 bytes).
Return: If the operation was successful, the return value is true, otherwise it is
false.
This chapter handles the usage of ISO7816 compliant Integrated Circuit Cards such as ID-1 or SAM
(Secure Access Module) cards. The TWN4 ISO7816 API offers different system functions for covering
different imaginable scenarios. A typical communication flow with contact cards looks like this:
This function shall be used to query information of the physical card slot status, e.g. to find out if a card is
inserted or not. The function returns the slot status in CCID compliant style, this means it return information
about slot status, error information and clock status. The internal state of the card is not changed. Please
note, depending on the used hardware (TWN4 Desktop or TWN4 SmartCard) the amount of retrievable
information differs.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
TISO7816SlotStatus* The card slot status is returned by this parameter. See the definition of
SlotStatus TISO7816SlotStatus for meaning of each member.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used to activate and initialize communication with the card inserted in one of the
slots connected to the TWN4 reader. All communication parameters are reset to default. Depending on
the hardware platform, the reader shows different behaviour regarding reset-handling of the card: On
TWN4 Desktop, calling this function always leads to a warm reset, on TWN4 SmartCard, the first call
performs a cold reset and any subsequent function call leads to a warm reset until the card is deactivated.
The result of the entire operation is the receipt of the Answer To Reset (ATR) from the card. Based on
the content of the ATR, the user may decide how to further proceed with the card. Note that selection of
voltage level is only available for TWN4 SmartCard.
bool ISO7816_IccPowerOn
(
int Channel,
byte* ATR,
int* ATRByteCnt,
int MaxATRByteCnt,
byte bPowerSelect,
TISO7816StatusReg* bStatus,
byte* bError
);
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
byte* ATR After successful completion of this function, the buffer referred by this pa-
rameter holds the ATR which was read from the card. Take care for ade-
quate dimensioning.
int* ATRByteCnt After successful completion of this function, this parameter holds the number
of bytes, the ATR contains.
int MaxATRByteCnt This parameter holds the array-size of ATR in bytes.
byte bPowerSelect Specify the operating voltage level which shall be used for the card.
Valid values are ISO7816_POWERSELECT_AUTO, ISO7816_POWERSELECT_5V,
ISO7816_POWERSELECT_3V, or ISO7816_POWERSELECT_1V8, use one of these
predefined constants.
TISO7816StatusReg* The CCID compliant slot status register is returned by this parameter. See
bStatus the definition of TISO7816StatusReg for meaning of the different bit fields.
byte* bError The CCID compliant error code is returned by this parameter.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used to deactivate and power off the card. When this function was called on TWN4
SmartCard reader, a subsequent call of IccPowerOn() leads to a cold reset of the card.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
TISO7816SlotStatus* The card slot status is returned by this parameter. See the definition of
SlotStatus TISO7816SlotStatus for meaning of each member.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used to assign new communication settings to the respective card slot. After call-
ing this function, the communication parameters which have been negotiated with the card during Pro-
tocol And Parameter Selection (PPS) become valid. For issuing a PPS, please refer to the function
ISO7816_Transceive. Specific communication parameters must be obtained from the ATR, for detailed
information refer to standard ISO7816-3.
bool ISO7816_SetCommSettings
(
int Channel,
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
const The new communication settings are passed by this parameter. See the
TISO7816CommSettings* definition of TISO7816CommSettings for meaning of each member.
CommSettings
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used for byte-wise communication with the card.
bool ISO7816_Transceive
(
int Channel,
const byte* TX,
int LenTX,
byte* RX,
int* LenRX,
int MaxRXByteCnt,
TISO7816StatusReg* bStatus,
byte* bError
);
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
const byte* TX This buffer holds the data which shall be transmitted to the card.
int LenTX This parameter specifies the data-length in bytes which shall be transmitted
to the card.
byte* RX This buffer holds the data which was read from the card. Take care for
adequate dimensioning.
int* LenRX After successful completion of this function, this parameter holds the number
of bytes read from the card.
int MaxRXByteCnt This parameter holds the array-size of RX in bytes.
TISO7816StatusReg* The CCID compliant slot status register is returned by this parameter. See
bStatus the definition of TISO7816StatusReg for meaning of the different bit fields.
byte* bError The CCID compliant error code is returned by this parameter.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This function shall be used for APDU exchange based on T=0/T=1 protocol according to ISO7816-3.
bool ISO7816_ExchangeAPDU
(
int Channel,
const TISO7816_ProtocolHeader* Header,
const byte* TXData,
int TXByteCnt,
byte* RXData,
int* RXByteCnt,
int MaxRXByteCnt,
uint16_t* StatusWord
);
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
const This parameter holds basic APDU information.
TISO7816_ProtocolHeader
*Header
const byte* TXData This buffer holds the data field of the APDU.
int TXByteCnt This parameter specifies the data-length in bytes of the data-field.
byte* RXData This buffer holds the data-field of the received APDU.
int* RXByteCnt After successful completion of this function, this parameters holds the data-
field size of the received APDU.
int MaxRXByteCnt This parameter holds the array-size of RXData in bytes.
uint16_t* StatusWord This parameter holds the status word received from the card.
Return: If the operation was successful, the return value is true, otherwise it is
false.
31.1.7 Examples
The following example shows how to make a PPS with an ISO7816 card.
bool ISO7816_PPS(int Channel, byte Protocol, byte* bmFindexDindex)
{
byte Cmd[4];
byte Res[4];
int TxByteCnt;
int RxByteCnt;
TISO7816StatusReg bStatus;
byte bError;
The following example shows how to prepare a ISO7816 card for communication at T=1 protocol and
exchange APDUs.
byte ATR[32];
int ATRByteCnt;
TISO7816SlotStatus SlotStatus;
TProtocolDataT1 ProtocolDataT1;
TISO7816CommSettings CommSettings;
TISO7816_ProtocolHeader Header;
byte TXData[128];
byte RXData[128];
int RXByteCnt;
uint16_t SW12;
MainLoop:
while (true)
{
// Is a card inserted in CHANNEL_SC1?
if (!ISO7816_GetSlotStatus(CHANNEL_SC1, &SlotStatus))
goto MainLoop;
// Card slot empty?
if (SlotStatus.bStatus.bmICCStatus == ISO7816_NOICCPRESENT)
goto MainLoop;
// Perform activation of the card and receive ATR
if (!ISO7816_IccPowerOn
(
CHANNEL_SC1,
ATR,
&ATRByteCnt,
sizeof(ATR),
ISO7816_POWERSELECT_5V,
&SlotStatus.bStatus,
&SlotStatus.bError
))
goto MainLoop;
// We expect the card to be present and active
if (SlotStatus.bStatus.bmICCStatus != ISO7816_ICCPRESENTANDACTIVE)
goto MainLoop;
// Perform PPS for T=1 protocol
if (!ISO7816_PPS(CHANNEL_SC1, ISO7816_PROTOCOL_T1,
&ProtocolDataT1.bmFindexDindex))
goto MainLoop;
// Setup ISO7816 UART accordingly
CommSettings.Protocol = ISO7816_PROTOCOL_T1;
CommSettings.Freq = ISO7816_FREQUENCY_5000000;
CommSettings.F = 512;
CommSettings.D = 12;
CommSettings.ProtocolData.T1 = ProtocolDataT1;
if (!ISO7816_SetCommSettings(CHANNEL_SC1, &CommSettings))
goto MainLoop;
// Let’s prepare our APDU. We want to select the Masterfile (MF)
// of a PKI card by its SFI (0x3F00).
Header.CLA = 0x00;
Header.INS = 0xA4;
Header.P1 = 0x00;
Header.P2 = 0x00;
Header.Lc = 0x0002;
Header.Le = 0x0000;
Header.Flags.LePresent = true;
Header.Flags.ExtendedAPDU = false;
TXData[0] = 0x3F;
TXData[1] = 0x00;
This chapter shows how to use TWN4 with contact based memory cards such as SLE44xx or compatible
cards. In order to query the card slot insertion state, the function ISO7816_GetSlotStatus can be used.
Use this function to retrieve the ATR (Answer To Reset) from an inserted card.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
byte* ATR The card’s ATR is returned by this buffer. The function always returns 4
bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Address Specify the start address in memory for reading.
byte* Data This buffer holds the data read from the card. Take care for proper dimen-
sioning.
int ByteCnt Specify the number of bytes to be read.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write one byte of data to the main memory.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Address Specify the address in memory to be written.
byte Value Specify the data byte to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read out the four bytes of Security Memory.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
byte* SecMemData This buffer holds the Security Memory data read from the card. The function
always returns 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write one byte of data to the Security Memory.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Address Specify the address in Security Memory to be written.
byte SecMemData Specify the data byte to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to read out the four bytes of Protection Memory.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
byte* ProtMemData This buffer holds the Protection Memory data read from the card. The func-
tion always returns 4 bytes.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to write one byte of data to the Protection Memory.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Address Specify the address in Protection Memory to be written.
byte ProtMemData Specify the data byte to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
Use this function to transmit one byte of verification input to the card.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Address Specify the address of verification data byte.
byte VerificationData Specify the verification data byte to be transfered to the card.
Return: If the operation was successful, the return value is true, otherwise it is
false.
This chapter shows how to use TWN4 with contact based I2C memory cards. In order to query the card
slot insertion state, the function ISO7816_GetSlotStatus can be used.
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Addr Specify the start address in memory for reading.
byte* Data This buffer holds the data read from the card. Take care for proper dimen-
sioning.
int ByteCnt Specify the number of bytes to be read.
Return: If the operation was successful, the return value is true, otherwise it is
false.
bool I2CCard_Write(int Channel, int Addr, const byte* Data, int ByteCnt);
Parameters:
int Channel Specify a communication channel by this parameter. Valid values are
CHANNEL_SAM1 through CHANNEL_SAM4 or CHANNEL_SC1, use one of these pre-
defined constants.
int Addr Specify the start address in memory for the write operation.
const byte* Data Specify data to be written.
int ByteCnt Specify the number of bytes to be written.
Return: If the operation was successful, the return value is true, otherwise it is
false.
32 Cryptographic Operations
The cryptographic API incorporates methods for encryption/decryption of data, these are Triple-DES (Data
Encryption Standard) or AES (Advanced Encryption Standard). TDES is available in two versions that
support different key-lengths: 128 bit (TDES2K) and 192 bit (TDES3K).
The implementation of TDES is based on FIPS PUB 46-3. The method always operates on entire data
blocks of 8 bytes. The DES algorithm is passed three times for one TDES operation. In case of TDES2K,
the 128 bit key is hereby split into two parts: K1 and K2. In case of TDES3K, the 192 bit key is split into
three parts: K1, K2 and K3.
The implementation of AES is based on FIPS PUB 197. The method always operates on entire data blocks
of 16 bytes, the key-length is 128 bit.
The cryptographic API may be used to simply encrypt/decrypt a single block or to encrypt/decrypt a chain
of blocks using the CBC-method (Ciphered Block Chaining).
In CBC mode, every ciphering operation depends on the foregoing step, this is achieved by involving the
so-called Init Vector IV. The first CBC-operation usually works with an Init Vector that is set to zero.
For encryption, a plain data block P is logically XOR-ed with this Init Vector before it comes to encryption.
The result is a ciphered block C which serves as Init Vector for the next operation. See the schematic
below for details:
P1 P2 Pn
IV ...
C1 C2 Cn
If a ciphered block C is decrypted, the result is logically XOR-ed with the Init Vector. See the schematic
below for details:
C1 C2 Cn
IV ...
P1 P2 Pn
32.1 Initialization
The cryptographic API has to be initialized before it can be used. During initialization the key is passed to
the cryptographic method and assigned to a cryptographic environment. After initialization the functions for
encryption and decryption are set up for the desired cryptographic mode. If a cryptographic environment
is configured for CBC-operation, the internally managed Init Vector is automatically reset to zero.
void Crypto_Init
(
int CryptoEnv,
int CryptoMode,
const byte* Key,
int KeyByteCnt
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
int CryptoMode Specify the mode of cryptographic operation. Choose either
one of the predefined non-CBC constants CRYPTOMODE_3DES,
CRYPTOMODE_3K3DES, CRYPTOMODE_AES128 or one of the pre-defined
CBC constants CRYPTOMODE_CBC_DES, CRYPTOMODE_CBC_DFN_DES,
CRYPTOMODE_CBC_3DES, CRYPTOMODE_CBC_DFN_3DES, CRYPTOMODE_CBC_3K3DES,
CRYPTOMODE_CBC_AES128.
const byte* Key The key is passed by this parameter. Depending on the specified crypto
mode, the key-length is either 16 or 24 bytes.
int KeyByteCnt Specify the length of the key in bytes.
Return: This function has no return value.
32.2 Encrypt
void Encrypt
(
int CryptoEnv,
const byte* PlainBlock,
byte* CipheredBlock,
int BlockByteCnt
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
const byte* PlainBlock Pointer to the array, that contains the plain data block to be encrypted.
byte* CipheredBlock Pointer to the array, that receives the encrypted data block. Take care for
proper dimensioning.
int BlockByteCnt Specify the number of bytes of a block.
Return: This function has no return value.
32.3 Decrypt
void Decrypt
(
int CryptoEnv,
const byte* CipheredBlock,
byte* PlainBlock,
int BlockByteCnt
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
const byte* Pointer to the array, that holds the encrypted data block.
CipheredBlock
const byte* PlainBlock Pointer to the array, that receives the decrypted data block. Take care for
proper dimensioning.
int BlockByteCnt Specify the number of bytes of a block.
Return: This function has no return value.
Use this function to manually reset the internally managed Init Vector of a cryptographic environment to
zero.
void CBC_ResetInitVector
(
int CryptoEnv
);
Parameters:
int CryptoEnv Specify a cryptographic environment by this parameter. The valid range is
CRYPTO_ENV0 to CRYPTO_ENV3, use one of these predefined constants.
Return: This function has no return value.
33 Storage Functions
33.1.1 FSMount
Before any access to files can be performed, the appropriate file system must be mounted. Following steps
are performed by function FSMount:
• Check, if the specified volume contains a valid file system.
Parameters:
int StorageID Specifies the volume, which should be mounted. Currently, there is one stor-
age available, the internal flash. The appropriate definition for this storage
is SID_INTERNALFLASH
int Mode Specifies the mode in which the volume is mounted. This can be
FS_MOUNT_NONE (equivalent to a unmount), FS_MOUNT_READONLY (no write
access to storage possible)or FS_MOUNT_READWRITE (full read/write access).
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.1.2 FSFormat
This function prepares the storage memory of TWN4 for further file operations.
— WARNING — WARNING — WARNING —
All data, which is stored on the file system will be irrecoverable deleted by calling this function!
bool FSFormat(int StorageID,int MagicValue)
Parameters:
int StorageID Specifies the volume, which should be formatted.
int MagicValue In order to avoid accidantely format of a volume, an appropriate parameter
for MagicValue must be specified. There is a definition for this magic value,
which is FS_FORMATMAGICVALUE.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.2.1 FSOpen
This function must be called in order to begin any read or write operation from/to a file.
Following definitions for the parameter mode are valid:
FS_READ Open a file for read access. If the file not exists, an error is generated. The
position of the read pointer is set to zero, thus to the start of the file.
FS_WRITE Open a file for write access. An empty file is created independently of if the
file already exists or not, thus content of an earlier version of that file will be
deleted.
FS_APPEND Open a file for write access. If the file does not exist, a new file is created. If
the file already exists, the file pointer is moved to the end of the file, which
means, that newly written data is appended to data of existing file.
Following further considerations:
• A file can be opened one time in mode FS_WRITE or FS_APPEND, but never, if it is already opened by
any other file operation.
• A file can be opened many times in mode FS_READ, but never, if it is already opened in mode
FS_WRITE or FS_APPEND by another file operation.
bool FSOpen(int FileEnv,int StorageID,uint32_t FileID,int Mode)
Parameters:
int FileEnv Specifies the environment to be used for the file operation. Up to four file
operations can be opened at a time. The appropriate defintions for these
environments are FILE_ENV0 - FILE_ENV3.
int StorageID Specifies the storage on which the file resides. Currently, this parameter can
be SID_INTERNALFLASH only.
uint32_t FileID Specifies the ID of a file. The file ID is a reduced version of file name and
be understood as such. File ID is an integer number from 1 to 232 − 1, thus
0x00000000 to 0xFFFFFFFF.
int Mode Specifies, how the file is accessed (see above).
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
X
33.2.2 FSClose
This function is used to terminate a file operation. Several actions are taken, when this function is
called:
• Pending data is written to the storage system.
• If this is the last file being closed, the file system is finalized in terms, that the even loss of the power
will restore this now achieved state.
bool FSClose(int FileEnv)
Parameters:
int FileEnv Specifies the environment to be used for the file operation.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.2.3 FSCloseAll
This function is closing all opened file operations throughout all mounted storages. This function avoids
keeping track of opened file operations.
void FSCloseAll(void)
Parameters: None.
Return: None.
33.2.4 FSSeek
Read and write operations from/to a file are implemented via a file pointer, which references the point, from
which next data is read or where next data is written. With this function, the file pointer can be moved
throughout a file and furthermore in relation to a specific point of the file.
FS_POSABS Move file position in relation to the start of the file. This results in a move of
the file pointer to an absolute position.
FS_POSREL Move the file pointer in relation to the current position. This allows an easy
skip of a number of bytes of the file.
FS_POSEND Move the file pointer in relation to the end of the file. This allows to move to
the end of the file without knowledge and independent of the length of a file.
bool FSSeek(int FileEnv,int Origin,int Pos)
Parameters:
int FileEnv Specifies the environment to be used for the file operation.
int Origin Specifies the reference point, from which the new file position is calculated
(see above).
int Pos Specifies the number of bytes in relation to the reference point. A negative
value is treated as position before reference point, a positive value is treated
as position behind the reference point.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.2.5 FSTell
This function returns the position of the file pointer in relation to a reference point. Please note that in
consequence, specifying FS_POSREL as origin must always return the value zero.
bool FSTell(int FileEnv,int Origin,int *Pos)
Parameters:
int FileEnv Specifies the environment to be used for the file operation.
int Origin Specifies the reference point, under which the current position is calculated
(see function FSSeek).
int *Pos A pointer to an integer, which will receive the value of the position.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.2.6 FSReadBytes
Read bytes from a file, which has been opened in mode FS_READ before. Use function FSOpen to open the
file accordingly.
The function generates the error ERR_ENDOFFILE, if less than the requested number of bytes were read
from the file or if there are no more bytes left to be read from the file.
bool FSReadBytes(int FileEnv,void *Data,int ByteCount,int *BytesRead)
Parameters:
int FileEnv Specifies the environment to be used for the file operation.
void *Data Pointer to an array of bytes, which receives read data.
int ByteCount Number of bytes, which should be read from the file.
int *BytesRead Pointer to an integer, which receives the number of actually read bytes. The
received value is valid even if the function returns with an error.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.2.7 FSWriteBytes
Write bytes to a file, which has been opened in mode FS_WRITE or FS_APPEND before. Use function FSOpen
to open the file accordingly.
bool FSWriteBytes(int FileEnv,const void *Data,int ByteCount,int *BytesWritten)
Parameters:
int FileEnv Specifies the environment to be used for the file operation.
const void *Data Pointer to an array of bytes, which contains data to be written.
int ByteCount Number of bytes, which should be written to the file.
int *BytesWritten Pointer to an integer, which receives the number of actually written bytes.
The received value is valid even if the function returns with an error.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.3.1 FSFindFirst
The functions FSFindFirst/FSFindNext implement the possibility to enumerate the files contained in a
files system. In order to begin enumeration of files the function FSFindFirst must be called.
The members of a directory entry are stored in a structure of type TFileInfot. The members of the
structure are:
ID The file ID.
Length The length of the file.
bool FSFindFirst(int StorageID,TFileInfo *pFileInfo)
Parameters:
int StorageID Storage ID of the file system, where files should be enumerated.
TFileInfo *pFileInfo Pointer to a structure of type TFileInfo which receives a directory entry.
Return: If the operation was successful, the return value is true, otherwise it is
false. If no directory entry was found the error code ERR_FILENOTFOUND is
generated. The concrete error code can be retrieved with system function
GetLastError.
33.3.2 FSFindNext
The functions FSFindFirst/FSFindNext implement the possibility to enumerate the files contained in a
files system. In order to continue enumeration, once first entry has been retrieved with function FSFindFirst,
the function FSFindNext must be called.
bool FSFindNext(TFileInfo *pFileInfo)
Parameters:
TFileInfo *pFileInfo Pointer to a structure of type TFileInfo which receives a directory entry.
Return: If the operation was successful, the return value is true, otherwise it is
false. If no directory entry was found the error code ERR_FILENOTFOUND is
generated. The concrete error code can be retrieved with system function
GetLastError.
33.3.3 FSDelete
Use function FSDelete to delete files from the file system. A file, which is currently opened can not be
deleted.
bool FSDelete(int StorageID,uint32_t FileID)
Parameters:
int StorageID Storage ID of the file in question.
uint32_t FileID File ID of the file to be deleted.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.3.4 FSRename
Parameters:
int StorageID Storage ID of the file in question.
uint32_t OldFileID Current file ID of the file to be renamed.
uint32_t NewFileID Future file ID of the file to be renamed.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
33.4.1 FSGetStorageInfo
Parameters:
int StorageID ID of the storage in question.
TStorageInfo Pointer to a structure of type TStorageInfo, which receives the requested
*pStorageInfo information.
Return: If the operation was successful, the return value is true, otherwise it
is false. A concrete error code can be retrieved with system function
GetLastError.
The structure TStorageInfo is defined as follows:
typedef struct
{
byte ID;
uint32_t Size;
uint32_t Free;
} TStorageInfo;
where:
33.5 Examples
This is an example for a function, which reads a complete file from the file system. The file system must
have been mounted before with function FSMount.
bool ReadFile1(uint32_t FileID,byte *Data,int *FileLength,int MaxFileLength)
{
if (!FSOpen(FILE_ENV0,SID_INTERNALFLASH,FileID,FS_READ))
return false;
FSReadBytes(FILE_ENV0,Data,MaxFileLength,FileLength);
int LastError = GetLastError();
FSClose(FILE_ENV0);
if (LastError != ERR_NONE && LastError != ERR_ENDOFFILE)
return false;
// Function was successfully completed
return true;
}
Here is an example for a function, which reads a complete file from the file system but in portions of
256 bytes. This might be useful, if the implementation is actually done on a host, which is doing system
calls indirectly via TWN4 Simple Protocol. The file system must have been mounted before with function
FSMount.
bool ReadFile2(uint32_t FileID,byte *Data,int *Length,int ExpectedLength)
{
*Length = 0;
if (!FSOpen(FILE_ENV0,SID_INTERNALFLASH,FileID,FS_READ))
return false;
bool ReadSuccess;
int RemainingBytes = ExpectedLength;
do
{
if (RemainingBytes == 0)
{
FSClose(FILE_ENV0);
return true;
}
const int BlockSize = 256;
int BytesToRead = RemainingBytes;
if (BytesToRead > BlockSize)
BytesToRead = BlockSize;
int BytesRead;
ReadSuccess = FSReadBytes(FILE_ENV0,Data,BytesToRead,&BytesRead);
Data += BytesRead;
*Length += BytesRead;
RemainingBytes -= BytesRead;
}
while (ReadSuccess);
int LastError = GetLastError();
FSClose(FILE_ENV0);
if (LastError != ERR_NONE && LastError != ERR_ENDOFFILE)
return false;
// Function was successfully completed
return true;
}
Here is an example for a function, which writes a complete file to the file system in portions of 256 bytes.
This might be useful, if the implementation is actually done on a host, which is doing system calls indirectly
via TWN4 Simple Protocol. The file system must have been mounted before with function FSMount.
bool WriteFile(uint32_t FileID,byte *Data,int Length)
{
if (!FSOpen(FILE_ENV0,SID_INTERNALFLASH,FileID,FS_WRITE))
return false;
bool WriteSuccess;
int RemainingBytes = Length;
do
{
if (RemainingBytes == 0)
{
FSClose(FILE_ENV0);
return true;
}
const int BlockSize = 256;
int BytesToWrite = RemainingBytes;
if (BytesToWrite > BlockSize)
BytesToWrite = BlockSize;
int BytesWritten;
WriteSuccess = FSWriteBytes(FILE_ENV0,Data,BytesToWrite,&BytesWritten);
Data += BytesWritten;
RemainingBytes -= BytesWritten;
}
while (WriteSuccess);
int LastError = GetLastError();
FSClose(FILE_ENV0);
if (LastError != ERR_NONE)
return false;
// Function was successfully completed
return true;
}
34 System Parameters
The TWN4 App-system provides methods of setting up paramaters before or during runtime of Apps.
• In order to set up parameters before the App is started, a so-called Manifest can be specified as part
of an App.
• In order to set up parameters during normal execution of an App there is the system function
SetParameters.
This section describes the specification of a Manifest and all available parameters. See chapter "System
Functions" for a description of function SetParameters.
Parameters for a Manifest or the system function SetParameters are specified in the TLV format. The
TLV format specifies a chain of parameters with variable type and length. This format must follow following
rules:
• Every entry (except the last entry) is a sequence of 3 items. The 3 items are ’Type’, ’Length’ and
’Value’.
• The name of the parameter is associated to ’Type’, the length of
• the value is associated to ’Length’ and the value itself is associated to ’Value’
• The TLV list must be terminated with an item consisting of just the type. This type must contain the
value TLV_END.
34.2 Manifest
The intention for specifying a Manifest as part of an App could be to avoid opening of communication
channels in order to further reduce current consumption. Another could be to modify behaviour of the USB
section of TWN4.
The specification of a Manifest is pretty simple:
Define an array of bytes with the key-name Manifest. This will point the firmware of TWN4 to the position
where the parameters of interest are stored. Here is an example:
Example:
// This sample demonstrates the specification of a Manifest:
const byte *Manifest =
{
OPEN_PORTS, 1, OPEN_PORT_USB_MSK, // Open USB channel only
TLV_END // End of TLV
};
35 System Errors
Here is a list of all error codes, which are generated by the firmware of TWN4. The error codes can be
retrieved with function GetLastError.
In the current version of the firmware, storage functions (FS...) are generating such errors.
ERR_TRANSACTIONLIMIT The limit of changes in the file system is reached, which is possible
within one transactions.
ERR_UNKNOWNFS The file system on the specified storage is not supported by the current
firmware.
ERR_FILENOTFOUND The specified file was not found.
ERR_FILEALREADYEXISTS The specified file already exists.
ERR_ENDOFFILE The end of the file was reached. There is no more data to be read.
Note: This error code is generated even the system function returned
successful execution.
ERR_STORAGENOTFOUND The specified storage was not found, e.g. because it is not mounted.
ERR_STORAGEALREADYMOUNTED The specified storage is already mounted.
ERR_ACCESSDENIED The access to a file was denied, e.g. write access to a file in a storage,
which is mounted as read only.
ERR_FILECORRUPT The specified file is corrupt in terms of a corrupted file system.
ERR_INVALIDFILEENV The specified environment is invalid.
ERR_INVALIDFILEID The specified file ID is invalid.
ERR_RESOURCELIMIT The maximum number of available resources have bee occupied.
Please see file twn4.sys.h (which can be found in local directory Tools\sys\ of the developer pack) for
concrete numbers, which are behind the definitions.
36 Runtime Library
There is a couple of functions, which are not part of the firmware of TWN4. Instead, they are statically
linked to the App.
There are several intentions for such functions:
• Provide functions instead of having similar code in each App.
• Provide an API at a higher level to simplify writing Apps.
• Maintain a degree of compatibility to TWN3.
36.1.1 StartTimer
Parameters:
unsigned long Duration Time in milliseconds, till function TestTimer returns true.
Return: None.
36.1.2 StopTimer
Stop the timer, thus function TestTimer will never return true.
void StopTimer(void);
Parameters: None.
Return: None.
36.1.3 TestTimer
Test, if the timer reached the timeout which was programmed by function StartTimer.
bool TestTimer(void);
Parameters: None.
Return: If the timeout has been reached, the function returns true, otherwise, it
return false.
36.2.1 SetHostChannel
Specify the channel, where communication should take place. By default, the channel is determined
by the connected communication cable, which is therefore either USB (TWN4 USB) or COM1 (TWN4
RS232).
void SetHostChannel(int Channel)
Parameters:
int Channel Specifies the communication channel to be used. This might
be CHANNEL_USB, CHANNEL_COM1, CHANNEL_COM2 or CHANNEL_I2C or
CHANNEL_NONE. If CHANNEL_NONE is specified, channel will be choosen de-
pending on connected communication cable.
Return: None.
36.2.2 HostTestByte
Use this function to check if there is a byte available in the input buffer of the host-channel.
bool HostTestByte(void)
Parameters: None.
Return: If there is a byte available, the return value is true, otherwise it is false.
36.2.3 HostReadByte
Use this function to read a byte from the input buffer of the host-channel. If there is no byte available, the
function blocks until there is one.
byte HostReadByte(void)
Parameters: None.
Return: The byte which was read from the input buffer.
36.2.4 HostTestChar
Test if a character is available from the host. The character can be read with function HostReadChar.
bool HostTestChar(void)
Parameters: None.
Return: true if at least one character arrived, otherwise false.
36.2.5 HostReadChar
Receive a character from the host. This is a blocking function. This means, it is waiting, till a character is
available.
char HostReadChar(void)
Parameters: None.
Return: The character, which was read from the host.
36.2.6 HostWriteByte
Use this function to send one byte to the host through the actually configured host-channel. If the output
buffer is completely occupied, the function blocks until there is enough space.
Parameters:
byte Byte The byte to be sent.
Return: None.
36.2.7 HostWriteChar
Send a character to the host. This is a blocking function. This means, it is waiting, till there is storage in
the output buffer, to transmit the character.
void HostWriteChar(char Char)
Parameters:
char Char The character to be sent to the host.
Return: None.
36.2.8 HostWriteString
Send a string to the host. The string must be terminated with a null character. The string is sent without
the null character.
void HostWriteString(const char *String)
Parameters:
const char *String Pointer to the string to be sent.
Return: None.
36.2.9 HostWriteRadix
Send a number to the host in ASCII format. The number is specified by an array of bytes containing the
binary data.
void HostWriteRadix(const byte *ID,int BitCnt,int DigitCnt,int Radix)
Parameters:
const byte *ID Pointer to the array of bytes.
int BitCnt Number of bits stored in the array.
int DigitCnt Number of output digits.
int Radix Base for conversion from binary to ASCII. Use:
• 2 for binary conversion
• 8 for octal conversion
• 10 for decimal conversion
• 16 for hexadecimal conversion
Return: None.
36.2.10 HostWriteBin
Send a binary number to the host in ASCII format. The number is specified by an array of bytes containing
the binary data.
void HostWriteBin(const byte *ID,int BitCnt,int DigitCnt)
Parameters:
const byte *ID Pointer to the array of bytes.
int BitCnt Number of bits stored in the array.
DigitCnt Number of output digits.
Return: None.
36.2.11 HostWriteDec
Send a decimal number to the host in ASCII format. The number is specified by an array of bytes containing
the binary data.
Parameters:
const byte *ID Pointer to the array of bytes.
int BitCnt Number of bits stored in the array.
DigitCnt Number of output digits.
Return: None.
36.2.12 HostWriteHex
Send a hexadecimal number to the host in ASCII format. The number is specified by an array of bytes
containing the binary data.
void HostWriteHex(const byte *ID,int BitCnt,int DigitCnt)
Parameters:
const byte *ID Pointer to the array of bytes.
int BitCnt Number of bits stored in the array.
DigitCnt Number of output digits.
Return: None.
36.2.13 HostWriteVersion
Send the firmware version to the host. This function is sending the result of function GetVersionString
to the host.
void HostWriteVersion(void)
Parameters: None.
Return: None.
36.3.1 SetVolume
Parameters:
int NewVolume Specify the volume in percent from 0 to 100.
Return: None.
36.3.2 GetVolume
Parameters: None.
Return: Current volume in arange from 0 to 100.
36.3.3 BeepLow
Parameters: None.
Return: None.
36.3.4 BeepHigh
Parameters: None.
Return: None.
36.4.1 ConvertTagTypeToTWN3
This functions converts a tag type from the TWN4 system to TWN3 system. Due to the fact that TWN4
covers a broader range of transponders, the situation might occure, that a conversion is not possible.
Under that circumstance the TWN3 value TAGTYPE_NONE (0) is returned.
int ConvertTagTypeToTWN3(int TagTypeTWN4)
Parameters:
int TagTypeTWN4 Tag type as returned e.g. by TWN4 system function SearchTag.
Return: Corresponding tag type as it would be returned by TWN3 system function
TagSearch.
int main(void)
{
InitSimpleProtocol(GetHostChannel(),PRS_COMM_MODE_ASCII | PRS_COMM_CRC_OFF);
while (true)
{
if (SimpleProtoTestCommand())
{
SimpleProtoExecuteCommand();
SimpleProtoSendResponse();
}
}
}
36.5.1 SimpleProtoInit
Use this function to prepare the Simple Protocol for operation. Before starting this function, it is possible
to e.g. prepare a serial port with appropriate communication parameters.
bool SimpleProtoInit(int Channel,int Mode)
Parameters:
int Channel This parameter specifies the communication channel for the Simple Proto-
col. This can be one the channels as defined by the system I/O functions.
int Mode This parameter specified the mode of communication. It is a or-operation,
which combines mode (PRS_COMM_MODE_ASCII or PRS_COMM_MODE_BINARY
and CRC (COMM_CRC_OFF or PRS_COMM_CRC_ON).
Return: This functions return true, if initialization was successful. Otherwise it re-
turns false.
36.5.2 SimpleProtoTestCommand
This is a none-blocking function, which polls for the availabilty of a command from the host. If the function
returns true, a command is available. The command is stored in the global variables SimpleProtoMessage
and SimpleProtoMessageLength.
bool SimpleProtoTestCommand(void)
Parameters: None.
Return: This functions return true, if a command became available. Otherwise it
returns false.
36.5.3 SimpleProtoExecuteCommand
This function executes a command stored in the global variables SimpleProtoMessage and SimpleProtoMessageLengt
After execution of the command, these variables contain the response to be sent to the host.
void SimpleProtoExecuteCommand(void)
Parameters: None.
Return: None.
36.5.4 SimpleProtoSendResponse
This function sends a response stored in the global variables SimpleProtoMessage and SimpleProtoMessageLength
to the host.
void SimpleProtoSendResponse(void)
Parameters: None.
Return: None.
Due to reduced functionality of TWN4 MultiTech Mini Reader, several API functions are not available. If an
API function is called, which is not supported by TWN4 MultiTech Mini Reader the device stops execution
of the App and enters exception state (diagnostic LED is flashing three times).
38 Disclaimer
Elatec reserves the right to change any information or data in this document without prior notice. The
distribution and the update of this document is not controlled. Elatec declines all responsibility for the use
of product with any other specifications but the ones mentioned above. Any additional requirement for a
specific custom application has to be validated by the customer himself at his own responsibility. Where
application information is given, it is only advisory and does not form part of the specification.
All referenced brands, product names, service names and trademarks mentioned in this document are the
property of their respective owners.