Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spark Core Float to Byte Test
float a = 6.7;
float b = 14.6;
float c = 26.3;
byte* method1(float num)
{
byte buff[sizeof(float)];
memcpy(buff, &num, sizeof(float));
return buff;
}
byte* method2(float num)
{
union float2bytes { float f; unsigned char b[sizeof(float)]; };
float2bytes f2b;
f2b.f = num;
return f2b.b;
}
void setup() {
Serial.begin(57600);
while(!Serial.available()) SPARK_WLAN_Loop();
}
void loop() {
Serial.println("Start --------------");
Serial.println();
Serial.println("Method 1");
Serial.print("a = ");
Serial.write(method1(a), 4);
Serial.println();
Serial.print("b = ");
Serial.write(method1(b), 4);
Serial.println();
Serial.print("c = ");
Serial.write(method1(c), 4);
Serial.println();
Serial.println();
Serial.println("Method 2");
Serial.print("a = ");
Serial.write(method2(a), 4);
Serial.println();
Serial.print("b = ");
Serial.write(method2(b), 4);
Serial.println();
Serial.print("c = ");
Serial.write(method2(c), 4);
Serial.println();
Serial.println();
Serial.println("End ----------------");
// Endless loop (but keep wifi alive)
while(1) SPARK_WLAN_Loop();
}
/* Arduino UNO Sketch */
float a = 6.7;
float b = 14.6;
float c = 26.3;
byte* method1(float num)
{
byte buff[sizeof(float)];
memcpy(buff, &num, sizeof(float));
return buff;
}
byte* method2(float num)
{
union float2bytes { float f; unsigned char b[sizeof(float)]; };
float2bytes f2b;
f2b.f = num;
return f2b.b;
}
void setup() {
Serial.begin(57600);
while(!Serial.available());
}
void loop() {
Serial.println("Start --------------");
Serial.println();
Serial.println("Method 1");
Serial.print("a = ");
Serial.write(method1(a), 4);
Serial.println();
Serial.print("b = ");
Serial.write(method1(b), 4);
Serial.println();
Serial.print("c = ");
Serial.write(method1(c), 4);
Serial.println();
Serial.println();
Serial.println("Method 2");
Serial.print("a = ");
Serial.write(method2(a), 4);
Serial.println();
Serial.print("b = ");
Serial.write(method2(b), 4);
Serial.println();
Serial.print("c = ");
Serial.write(method2(c), 4);
Serial.println();
Serial.println();
Serial.println("End ----------------");
// Endless loop
while(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment