I have a data logger (datasheet) and I am trying to get Battery Voltage using Get Battery Level command (0xAA) but the result is incorrect (negative number). Anyone knows what seems to be a problem?
My source code:
public static double cmdGetBatteryLevel(Tag tag, NfcV nfcvTag) throws IOException {
byte[] comGetBatLvl = new byte[]{
(byte) 0x20, // Flags - addressed
(byte) 0xAA, // Command: Get Battery Level
(byte) 0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // placeholder for tag UID
};
System.arraycopy(tag.getId(), 0, comGetBatLvl, 2, 8);
byte[] replyData = nfcvTag.transceive(comGetBatLvl);
int batCode = replyData[1];
//3V battery
double batLvl = (batCode*6.32) + 1.62;
// 1.5V battery
//double batLvl = (batCode*3.35) + 860;
return batLvl; }
There seem to be two problems in your code:
You are using an incorrect coversion between the received byte value and an integer value.
Bytes (as well as integers) in Java are signed bytes. The temperature logger treats the byte as unsigned though. So when your byte value is in the negative range (upper bit = 1) this sign bit will be extended when your assign the value to an integer variable. In order to cast the byte value to its unsigned integer representation you have to truncate the extended sign bits:
int batCode = replyData[1] & 0x0FF;
The second problem is the units you used in your formula. 6.32 is a value in millivolts while 1.62 is a value in volts. Hence, you should use
double batLvl = (6.32d * batCode / 1000.0d) + 1.62d;
to get the value in volts or
double batLvl = (6.32d * batCode) + 1620.0d;
to get the value in millivolts.