I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.
unsigned long previousMillis = 0;
const long interval = 1000;
char incomingByteA[8];
void setup() {
Serial.begin(9600);
while(!Serial);
Serial1.begin(9600);
while(!Serial1);
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval){
//1 second timer
previousMillis = currentMillis;
Serial1.write('O');
//Send command 'A' to device *noting Serial1 not Serial
for(int n = 0; Serial1.available() < 8; n++) {
incomingByteA[n] = Serial1.read();
//Add each consecutive byte to an array until all 8 bytes have been added
}
float x;
float y;
((byte*)&x)[3] = incomingByteA[0];
//Convert first four bytes into a float
((byte*)&x)[2] = incomingByteA[1];
((byte*)&x)[1] = incomingByteA[2];
((byte*)&x)[0] = incomingByteA[3];
((byte*)&y)[3] = incomingByteA[4];
//Convert final four bytes into a float
((byte*)&y)[2] = incomingByteA[5];
((byte*)&y)[1] = incomingByteA[6];
((byte*)&y)[0] = incomingByteA[7];
Serial.println(x, 4);
}
}
However, when I do Serial.println(x);
, it returns "nan". And if I try to do Serial.println(incomingByteA[2]);
, it returns "?".
The following is the floating point format as per the device protocol:
31: sign of mantissa, 1=negative. 30-23: exponent, biased by 128. 22-0: mantissa, 24 bits, MSB hidden and always=1.
The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.
I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?
Thanks in advance.