Go Down

Topic: TWI/I2C - Arduino to Arduino, sending float (Read 7 times) previous topic - next topic

WanaGo

Sep 19, 2010, 03:18 am Last Edit: Sep 19, 2010, 03:20 am by WanaGo Reason: 1
Hi

I am just trying to send a float from 1 arduino to another over TWI/I2C and I have data coming over, but it doesnt look correct and need some help please.

I am getting the Master to request data from the Slave.

Code below are snippets just to show what im trying to do.

The slave has this code, which I stole from another post:
Code: [Select]
byte* RPMFloatPtr;

void setup()
{
Address = 2;
Wire.begin(Address);
Wire.onRequest(requestEvent); // register event
}

void requestEvent()
{
 RPMFloatPtr = (byte*) &lastRPM;
 Wire.send(RPMFloatPtr, 8); // respond with message of 4 bytes as expected by master
}


The Master does this:

Code: [Select]
void setup()
{
Wire.begin();
}

void loop()
{
Wire.requestFrom(2, 4);
float data;
while(Wire.available())    // slave may send less than requested
{
 data = Wire.receive(); // receive a byte as character  
}
Serial.print(data);
}


So the master is requesting 8 bytes of data from the slave, the slave is replying with 8 bytes in a byte array (float made into a byte array), and then the master is printing the incomming data as a float.

Im sure I have made a rookie mistake though.
Can someone assist?

The Slave has a float called 'lastRPM' which could be 0.00 up to 20000.00, and I just want the master to print that to the serial port.

Can someone help please

Regards
James

WanaGo

I found another post with this code in it (different variable names in some cases) - but this seems to work...

I made data an array of bytes first:

Code: [Select]
while(Wire.available())    // slave may send less than requested
   {
     data[i] = Wire.receive(); // receive a byte as character
     Serial.print("B: ");
     Serial.println(data[i]);
     i = i + 1;
   }


Then I used the code I found:

Code: [Select]
float RPM;

   union u_tag {
     byte b[4];
     float fval;
   } u;
   
   u.b[0] = data[0];
   u.b[1] = data[1];
   u.b[2] = data[2];
   u.b[3] = data[3];
   
   RPM = u.fval;


no idea what a union is yet or how/why this works though.

deSilva

A union is an "overlay" of variables, sharing the same memory cells.
In this case it is used as a re-interpret-cast.
It will only work if transmitting and sending devices have the same floating point model...

Senso

Why do you need floating point to represent rpms?

WanaGo

Due to the application demanding it.

You can still have half a revolution etc...

20000 RPM wont warrant it, but when using it for precise measurements like an encoder input (1000 pulses per rev), knowing parts of a revolution is required.

Go Up