![](/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.