Following is the code for I2C slave
Code: Select all
#include <Wire.h>
int receivedValue = 0;
int responseValue = 0;
void setup() {
Wire.begin(0x08); // join I2C bus with address 0x08
Wire.onReceive(receiveEvent); // register event for receiving data from master
Wire.onRequest(requestEvent); // register event for responding to master requests
Serial.begin(115200);
}
void loop() {
}
// This function is triggered when data is received from the master
void receiveEvent(int howMany) {
if (Wire.available()) {
receivedValue = Wire.read(); // Receive the number sent by the master
responseValue = receivedValue * 2; // Double the value
Serial.print("Received from master: ");
Serial.print(receivedValue);
Serial.print(", Prepared to send: ");
Serial.println(responseValue);
}
}
// This function is triggered when the master requests data
void requestEvent() {
Wire.write(responseValue); // Send the doubled value back to the master
}
Code: Select all
#include <Wire.h>
const int slaveAddress = 0x08; // I2C address of the slave
void setup() {
Wire.begin(); // join I2C bus as master
Serial.begin(115200);
}
void loop() {
// Send numbers 1, 2, 3, 4, 5 in series
for (int valueToSend = 1; valueToSend <= 5; valueToSend++) {
sendAndReceive(valueToSend); // Send and receive for each number
delay(1000); // 1-second delay between transmissions
}
}
void sendAndReceive(int valueToSend) {
// Send the value to the slave
Wire.beginTransmission(slaveAddress);
Wire.write(valueToSend); // Send the number to be doubled
Wire.endTransmission();
delay(5000); // Small delay to ensure the slave processes the request
// Request 1 byte back from the slave
Wire.requestFrom(slaveAddress, 1);
if (Wire.available()) {
int receivedValue = Wire.read(); // Read the response from the slave
Serial.print("Sent: ");
Serial.print(valueToSend);
Serial.print(", Received: ");
Serial.println(receivedValue); // Expecting the doubled value
} else {
Serial.println("No response from slave");
}
}
Code: Select all
Received from master: 1, Prepared to send: 2
Received from master: 2, Prepared to send: 4
Received from master: 3, Prepared to send: 6
Received from master: 4, Prepared to send: 8
Received from master: 5, Prepared to send: 10
Received from master: 1, Prepared to send: 2
Received from master: 2, Prepared to send: 4
Received from master: 3, Prepared to send: 6
Received from master: 4, Prepared to send: 8
Received from master: 5, Prepared to send: 10
Code: Select all
Sent: 1, Received: 10
Sent: 2, Received: 2
Sent: 3, Received: 4
Sent: 4, Received: 6
Sent: 5, Received: 8
Sent: 1, Received: 10
Sent: 2, Received: 2
Sent: 3, Received: 4
Sent: 4, Received: 6
Sent: 5, Received: 8