I am working on a project which involved i2c communication between an Arduino Uno and a Raspberry Pi. I'm trying to send data to the Arduino from the Pi and back.
Here is my code for the Arduino:
#include <Wire.h>
#include <Arduino.h>
#define SLAVE_ADDRESS 0x12
int flag_int_to_send_to_PI = 0;
int flag_int_received_from_PI = 0;
char data_to_send_PI[] = "hello PI";
String data_recieved_from_pi = "";
void setup() {
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.begin(9600);
flag_int_to_send_to_PI = 1;
}
void loop() {}
void receiveData(int byteCount) {
while(Wire.available()) {
flag_int_received_from_PI = Wire.read();
if(flag_int_received_from_PI == 1) {
Serial.println("PI Wants data[].");
flag_int_to_send_to_PI = 3;
}
if(flag_int_received_from_PI == 3) {
Serial.println("PI Wants To say its ok.");
//reading a string from pi: Here (How ?)
while( Wire.available()) {
data_recieved_from_pi += (char)Wire.read();
}
Serial.print("Data Received From PI:");
Serial.println(data_recieved_from_pi);
data_recieved_from_pi = "";
}
}
}
void sendData() {
if(flag_int_to_send_to_PI == 1) {
Serial.println("Conversation begin : sending 1 to PI");
Wire.write(flag_int_to_send_to_PI);
}
if(flag_int_to_send_to_PI == 3) {
Wire.write(data_to_send_PI);
}
flag_int_to_send_to_PI = 0;
}
and here is the Raspberry Pi Code:
#!/usr/bin/python
from smbus import SMBus
import time
bus = SMBus(1)
slaveAddress = 0x12
data_received_from_Arduino = ""
data_to_send_to_Arduino = "Hello Uno"
def StringToBytes(val):
retVal = []
for c in val:
retVal.append(ord(c))
return retVal
while(1):
try:
x = bus.read_byte(slaveAddress)
if (x == 1):
print(x)
bus.write_byte(slaveAddress,1)
time.sleep(0.2)
data_received_from_Arduino = bus.read_i2c_block_data(slaveAddress, 0,12)
print(data_received_from_Arduino)
bus.write_byte(slaveAddress,3)
print(StringToBytes(data_to_send_to_Arduino))
bus.write_i2c_block_data(slaveAddress, 0x00,StringToBytes(data_to_send_to_Arduino))
Here is the serial and console output:
Arduino serial output:
Conversation begin : sending 1 to PI
PI Wants data[].
PI Wants To say its ok.
Data Received From PI:
Raspberry Pi console:
1
[0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
[72, 101, 108, 108, 111, 32, 85, 110, 111]
How does it work?
- The Arduino sends a 1 to the Pi to initiate a two communication.
- The Pi sends back 1 to acknowledge.
- The Arduino then sends the data string to the Pi.
- The Pi receives the data and sends back 3 to the Arduino to say it went OK. (but it does not go ok).
The Pi then sends the data string to the Arduino, which I'm unable to read on the Arduino side, even though I tried.
My Questions
- Why is the Raspberry Pi receiving 255 every where in the buffer?
- How can the Arduino get the byte array sent from the Pi?