Why does the Serial.print command kill I2C?

2 x UNO R4 Wifi connected to USB. SCL and SDA connected via 4k7 pull up resisters. If I run this code on the slave then I2C stops. If I comment the Serial.print command in the receiveEvent function, I2C starts again (on the oscope). Why? I reversed the master/slave with the same effect.

// slave
#include <Wire.h>
char c;

void setup() {
  Serial.begin(9600);
  Wire.begin(1); 
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  c = Wire.read();    // read I2C
  Serial.print(c);
}

void loop() {
  Serial.println(c);
  c = 0;
  delay(1000);
}

Here's the master code:

// Arduino master
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  // Start the I2C Bus as Master
  Wire.begin(); 
}
void loop() {
  Wire.beginTransmission(1); 
  Wire.write("a");            
  Wire.endTransmission();    
  delay(80);

  
}

In wire.h, receiveEvent() is an interrupt service routine, and other interrupts are disabled inside of it.

Serial.print( ) requires interrupts to function so it doesn't.

you can set a marker in the receiveEvent() and print in loop only.

// slave
#include <Wire.h>
char c;
volatile bool somethingNewCameIn = false;  // a marker to indicate if we have received new data

void setup() {
  Serial.begin(9600);
  Wire.begin(42);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  c = Wire.read();    // read I2C
  somethingNewCameIn = true;  // set receive marker
}

void loop() {
  if (somethingNewCameIn) {
    Serial.println(c);
    somethingNewCameIn = false; // reset receive marker
  }
  //delay(1000);
}

by the way, don't use a reserved addresses like 1.
Therefore I changed it to 42 (something from 8 to 119)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.