Magneto Sensor and interupt

My project works, but as a learning exercise I would like to do it "right"

I have an HMC5883L connected to an arduino nano via I2C. The sensor is attached to a gas-meter. It generates a full sinus-wave once every 0.002 m3 of gas.

In my main code I am reading the sensor, compare it to a high thresholt for the "top" and compare it to a low-thresholt for the "bottom" of the wave. Based on this I am outputing a "pulse" to have a resolution of 0.001m3.

These pulses should go to a S0PCM and that is attached to "Domoticz" to monitor gas usage and statistics.

Instead of a seperate S0PCM, I am using a timer interupt to output the S0PCM code directly over a serial line every 5 seconds.

This works, but using Serial.print within the interupt handler is not recommended. Nice would be to have the main loop "wait" 5 seconds, then output the serial data and have the sensor generate an interrupt on the up and down going wave.

Since my sensor is over the I2C bus, how would I implement this, if at all possible??

Nice would be to have the main loop "wait" 5 seconds, then output the serial data and have the sensor generate an interrupt on the up and down going wave.

No, that would not be nice. Nice would be to have the "main loop" be busy doing whatever needs doing, and to periodically, output the serial data. The blink without delay example will show you how to do that (or Robin2's thread linked in one of the stickies at the top of this forum).

Since my sensor is over the I2C bus, how would I implement this, if at all possible??

Change lines 38 to 72.

I understand the time-comparison, but wouldn't that be less precise?? I mean, at the moment I have the timer interrupt every 5000ms regardless where I am in my main loop. If I compare millis myself it could happen that at 4999ms I compare and loop again and the next time I compare I am already at e.g. 5020ms due to reading from the I2C bus and doing simple math.

So in my interrupt handler I should set a flag to update the pulses and let the main loop handle the sending of data over serial?? sending the data is not critical as long as the pulses per time-unit are correct. I have a similar project reading a TRTC5000 which I probably could enhance with a schmitt-trigger instead of doing it in software (for energy-readings kWh)