Skip to main content
2 of 2
Added C++ language formatting tag.
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126

I2C requires interrupts to work, however enabling interrupts inside an ISR is not recommended. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one.

Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.

As an example, your main loop could be rewritten as:

unsigned long lastReading;
unsigned long lastDisplay;
void loop()
{
  if (millis () - lastReading >= 5)   // 200 Hz
    {
    lastReading = millis ();
    // Update x, y, and z with new values 2.5ms     
    getGyroValues(); 
    cont++;
    }

  if (millis () - lastDisplay >= 1000)  // one second
    {
    lastDisplay = millis ();
    Serial.println(cont);
    Serial.println(z);
    cont=0; 
    }
}

Now you don't need the timer, and you are interrupt-friendly. :)

More information about interrupts: http://www.gammon.com.au/interrupts

Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126