I tried to connect an Arduino Uno with my Raspberry using the i2c bus, with code and wiring suggested here. This example is sending only one byte from RPi to Arduino and back, and everything works fine.
Now, since I need to send a larger number (which is a value from the ultrasonic sensor on Arduino) to RPi, I edited the code, but I just receive zeros. I was reading on the documentation of the Wire.h
library (Arduino side) and the smbus
python module (RPi side) but I haven't spotted anything helpful.
What I try to do is to send 4 bytes one by one and then read them using struct.unpack
This is the code on Arduino
/*
i2c
pin A4 SDA (raspi pin3)
pin A5 SCL (raspi pin5)
*/
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
void setup() {
Serial.begin (9600); // start serial for output
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
Wire.onRequest(requestEvent); // register event
Serial.println("Ready!");
}
void loop() {
delay(500);
}
void requestEvent()
{
long d;
d=10; // mockup value, in the real script is acquired by the sensor
Serial.println(d);
Wire.write((const uint8_t*)&d, sizeof(long));
}
And this is the script on RPi
import smbus
import time
import struct
# 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 readLong():
#number = bus.read_byte(address)
number=""
for i in xrange(4):
number += chr(bus.read_byte(address))
return struct.unpack('l', number)
while True:
time.sleep(1)
number = readLong()
print "[Arduino]", number, "mm"