How to hand float over another Arduino?

Hi, I'm a beginner. Now I want an Arduino(Master) to hand float over another Arduino(Slave) using I2C. For some reason, I can't make it. Please tell me any source to archive this.

For your information my Sketches are like this but it's crap :frowning:

(The basic idea is to split float into 4byte and send them all. Then slave get them together.)

AGAIN, you not necessarily need to fix my code. I just want any code to archive this: An Arduino(Master) to hand float over another Arduino(Slave)

Thank you. Much love


β€”β€”MASTERβ€”β€”β€”
volatile float test=0.0;

#include <Wire.h>


volatile uint8_t data[4];



void setup() {
  Serial.begin(115200);

  
  Wire.begin(); 
 }

void loop() {

  Wire.requestFrom(8, 2);
  uint8_t i=0;
  while (Wire.available()){
    data[i++]=Wire.read();
  }
  
  test= (float)( data[0]  | data[1]  | data[2]  | data[3] );
  Serial.println(test);
  
  delay(100);
  
}


β€”β€”SLAVEβ€”β€”β€”
#include <Wire.h>
float test = 900;


void setup() {

  
  Wire.begin(8);
  Serial.begin(115200);
  Wire.onRequest(requestEvent);

}

void loop() {
  

  }


void requestEvent() {
  

byte data[4];
data[0] = byte(test);
data[1] = byte(test >> 8);
data[2] = byte(test >> 16);
data[3] = byte(test >> 24);
Serial.write(data, 4);
}

β€”β€”

This library may be of interest: GitHub - nickgammon/I2C_Anything: Arduino library to simplify reading/writing to I2C

1 Like

Why do you sending 4 bytes, but requesting only two?

1 Like

I spotted the error already. As a beginner you should not be using multiple Arduino in any project. It is almost never a good solution. Only an expert will know when it's a good solution, and it is not very often.

Please explain why you think it is a good idea to use 2 Arduino.

1 Like

Perhaps this is not a real project, but only training. It's very interesting - to make two arduinos communicate with each other

1 Like

This is your next problem (After requesting 4 bytes)

When you're sure the 4 bytes are in the correct order, you can use something like
memcpy(&test, data, 4);

c/c++ provides a union to interpret the same memory area in different ways,
although officially undefined behaviour, this works as well on all Arduino hardware.

2 Likes

memcpy send memcpy

1 Like

Shifting works for integers but not so much for floats.

One way to do it is by making your 'float' look like a byte array. Actually: make a pointer to your float (&temp) look like a pointer to a byte array.

void requestEvent() 
{
  byte *data = (byte *) &temp;  // Point 'byte' pointer at the 'float'.
  Serial.write(data, sizeof temp); // Send the bytes
}

On the requesting side:

  byte *data =  (byte *) &temp;  // Point 'byte' pointer at the 'float' 
  Wire.requestFrom(8, sizeof temp);
  for (int i=0; i< sizeof temp; i++)
  {
    data[i] = Wire.read();
  }
  Serial.println(test);
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.