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);
}
I2C - wrong order of values received
Jump to
- English Forum
- Explore
- News
- General Discussion
- FAQ
- Documentation
- Documentation
- Sample Code
- Discussion Forum
- Hardware
- ESP-IDF
- ESP-BOX
- ESP-ADF
- ESP-MDF
- ESP-WHO
- ESP-SkaiNet
- ESP32 Arduino
- IDEs for ESP-IDF
- ESP-AT
- ESP IoT Solution
- ESP RainMaker
- Rust
- ESP8266
- Report Bugs
- Showcase
- Chinese Forum 中文社区
- 活动区
- 乐鑫活动专区
- 讨论区
- 全国大学生物联网设计竞赛乐鑫答疑专区
- ESP-IDF 中文讨论版
- 《ESP32-C3 物联网工程开发实战》书籍讨论版
- 中文文档讨论版
- ESP-AT 中文讨论版
- ESP-BOX 中文讨论版
- ESP IoT Solution 中文讨论版
- ESP-ADF 中文讨论版
- ESP Mesh 中文讨论版
- ESP Cloud 中文讨论版
- ESP-WHO 中文讨论版
- ESP-SkaiNet 中文讨论版
- ESP 生产支持讨论版
- 硬件问题讨论
- 项目展示
Who is online
Users browsing this forum: No registered users and 47 guests
- All times are UTC
- Top
- Delete cookies
About Us
Espressif Systems is a fabless semiconductor company providing cutting-edge low power WiFi SoCs and wireless solutions for wireless communications and Internet of Things applications. ESP8266EX and ESP32 are some of our products.