I2C Raspi Master Arduino Slave analog Values transmission for csv file

Hi everybody,

i got 4 sensors connected to my Arduino Mega (Slave) and i want to transmit their values over I2C.

My current Arduino code looks like this:

#include <Wire.h>

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


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);
  int reading4 = analogRead(analogPin4);

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

}

The Code on my Raspberry looks like this:

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

def requestreading():
block = bus.read_i2c_block_data((SLAVE_ADDRESS), 0, 4)
print(block)

while True:
var = input("Press any key for reading: ")
requestreading()

First Problem is that i only get values from 0 - 255 and not the whole range to 1023. Is this because of the script on my Arduino and the fact that the analogreadings have been defined as int?

For the Master script:
i would like to be able to start and stop the transmission via the press of a button and the log the values into a csv file. I would very much appreciate if anybody had suggestions.

Thanks

Is the Wire.write reference any help ?

Unfortunately not. If i try to redefine the analog readings as datatypes u_int16 it still only gives me an 8 bit value.

First Problem is that i only get values from 0 - 255 and not the whole range to 1023. Is this because of the script on my Arduino and the fact that the analogreadings have been defined as int?

I2C can only transfer bytes. So if you have a 10bit value (or an int16_t) you have to split it into two bytes, transfer the two bytes and join them again on the receiving side.

The Arduino side might be quite easy:

Wire.write((char *) &reading1, 2);

will send one value as 2 bytes. Keep in mind that you have read 8 bytes on the Raspi if you send all 4 integer values on the Arduino.

Prj2017:
Unfortunately not.

write()

Description

Writes data from a slave device in response to a request from a master, or queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission()).
Syntax

Wire.write(value)
Wire.write(string)
Wire.write(data, length)

Parameters

value: a value to send as a single byte