to be able to decode the float correctly on the receiving side, the receiver need to know when to start interperting the receiving data as a float ie I would suggest you to implement a start byte
for example you start byte could describe how many data byte the receiver will be receiving
maybe something like this on your TX side:
union{
float num;
uint8_t bytes[sizeof(float)];
} f_tx;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
int ref = 0;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
mySerial.begin (9600);
}
void loop() {
if (ref > 9) {
ref = 0;
}
else {
ref ++;
}
f_tx.num = ref/10;
// if (mySerial.available()) { (this does not work when I remove the //)
mySerial.write(sizeof(float)); //start byte
for(uint8_t i=0; i<sizeof(float);++i){
mySerial.write(f_tx.bytes[i]);
delay(100);
}
Serial.print("f_tx.num = ");
Serial.println(f_tx.num,DEC);
delay(100);
// }
}
and on you RX side:
union {
float num;
uint8_t bytes[sizeof(float)];
} f_rx;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
uint8_t i, r_float;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
mySerial.begin (9600);
}
void loop() {
byte data;
if (mySerial.available()) {
data = mySerial.read();
if (data == sizeof(float) && r_float == 0) {
f_rx.num = 0.0;
r_float = 1;
i = 0;
}
else if (r_float == 1) {
if (i < sizeof(float)) {
f_rx.bytes[i] = data;
++i;
}
else {
Serial.print("f_rx.num = ");
Serial.println(f_rx.num, DEC);
r_float = 0;
}
}
}
else {
Serial.println(data, DEC);
}
}