How to read data from Arduino with Raspberry Pi with I2C
I managed to initiate a communication between an Arduino and a Raspberry Pi. The two are connected using two 5k pullup resistors (see this page). The arduino write a byte on the i2c bus for each request. On the Raspberry Pi, hello
is printed every second.
Arduino code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x2A
void setup() {
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
Wire.onRequest(sendData);
}
void loop() {
}
char data[] = "hello";
int index = 0;
// callback for sending data
void sendData() {
Wire.write(data[index]);
++index;
if (index >= 5) {
index = 0;
}
}
Python code on the Raspberry Pi:
#!/usr/bin/python
import smbus
import time
bus = smbus.SMBus(1)
address = 0x2a
while True:
data = ""
for i in range(0, 5):
data += chr(bus.read_byte(address));
print data
time.sleep(1);
On my Raspberry Pi, the i2c bus is 1. Use the command i2c-detect -y 0
or i2c-detect -y 1
to verify if your Raspberry Pi detect your Arduino.