我读了很多文章,了解Rpi如何通过i2c通过Arduino接收浮点数据,Rpi作为主数据。
但我需要为arduino写浮动值,我没有找到任何例子。我想使用python smbus。
有人举个例子吗?
非常感谢!
答案 0 :(得分:0)
经过多次测试,我可以在arduino作为slave和Raspberry pi3之间交换多个数据作为master。
Arduino代码:
#include <Wire.h>
byte data[12];
int command;
typedef struct processData{
float temp1;
float temp2;
float temp3;
float temp4;
float vazao_quente;
float vazao_fria;
byte pump_speed;
//bool pump_status;
byte bstatus;
//bool heater_status;
byte chksum;
};
typedef union I2C_Send{
processData data;
byte I2C_packet[sizeof(processData)];
};
I2C_Send send_info;
void parseValues(byte data[]){
union float_tag{
byte b[4];
float fval;
}ft;
ft.b[0] =data[1];
ft.b[1] = data[2];
ft.b[2] = data[3];
ft.b[3] = data[4];
Serial.println(ft.fval);
}
void setup()
{
Wire.begin(12); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent);
Serial.begin(9600); // start serial for output
setrnddata();
}
void loop()
{
delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
command = Wire.read();
if (command==1){
int i=0;
while(1 <= Wire.available()) // loop through all but the last
{
data[i] = Wire.read(); // receive byte as a character
i = i+1;
}
parseValues(data);
}
}
void requestEvent()
{
if(command==2){
Wire.write(send_info.I2C_packet,sizeof(processData));
}
}
Raspberry代码:
from datetime import datetime
from datetime import timedelta
from smbus import SMBus
import struct
start_time = datetime.now()
def millis():
dt = datetime.now()-start_time
ms = (dt.days*24*60*60 + dt.seconds)*1000+dt.microseconds / 1000.0
return ms
#inicia escravo i2c
bus = SMBus(1)
arduinoAddress = 12
#interval request
interval = 150
temperatura = 10.2
vazao = 5.3
command = 20
teste = 30
if __name__ == '__main__':
prevmillis = millis()
while True:
currentmillis = millis()
if(currentmillis - prevmillis > interval):
#write
bytescommand = struct.pack('=2fbb',temperatura,vazao,command,teste)
bus.write_block_data(arduinoAddress,1,list(bytescommand))
print(list(bytescommand))
#request
block = bus.read_i2c_block_data(arduinoAddress,2,27)
output = struct.unpack('6f3b',bytes(block))
print(output)
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
prevmillis = currentmillis
我希望能帮助别人! 谢谢!