Last active
November 27, 2023 21:54
-
-
Save gileri/5a9285d6a1cfde142260 to your computer and use it in GitHub Desktop.
Sending float from arduino to raspberry pi using Wire (arduino) and smbus (python) libraries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://bradsrpi.blogspot.fr/2013/03/sending-data-from-arduino-to-raspberry.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Wire.h> | |
#define SLAVE_ADDRESS 0x04 | |
#define FLOATS_SENT 2 | |
float temperature = 10.5; | |
float luminosity = 5.2; | |
float data[FLOATS_SENT]; | |
void setup() { | |
pinMode(13, OUTPUT); | |
Serial.begin(9600); | |
data[0] = temperature; | |
data[1] = luminosity; | |
// 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*) &temperature, FLOATS_SENT*sizeof(float)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import struct | |
import smbus | |
# 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+1)*4] | |
return struct.unpack('f', "".join(map(chr, bytes)))[0] | |
while True: | |
try: | |
data = get_data() | |
print(get_float(data, 0)) | |
print(get_float(data, 1)) | |
except Exception as e: | |
print(e) | |
continue | |
finally: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, thanks for the interest in the script !
I cleaned up the script and implemented the read size based on @wicusverhoef's suggestion. However I can't test it right now, I count on you lads :)