RPM counter (Tachometer) with HALL sensor

Hi everyone

I' am currently making a project involving a Hallstate sensor to messure the RPM of a 4-stroke engine.
I think I am almost ther exept for one part. when I open the serial monitor I the RPM is quite accurate but how longer the program is running the worse the accuracy of the program. I think I have to use an Intterupt function but I dont know how and where. Can anyone help ith this?

Thanks a Lot.

unsigned long time;
const int  buttonPin = 2; 
const int ledPin = 13; 
float RPM=0;
float SEC;
float MIN;

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
 // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
void loop() {

  buttonState = digitalRead(buttonPin);     // read the pushbutton input pin:
  if (buttonState != lastButtonState)       // compare the buttonState to its previous state 
 {if (buttonState == HIGH)                  // if the state has changed, increment the counter
 {buttonPushCounter++; }}                     // if the current state is HIGH then the button went from off to on:
  lastButtonState = buttonState;          // save the current state as the last state, for next time through the loop
  time = millis();
  SEC = (time/1000);
  MIN = (SEC/60);
  RPM = (buttonPushCounter/MIN);

Your code is calculating the average RPM over the entire duration that the program has been running.

two things you need.

1 is to see each sensor reading. using delay() as you do prevents that.

Second thing is to take x number of readings, then divide by x and then by time.
but, you would want a circular buffer ( ring buffer?) so you delete the oldest reading.

here is one tutorial

Don't use float for SEC and MIN. Use unsigned LONG. Extract SEC and MIN using modulo, %.