Read I2C data from Arduino slave

Hello @gohai - thanks for your respons and your generous offer to help me debug this issue. :slight_smile:

First of all: I get a positive respons with the hex 0X21 adress running “i2cdetect -y 1” in the PI terminal. My set up works OK. And I can also read and write to and from other I2C devices like MCP23017 from the PI.

My referensers like “ARD2.read(2)” are picked from my code below so please read it not to be confused…

I have made the code very basic do get this going… also tried different “wait” times.
I think it’s something with this “requestEvent()” on the Arduino side and the “ARD2.read(2)” that doesn’t work well together.

Do look at this page with two Arduinos working fine as Master and Slave. https://www.arduino.cc/en/Tutorial/MasterReader
The Arduino code “Wire.requestFrom(8, 6);” in that code are interresting compared tho the processing “ARD2.read(2)”

The ARD2 receives and do “Serial.println(opcode);” with no problem and I can read it on my Serial Monitor from the Arduino.

In the Arduino Code:
I have also tried to remove the “if (opcode == Status) { }” statement and run the code anyway.
And I have also tried to put the “Wire.write(H_DIST);” directly in the receiveEvent() but that was a kind of desperate… :slight_smile:

Processing Code:

import processing.io.*;
I2C ARD2;
//**********************************************************
void setup() {
  //printArray(I2C.list());
  ARD2 = new I2C(I2C.list()[0]);
}
//**********************************************************
void draw() {
  // read DIST over I2C from Arduino2
  // with address 0x21
  ARD2.beginTransmission(0x21);
  // first send a command byte
  ARD2.write(0x41);
  // read in two bytes
  //wait(10);
  byte[] DIST = ARD2.read(2);
  println(DIST);
  //wait(500);
}

//**********************************************************
void wait(int num) {
  int j=0;
  int i=millis();
  while (j<i+num) {j=millis();}  
}

Arduino Code:

#include <Wire.h>

#define I2C_ADDRESS 0x21 // ARD2 address

uint8_t opcode; // command register
uint8_t H_DIST; // High byte
uint8_t L_DIST; // Low byte
uint8_t Status; //send data

void setup() {
Wire.begin(I2C_ADDRESS);
Serial.begin(9600); 
H_DIST=32;
L_DIST=64;
Status=65;

Wire.onRequest(requestEvent);

Wire.onReceive(receiveEvent); 
}

void loop() {
  Serial.println('*');
  delay(100);
}

void receiveEvent(int bytes) {
  // Read the first byte to determine which register is concerned
  opcode = Wire.read();
  Serial.print("received_opcode:");
  Serial.println(opcode);
  // If there are more than 1 byte, then the master is writing to the slave
  //if (bytes > 1) {
  // }
 
}

void requestEvent() {
  // Read from the register variable to know what to send back
  if (opcode == Status) {
  Wire.write(H_DIST);
  Wire.write(L_DIST);
  Serial.println("writes");
  }
}
1 Like