I've written a small function to format raw data to NDEF and then write it onto a tag.
The main part of the function works without any problems, the only thing that is not working is that it keeps writing 0xFF to the end of the sector instead of 0x00, if it's empty.
CODE:
int write_ndef(FreefareTag tag, uint8_t *data, const uint8_t type, size_t isize) {
uint8_t *ndef_msg;
size_t ndef_msg_len;
int sector_count;
ndef_msg = data;
ndef_msg_len = isize;
uint8_t write_data [4];
printf("Printing raw message :\n");
print_hex(ndef_msg, ndef_msg_len);
size_t encoded_size;
uint8_t *tlv_data = tlv_encode(type, ndef_msg, ndef_msg_len, &encoded_size);
printf("NDEF file is %zu bytes long.\n", encoded_size);
printf("Printing NDEF formatted message :\n");
print_hex(tlv_data, encoded_size);
sector_count = encoded_size / 4;
if((encoded_size%4)!= 0)
sector_count++;
for (size_t i = 0; i < sector_count; i++) {
for (size_t f = 0; f < 4; f++) {
/*once message written fill rest of sector with 0x00*/
if((i * 4 )+ f > encoded_size) {
write_data[f] = 0x00;
}
else {
write_data[f] = tlv_data[(i * 4) + f];
}
}
ntag21x_write(tag, block[i], write_data);/*takes an array with exactly 4 bytes and writes it to given address on given tag*/
}
return 1;
}
The program output is:
It probably has something to do with the way I'm splitting up the data to write it, but I just can't figure out how.
The last (3rd in this case) block of data reads: 0x67, 0x6c, 0xfe, 0xff (instead of 0x00 as it should).
Your test for reaching the end of the encoded data is off by one.
((i * 4) + f) > encoded_size
This is only true starting with the second byte after the end of the TLV encoded data (e.g. if encoded_data == 0
, the test would still be false for i = 0
, f = 1
).
Consequently, you need to modify this condition to
if (((i * 4) + f) >= encoded_size) {
write_data[f] = 0x00;
} else {
write_data[f] = tlv_data[(i * 4) + f];
}