I2C - wrong order of values received

Iznogud
Posts: 1
Joined: Mon Jun 10, 2024 12:19 pm

I2C - wrong order of values received

Postby Iznogud » Mon Jun 10, 2024 12:30 pm

Hi
I have a problem with solving this. I use two ESP32 modules that are communicating with I2C protocol. Master got values from slave module in wrong order. Why is this happening?

This is master code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x08 // I2C address of the slave

void setup() {
Serial.begin(115200);
Wire.begin(); // join i2c bus as master
}

void loop() {
sendCommand(1); // Send command 1
delay(1000);
sendCommand(2); // Send command 2
delay(1000);
sendCommand(3); // Send command 3
delay(1000);
}

void sendCommand(int command) {
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.write(command);
Wire.endTransmission();

delay(50); // small delay to let slave process the command

Wire.requestFrom(SLAVE_ADDRESS, 1); // request 1 byte from slave
if (Wire.available()) {
int response = Wire.read();
Serial.print("Command ");
Serial.print(command);
Serial.print(": Response from slave = ");
Serial.println(response);
}
}




And this is slave code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x08 // I2C address of the slave

void setup() {
Wire.begin(SLAVE_ADDRESS); // join i2c bus as slave with address SLAVE_ADDRESS
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent); // register event
Serial.begin(115200);
}

void loop() {
delay(100);
}

int receivedCommand = 0;

void receiveEvent(int howMany) {
if (Wire.available()) {
receivedCommand = Wire.read(); // receive the command
Serial.print("Received command: ");
Serial.println(receivedCommand);
}
}

void requestEvent() {
int response = 0;
switch (receivedCommand) {
case 1:
response = 42;
break;
case 2:
response = 73;
break;
case 3:
response = 100;
break;
}
Wire.write(response);
Serial.print("Sent response: ");
Serial.println(response);
}

Who is online

Users browsing this forum: No registered users and 47 guests