hello,
just start using I2C and want connect arduino UNO and Raspberry Pi 3. Found tutorial how to do this:
works fine and I get data from RPI to UNO. I use two UNO as slave and RPI as master. Now I want use one uno to get data and other to send data to RPI. How can I change code to do this?
UNO1
/*
I2C Pinouts
SDA -> A4
SCL -> A5
*/
//Import the library required
#include <Wire.h>
//Slave Address for the Communication
#define SLAVE_ADDRESS 0x04
char number[50];
int state = 0;
int x = 3;
//Code Initialization
void setup() {
// initialize i2c as slave
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(sendData);
// Wire.onRequest(sendData);
}
void loop() {
delay(100);
} // end loop
// callback for received data
void receiveData(int byteCount) {
int i = 0;
while (Wire.available()) {
number[i] = Wire.read();
i++;
}
number[i] = '\0';
Serial.print(number);
} // end while
// callback for sending data
void sendData() {
Wire.write(number);
Wire.write(x);
}
//End of the program
UNO2
/*
I2C Pinouts
SDA -> A4
SCL -> A5
*/
//Import the library required
#include <Wire.h>
//Slave Address for the Communication
#define SLAVE_ADDRESS 0x05
char number[50];
int state = 0;
//Code Initialization
void setup() {
// initialize i2c as slave
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
// Wire.onRequest(sendData);
}
void loop() {
delay(100);
} // end loop
// callback for received data
void receiveData(int byteCount){
int i = 0;
while(Wire.available()) {
number[i] = Wire.read();
i++;
}
number[i] = '\0';
Serial.print(number);
} // end while
// callback for sending data
void sendData(){
Wire.write(number);
}
//End of the program
RPI
#RPi Pinouts
#I2C Pins
#GPIO2 -> SDA
#GPIO3 -> SCL
#Import the Library Requreid
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
#Slave Address 1
address = 0x04
#Slave Address 2
address_2 = 0x05
def writeNumber(value):
bus.write_byte(address, value)
bus.write_byte(address_2, 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:
#Receives the data from the User
data = raw_input("Enter the data to be sent : ")
data_list = list(data)
for i in data_list:
#Sends to the Slaves
writeNumber(int(ord(i)))
time.sleep(.1)
writeNumber(int(0x0A))
#End of the Script