Reading Multiple Sensors from the same slave via I2C Connection

Hi there,

i’m trying to read the analog inputs A0, A1, A2 of my Arduino mega (as slave) via an raspberry pi (master) via an I2C bus.
My questions is whether it’s possible to read more than 1 value from 1 slave or whether the other analog inputs need to be defined seperately in order to get a reading from them. Right now it returns the value of the A0 Channel 3 times instead of the readings from A0, A1, A2.

#include <Wire.h>

int SLAVE_ADDRESS = 0x08;
int analogPin1 = A0;
int analogPin2 = A1;
int analogPin3 = A2;


void setup(){
  Wire.begin(SLAVE_ADDRESS);
  Wire.onRequest(sendAnalogReading);
}

void loop(){
  
}

void sendAnalogReading(){
  int reading1 = analogRead(analogPin1);
  int reading2 = analogRead(analogPin2);
  int reading3 = analogRead(analogPin3);

  Wire.write(reading1);
  Wire.write(reading2);
  Wire.write(reading3);

}

Code Raspberry:

import smbus
import time

bus = smbus.SMBus(1)
SLAVE_ADDRESS = 0x08

def request_reading():
    reading1 = int(bus.read_byte(SLAVE_ADDRESS))
    print(reading1)
    reading2 = int(bus.read_byte(SLAVE_ADDRESS))
    print(reading2)
    reading3 = int(bus.read_byte(SLAVE_ADDRESS))
    print(reading3)

while True:
    command = input("Enter command: r - read A0, A1, A2 ")
    if command == 'r' :
        request_reading()

This line of Raspberry code:

reading1 = int(bus.read_byte(SLAVE_ADDRESS))

Reads one byte from the I2C bus, so on the Arduino it calls sendAnalogReading() which transfers the lower byte of the reading of the analog value of A0. The rest of the values are ignored because the master requested exactly one byte. Two lines later in the Raspberry code the same happens again. The master (Raspberry) requests one byte from the Arduino, that calls sendAnalogReading() and sends again the lower byte of the analog value of A0.

So you have to change your Raspberry code to either read all values in one call or define an I2C protocol where you can address the value you want to read.
And you have to change your Arduino code to transfer two bytes instead of only one (Wire.write() send one byte!) for the analog reading.