Is there a way to make one, a lower precision float type of variable using only 2 bytes rather than the usual 4? It would be useful for doing float mathematics on an ATTiny where one has less variable memory space to work with, and would mean that when using union to split this sort of variable in to bytes for sending over I2C/SPI/... you'd be able to send shorter messages. For an array of floats, when you don't need 4 bytes worth of precision, this means you can halve the memory requirements and/or the length of messages to be sent/received.
Side note. You cannot send things like a double or a float over I2C. You would need to shift bits and send them 8 at the time using the write function. This does not work with non-integers AFAIK. You can solve this using a union iirc.
why ? you just push bytes, it's up to the receiver to know what the bytes mean
something like this would probably work
#include <Wire.h>
void sendMyData() {
float dataToSend = 3.141592; // Example float data to send
byte* bytes = reinterpret_cast<byte*>(&dataToSend);
for (size_t i = 0; i < sizeof(float); i++) Wire.write(bytes[i]);
}
void setup() {
Wire.begin(0x08); // we are an I2C client with address 8
Wire.onRequest(sendMyData); // callbakc when a request is received
}
void loop() {}
you could also do
void sendMyData() {
float dataToSend = 3.141592; // Example float data to send
byte* bytes = reinterpret_cast<byte*>(&dataToSend);
Wire.write(bytes, sizeof(float));
}
I said that because the last time I tried to bit shift a float, I got a compile error.. I figured that a union would solve that, which it does not. I am not familiar with reinterpret_cast.
This was al 10 years ago and I have never used a float or double since (no need)
To transfer a floating point number (say: 17.35) over the I2C Bus, one can use the Wire.print() function; at the receiver side, ASCII coded bytes are to be collected and then the atof() function be applied to retrieve the original float number.
With that approach, you suffer loss of precision, rounding, etc with both the print() and atof() operations. It's almost guaranteed that the 4 bytes that make up the float on the receive end will be different than the original 4 bytes on the transmit end.