Dear All.
Below codes are sample code for I2C communication.
Raspberry pi is master and Arduino is slave.
The sample codes are echo cases. If I put # 3, arduino should send me back same number.
However, it always sends me '1'.
I do not know why..
Arudino Code
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600); // start serial for output
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.println(“Ready!”);
}
void loop() {
delay(100);
}
// callback for received data
void receiveData(int byteCount){
while(Wire.available()) {
number = Wire.read();
Serial.print(“data received: “);
Serial.println(number);
}
}
// callback for sending data
void sendData(){
Wire.write(number);
}
Raspberry pi Code(Python)
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 writeNumber(value):
bus.write_byte(address, value)
bus.write_byte_data(address, 0, value)
return -1
def readNumber():
number = bus.read_byte(address)
number = bus.read_byte_data(address, 1)
return number
while True:
var = input(“Enter 1 – 9: “)
if not var:
continue
writeNumber(var)
print “RPI: Hi Arduino, I sent you “, var
sleep one second
time.sleep(1)
number = readNumber()
print “Arduino: Hey RPI, I received a digit “, number
print