如何通过I2C从Arduino Mega到我的Raspberry获得双人间?

如何通过I2C从Arduino Mega到我的Raspberry获得双人间?,arduino,raspberry-pi,arduino-uno,Arduino,Raspberry Pi,Arduino Uno,我想从我的Arduino Mega给我的Raspberry送一个双人间。是否可以通过I2C实现这一点?这是我的密码: #include <Wire.h> #define SLAVE_ADDRESS 0x04 int dataReceived = 0; void setup() { Serial.begin(9600); Wire.begin(SLAVE_ADDRESS); Wire.onReceive(receiveData); Wire.onRe

我想从我的Arduino Mega给我的Raspberry送一个双人间。是否可以通过I2C实现这一点?这是我的密码:

#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);

}

这是因为您的
dataReceived
answer
被声明为
int
。如果您的意思是即使使用
float
/
double
,也无法使其工作,您可以尝试以下方法,它应该可以工作:

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));

我认为double和float在Arduino Mega(4字节)上的大小相同:

撇开串口问题不谈,因为低端Arduinos(328s)缺乏对浮点的内置硬件支持,浮点是在软件中完成的。内置的Arduino库(实际上也适用于GCC)将
single
double
视为相同的,即
single
。如果您需要更多,也许第三方库就是答案:。

谢谢您,我尝试了一下,但我只得到了121个。我用python编写了上面的代码,用我的raspberrySorry获取值,这真的帮不了您。我不熟悉Python,对于Python中的I2C更是如此。
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));