Edit: Chris Stratton rightfully points out that the question is
about a double
, not a float
:
Most, but not all Arduinos, are AVR-based.
In the following I assume you are talking about AVR doubles, i.e.
floats. If this is not the case, then just replace the array of 4 bytes
by an array of 8 bytes.
Original answer:
A float
is four bytes, so it is somewhat equivalent to an array of
four unsigned chars, i.e. to unsigned char[4]
. You can use this
equivalence with an union
. For example, the following function will
send a float byte by byte:
void ble_write_float(float x)
{
union {
float f;
unsigned char c[4];
} data;
data.f = x;
ble_write(data.c[0]);
ble_write(data.c[1]);
ble_write(data.c[2]);
ble_write(data.c[3]);
}
Notice that this will send the bytes in whatever is the natural order of
the sending processor. If it's an AVR (like most Arduinos), this will be
LSB (least significant byte) first. You have to make sure that this is
what the receiver expects.
Following Ignacio Vazquez-Abrams' suggestion, for sending a random float
you could just send four random bytes. However, it may be wiser to have
an idea of the random distribution you want for your float, and use
things like random()
and map()
to achieve that distribution. Using
four random bytes, you get a very wide distribution (all the possible
floats are equally likely) which includes weird things like denormals,
infinities and NaN (literally meaning “not a number”).