Hi guys,
I am currently trying to transport two floats with approx 7 significant figures(to right of decimal) using i2C but am getting the errors. I was able to successfully transfer a string of chars over from an electron to an arduino, but an having issues with a float.
My Slave Electron complies fine but when I go to read my float from the serial on the Arduino Master, I am getting odd results. Any help would be appreciated! Here are samples of my code with the results:
Electron slave:
void setup() {
Serial.begin(9600);
Wire.begin(8); // i2c bus #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(500);
requestEvent();
}
void requestEvent() {
// generate some simulated data
float val_1 = 5566;// (random(200000) - 1000) / 100000.0;
float val_2 = (random(200000) - 1000) / 100000.0;
char* val_3 = NULL;
if ((val_1 + val_2) >= 1) {
val_3 = "EN \0";
} else {
val_3 = "DIS\0";
}
// transmit the simulated data
Wire.write((char*)&val_1); // respond with message of 6 bytes
Wire.write((char*)&val_2);
}
Arduino Master:
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
Serial.println("setup complete.");
}
void loop() {
// variables
int packet_size = sizeof(float) + sizeof(float) + 4;
//Serial.print("packetsz is "); //mtp feedback
//Serial.println(packet_size); // mtp feedback
// send READ request to slave
Wire.requestFrom(8, packet_size); // request 6 bytes from slave device #8
int i = 0;
char msg[32];
float* val_1 = NULL;
float* val_2 = NULL;
char* status_msg = NULL;
// flush data buffers
i = 0;
// collect all data from slave (note: this may fail if master reads faster than slave writes)
while (Wire.available()) { // slave may send less than requested
msg[i] = Wire.read(); // read msg packet byte by byte
//Serial.println(msg[i]); //mtp feedback
i++;
if (i >= packet_size) {
break;
}
}
// typecast the apppropiate sections on the packet
val_1 = (float*)(&msg[0]); // extract first float
val_2 = (float*)(&msg[4]); // extract second float
status_msg = (char*)(&msg[8]); // extract string of text at the end
// perform all printouts
Serial.print(*val_1);
Serial.print(", ");
Serial.println(*val_2,10);
//Serial.print(", ");
//Serial.print(status_msg);
//Serial.print("\n");
delay(500);
}
Arduino Serial Result:
setup complete.
ovf, 0.7470588207
ovf, 0.7470588207
-0.77, 0.7470588207
-0.00, 0.7470588207