swim lap counter

I found an alternative for counting laps in the pool.
As you turn your heading changes by roughly 180 degrees, so if you swim back and forth or swim square rounds a change of heading of 20 degrees should indicate a lap change and up a counter by one. I found a breakout board with a HMC 5883 l magnetometer works perfectly well with this sketch:

// I2C device class (I2Cdev) demonstration Arduino sketch for HMC5883L class
// 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
//===============================================
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#include "Wire.h"

// I2Cdev and HMC5883L must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "HMC5883L.h"

// class default I2C address is 0x1E
// specific I2C addresses may be passed as a parameter here
// this device only supports one I2C address (0x1E)
HMC5883L mag;

int16_t mx, my, mz;

float oldheading;
float heading;
//unsigned long Time = millis();
int i;

void setup() {
   pinMode(buttonPin, INPUT);
    buttonState = digitalRead(buttonPin);
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();

    // initialize serial communication    
    // which speed is really up to you depending on your project)
    Serial.begin(9600);

    // initialize device
   // Serial.println("Initializing I2C devices...");
    mag.initialize();

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(mag.testConnection() ? "HMC5883L connection successful" : "HMC5883L connection failed");
    mag.getHeading(&mx, &my, &mz);
     float oldheading = atan2(my, mx);
     if(oldheading < 0)
     oldheading += 2 * M_PI;
}

void loop() {
    unsigned long Time = millis();
    // read raw heading measurements from device
    mag.getHeading(&mx, &my, &mz);
// To calculate heading in degrees. 0 degree indicates North
    float heading = atan2(my, mx);
    if(heading < 0)
      heading += 2 * M_PI;
    float difference = ((heading - oldheading)* 180/M_PI);  
     if (difference < 0)
     difference = ((oldheading - heading)* 180/M_PI);
     if (difference > 20)
     i++;
     Serial.print("Lap " );
     Serial.println(i);
     oldheading = heading;
     Serial.print("Time = " );
     Serial.print(Time/ 1000); 
     Serial. println ( " seconds");
     Serial. println ();
     delay(1000);   
}

As this is a work in progress, a starting reed relay and a display have yet to be added.
Hope that this helps someone with a similar problem, any inprovements and/or elaborations will be greatly appreciated!

moderator: added code tags