Send float over i2c

hello,

i need to send a float value over i2c, from one Arduino to another.
i understand i need to convert it, because onle byte or string can be sent.

so i converted it to string, but a get an error when sending, that says
" no matching function for call to 'TwoWire::write(String&)' "

the code looks like this (reading a temperature from a Dht22 on one arduino, sending it to another for display on a screen):

float t = dht.readTemperature()-1.5; // reading the temp from sensor
String temp = String(t,1); // conversing to string
Serial.println(temp); //check if conversion is ok
Wire.beginTransmission(8);
Wire.write(temp); // my error is here.
Wire.endTransmission();

any sugestions? should i convert to something else ? and how?
ps: i will see about receving on the oder side after this works :))

thanks in advance
justsilviu

A float is represented as four bytes.

float x = 3.141;
byte* px = (byte*)&x;

No conversion, no loss of precision.

ok,

so what does this mean.

cand i send it without converting? as a parameter to the wire.write function?

if i use

float t = dht.readTemperature()-1.5; // reading the temp from sensor
//  String temp = String(t,1); // conversing to string
//  Serial.println(temp); //check if conversion is ok
  byte* px = (byte*)&t;
  Serial.println(*px); //i get returns as 51, 102, or sometimes 0
  
  Wire.beginTransmission(8); 
 Wire.write(*px);  // my error is here.
 Wire.endTransmission();

i get random results which i cannot understand.

thanks.

 Wire.write(*px);  // my error is here.

A float value consists of four bytes, but you're only trying to send one.

1 Like
float t = dht.readTemperature()-1.5; // reading the temp from sensor

  String temp = String(t,1); // converting to string
  Serial.println(temp); //check if conversion is ok

 Wire.beginTransmission(8); 
 Wire.write(temp[4]); 
 Wire.endTransmission();

it works now.
Wire.write(temp[4]); this is the right sintax, it sends the right value.

now to see if i cand read it :slight_smile:

thanks for the help.

justsilviu:
it works now.

I'm not sure what your definition of "work" is here.

Wire.write(temp[4]); this is the right sintax, it sends the right value.

now to see if i cand read it :slight_smile:

thanks for the help.

You've ignored everthing I've written, so I don't know why I'm being thanked.