Dear Community
I am trying to set up a master-slave based communication between two microcontrollers using I2C. The setup includes:
-
nRF52840 microcontroller (master)
-
Adruino M0 (slave)
In the end, I want to achieve the following behaviour:
The master sends a command (a payload of a few bytes) to the master, which then proccesses the command and computes some stuff based on the received information. When it is done, it sends a response back to the master. In both directions, the length of the payload is of variable length. Also, processing the command will take some time, so from the master's side the waiting for the response must be non-blocking.
For a first implementation, I want to implement a demo app in which both microcontrollers are connected to a serial monitor and forward the messages from the serial buffer to the I2C interface.
Code for master (code for response not included yet):
#include <Wire.h>
void setup() {
Serial.begin(115200);
while (!Serial) {} // wait for Serial Monitor to open
Serial.println("Hello world!");
Wire.begin();
Wire.setClock(100000);
Serial.println("I2C ok!");
}
void loop() {
if (Serial.available()) {
byte txData[20];
size_t bytesRead = Serial.readBytes(txData, 20);
Serial.println("Starting I2C transmission...");
Wire.beginTransmission(0x42);
Wire.write(txData, 20);
Wire.endTransmission();
Serial.println("I2C transmission finished!");
}
delay(50);
}
Code for slave (can only receive information, sending not implemented yet):
#include <Wire.h>
void setup() {
SerialUSB.begin(115200);
while (!SerialUSB) {}
SerialUSB.println("Hello world!");
Wire.begin(0x42);
Wire.setClock(100000);
Wire.onReceive(receiveEvent);
SerialUSB.println("I2C ok!");
}
void receiveEvent(int nBytes){
SerialUSB.println("i2C callback");
while(Wire.available()){
char c = Wire.read();
SerialUSB.print(c);
}
}
void loop() {
delay(50);
}
With this code, I am unable to receive any messages via the I2C bus. The callback receiverEvent() is never invoked. If I put the code of receiveEvent() inside the main loop, the same situation occurs, i.e. no data is ever received.
Problem 1:
The start-up of the master is very slow for some reason. It takes a couple of seconds until I see the welcome messages on my serial monitor. The slave always starts up immediately. Any idea why?
Problem 2:
How to correctly receive bytes with the Write library? Using Wire.read() never seems to return anything (no matter if called inside or outside the callback).

