Skip to content

Instantly share code, notes, and snippets.

@Saader
Created June 11, 2019 08:43
Show Gist options
  • Save Saader/560338e663c3a6c20edfa878a24b4f15 to your computer and use it in GitHub Desktop.
Save Saader/560338e663c3a6c20edfa878a24b4f15 to your computer and use it in GitHub Desktop.
sends floating values from an arduino to a rpi via i2c
import struct
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
# This is the address we setup in the Arduino Program
address = 0x04
def get_data():
return bus.read_i2c_block_data(address, 0, 8);
def get_float(data, index):
bytes = data[4*index:(index*4)+4]
return struct.unpack('f', "".join(map(chr, bytes)))[0]
#return
while True:
data = get_data()
print(get_float(data, 0))
print(get_float(data, 1))
print(get_float(data, 2))
print("attend")
time.sleep(3);
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
#define FLOATS_SENT 3
float temperature = 10.5;
float luminosity = 5.0;
float batterie = 49.4;
float data[FLOATS_SENT];
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
data[0] = temperature;
data[1] = luminosity;
data[2] = batterie;
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onRequest(sendData);
}
void loop() {
delay(100);
}
void sendData(){Wire.write((byte*) &data, FLOATS_SENT*sizeof(float));}
@Saader
Copy link
Author

Saader commented Jun 11, 2019

Here are the two code I used to send three floating values from an Arduino to a Raspberry connected by the i2c bus.
For two floating it works very well but when I add the third, that I try to display by the print(get_float(data, 2))

I receive this error message on the terminal of the raspberry

return struct.unpack ('f', "" .join (map (chr, bytes))) [0] struct.error: unpack requires a string argument of length 4

Any ideas please ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment