I2C between a Arduino and a Raspberry Pi

hello guys. I am coding on an Arduino and a Raspberry Pi.
I am making a test code for a protocol and made a test program that sends one byte from the Raspberry Pi
to an arduino. but Raspberry fails it after random amount of repeated try.
It works fine like few hundreds or thousands of time to send 1 byte to the Arduino but it fails.
The next problem is that when that happens, Arduino cannot even send correct values to Raspberry Pi
until i reset both of the Raspberry program and the Arduino. Does anybody know anything about this?
I Know this is complecated problem and It is also related about Raspberry but I think here could be a good place to ask this. Thank you for reading this.

I attached both of the source code for the Raspberry and the Arduino.

ArduinoSlave.ino (670 Bytes)

PiMaster.cpp (1.8 KB)

I had the same problem. Mine could be corrected by resetting only the Arduino.

But you know, resetting arduino is not a correct way that i can use in real usecase. I need some way to fix my problem permenantly.

As I recall, I use a delay between sending a command and reading characters.

This is my Arduino slave code

#include <Wire.h>
byte array[8] = {2,4,6,8,10,12,14,16};
volatile byte regReq = 0;
volatile byte* rtnPtr;
 
void setup()
{
  Serial.begin(115200);
  Wire.begin(13);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

void loop()
{

}

void receiveEvent(int byteCount)
{
  regReq = Wire.read();
}

void requestEvent()
{
  rtnPtr = &array[regReq*2];    
  Wire.write((byte*)rtnPtr,2);
  rtnPtr += 2;
}

My RPi C code.

#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// #include <math.h>

int fd;
char buf[32];
unsigned char  readReg = 0;

int main(int argc, char **argv)
{
    const char *i2cDevice = "/dev/i2c-1";
    const int i2cAddress = 13;
    unsigned char i;
    unsigned char readCount;

    if ((fd = open(i2cDevice, O_RDWR)) < 0) {
        printf("Failed to open i2c port\n");
        exit(1);
    }

    if (ioctl(fd, I2C_SLAVE, i2cAddress) < 0) {
        printf("Unable to configure i2c address\n");
        exit(1);
    }

	while(1)
	{
		usleep(500000);

		if(readReg == 0) readReg = 1;
		else readReg = 0;

		if(write(fd,&readReg,1) == 1)
		{
			usleep(20);

			printf("%d  ",readReg);
			int testRtn = read(fd,buf,2);
			buf[2] = 0;

			if(buf[0] != '*') printf("%d %d %d\r\n",testRtn,buf[0],buf[1]);
			else printf("**READ BLOCKED**\r\n");
		}
	}
}