我读了很多帖子 Rpi 如何通过 Arduino 通过 i2c 接收浮点数据,Rpi 作为主控。
但我需要将浮点值写入 arduino,但我没有找到任何示例。我想使用 python smbus。
任何人有一个例子?
非常感谢!
我读了很多帖子 Rpi 如何通过 Arduino 通过 i2c 接收浮点数据,Rpi 作为主控。
但我需要将浮点值写入 arduino,但我没有找到任何示例。我想使用 python smbus。
任何人有一个例子?
非常感谢!
经过多次测试,我可以在作为从机的 arduino 和作为主机的 Raspberry pi3 之间交换多个数据。
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));
}
}
树莓派代码:
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
我希望能帮助别人!谢谢!