Arduino and Raspberry Pi (i2c communication)

Hello everyone.I have a Raspberry Pi 3 (I use it as a master) , an Arduno Mega (slave) and I use i2c communication to transfer data to my Arduino.
Also,I have a led.So,using Python3 on my raspberry ,everytime I press '1' (without Enter) I increase the brightness of led (that is connected to Arduino).When I press '0' , I decrease the brightness.That works fine.
So ,what I want to do is to tranfer multiple data at the same time,for instance I want to open a led(as I did) and I also want to send another data to do other stuff on Arduino board.
So,how can I do it? I hope I'm clear.

Arduino Code:

#include <Wire.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd (22,23,24,25,26,27);

const int ledPin = 7; 

void setup()
{
  // Join I2C bus as slave with address 8
  //Serial.begin(9600);
  Wire.begin(0x8);

  // Call receiveEvent when data received                
  Wire.onReceive(receiveEvent);
  
  // Setup pin 13 as output and turn LED off
  pinMode(ledPin, OUTPUT);
  analogWrite(ledPin, 0);
}
 
// Function that executes whenever data is received from master
void receiveEvent(int howMany) 
{
  if (Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    analogWrite(ledPin, c);
  }
}
void loop()
{
}

Raspberry Pi Code:

from smbus import SMBus
import curses

addr = 0x8 # bus address
bus = SMBus(1) # indicates /dev/ic2-1

numb = 1

give_move = curses.initscr()
curses.noecho()
give_move.nodelay(1) # set getch() non-blocking

#print ("Enter 1 for ON or 0 for OFF")
num = 0
while 1:

	push_key = give_move.getch()#input(">>>>   ")

	if push_key == ord("1"):
		if(num <= 250):
			num += 5
			#bus.write_byte(addr, 0x1) # switch it on
			bus.write_byte(addr, num)
	
	elif push_key == ord("0"):
		if(num >= 5):
			num -= 5
			#bus.write_byte(addr, 0x0) # switch it on
			bus.write_byte(addr, num)
	

Thanks a lot.

When you connect the Arduino board with a USB connector to the Raspberry Pi, then you can use Serial communication. There will be no trouble with 3.3V versus 5V. It is easier than using I2C. If you know everything about I2C, then the I2C is twice as hard as Serial communication. If you are new to I2C, then I2C is ten times harder than Serial.

The Arduino Mega has onboard 10k pullup resistors to 5V and the Raspberry Pi is not 5V tolerant. Do you use a I2C level shifter ?

In the receiveEvent(), use the parameter 'howMany' to see how much data you have.
It depends on the data that is transferred. Are they some numbers of a fixed length, or a command in readable ASCII.
You have to combine the bytes in receiveEvent. If you use a 'struct', then you can read the whole struct with a single Wire.readBytes().
The receiveEvent() should be as short as possible, you probably need to process the data in the Arduino loop().

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.