How to use millis() "timer" function in accordance with I2C request?

My goal is to make an sort of "delay" using the millis() function, inside an function which is called when an I2C request is received.

When the I2C request contains "relay" the function handleRelay() is called.

Inside this function the relay has to turn on, wait a few seconds and then turns off.

My problem is that the "timer" inside my function is not working properly.

Comments are welcome...

#include <Wire.h>

// Relay
#define relay 2

unsigned long currentMillis;
unsigned long previousMillis;

void setup()
  Serial.begin(115200);         // start serial for debug
  Wire.begin(9);                // join i2c bus with address 9
  Wire.onReceive(receiveEvent); // register receive event

  // Initialize relay
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

void loop()
  currentMillis = millis();

// ===================== Functions ========================

// Function that executes whenever data is received from the master
void receiveEvent(int howMany)
  char wireData;
  String content = "";
  if (Wire.available())          // now we have at least one character in the Serial input buffer
    delay(20);                   // just wait a little bit for more characters to arrive
    while (0 < Wire.available()) // look for all characters in the input buffer
      wireData =;
    Serial.println(content);     // and print them all together

  //Handle relay
  if (content.indexOf("relay") >= 0)
    //Call the function

// Function that handles the relay
void handleRelay()
  currentMillis = millis();
  const long interval = 2000;                     // interval to turn the relay off

  digitalWrite(relay, LOW);                       // turn the relay on
  previousMillis = currentMillis;

  if (currentMillis - previousMillis >= interval) // wait for a few seconds (interval)
    digitalWrite(relay, HIGH);                    // turn the relay off

Never use delay() or Serial.print() inside an ISR.

Just get in set a Flag then get out.

Once out, when the flag is set, get your RX data, do your stuff, reset your flag.

Read these: