![](/img/trans.png)
[英]How to read a float value in C on Raspberry Pi 3B from Arduino slave (via I2C)?
[英]How can I receive a double from an Arduino Mega to my Raspberry via I2C?
我想从我的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);
}
我的代码中的问题是我不能写浮点答案而不是int答案。 有什么建议么?
非常感谢你!
编辑:
这是我在Python中获得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
这是因为您的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));
我认为从这里开始,Arduino Mega上的double和float大小相同(4字节): https : //www.arduino.cc/en/Reference/Double
除了串行端口问题外,由于低端Arduino(328s)缺乏对浮点的内置硬件支持,因此浮点由软件完成。 内置的Arduino库(甚至对于GCC也是如此)将single
和double
视为相同,即single
。 如果需要更多,也许答案是第三方库: BigNumber 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.