0

I would like to send a double from my Arduino Mega to my Raspberry. Is it possible to do this via I2C? Here is my code:

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int dataReceived = 0;

void setup() {
    Serial.begin(9600);
    Wire.begin(SLAVE_ADDRESS);
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

}

void loop() {
    delay(100);
}

void receiveData(int byteCount){
    while(Wire.available()) {
        dataReceived = Wire.read();
        Serial.print("Donnee recue : ");
        Serial.println(dataReceived);
    }
}

void sendData(){
    int answer = dataReceived + 100;
    Wire.write(answer);

}

The problem in my code is I can't write float answer instead of int answer. Any suggestions?

Thank you very much!

Edit :

Here is my code in Python to get the value of a double :

import smbus import time  
bus = smbus.SMBus(0) 
address = 0x04  
print "double" 
bus.write_byte(address, 6)

time.sleep(1) 
answer = bus.read_byte(address) 
print answer

2 Answers2

0

It's because your dataReceived and answer are declared as int. If you mean that you can't get it to work even with float/double, you can try this, it should work:

double sending_data = 123.456;
uint8_t Write_Buffer[sizeof(sending_data)];

memcpy(&Write_Buffer[0], &sending_data, sizeof(sending_data));

Wire.write(&Wbuffer[0], sizeof(sending_data));

I think double and float are the same size on Arduino Mega (4 bytes) from here: https://www.arduino.cc/en/Reference/Double

dda
  • 6,030
  • 2
  • 25
  • 34
Eugene L
  • 121
  • 7
0

Serial port issues aside, because the lower-end Arduinos (328s) lack built-in hardware support for floating point, the floating point is done in software. The built-in Arduino libraries (and indeed also for GCC) treat single and double the same, namely as single. If you need more perhaps a third-party library is the answer: BigNumber.

TomServo
  • 7,248
  • 5
  • 30
  • 47