Code for counter

Be careful with that. A Mega can only take 3.3 V signals. You are doing some kind of level shifting, aren't you?

Does your logic work on the bench, with a pushbutton in lieu of the sensor? The code should detect the change in the state of a pin (i.e. its going from high to low or the other way around).