Counting pulses using hall effect sensor

Hello,

We are trying to count the number of pulses registered by a hall sensor. When the magnet passes the sensor, it’s output is low and then returns high when the magnetic field is removed

Every time this happens we want to that to be counted as one pulse. However, when using serial print, the code we have at the moment the counter increases many times for one pass.

const int hallPin=8;
const int ledPin=13;
int hallState ;
int lasthallState;
int rpmcount =0;
int motorSt=2;
int motorDr=3;
int motorEn=4;
int i=0;
boolean isCheck=false;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
 Serial.begin(9600);
 
   pinMode(motorEn, OUTPUT);
  pinMode(motorDr, OUTPUT);
  pinMode(motorSt, OUTPUT);
   
}

void loop()
 {
   if(i<2500) 
  {
    digitalWrite(motorSt, HIGH);
    delayMicroseconds(1000);
    digitalWrite(motorSt, LOW);
    delayMicroseconds(1000);
    i++;

  }
    hallState = digitalRead(hallPin);
 
     if (hallState!=lasthallState  ){
     digitalWrite(ledPin, HIGH); 
     rpmcount++;
     Serial.println(rpmcount);
           lasthallState = digitalRead(hallPin);


}

else{digitalWrite(ledPin, LOW);} 
hallState=lasthallState;

 }

Can anyone tell us why it doesn’t count one for every pass of the magnet?

Many thanks

note: this is for use with a stepper motor and counting the number of revolutions

     Serial.println(rpmcount);
           lasthallState = digitalRead(hallPin);

You are re-reading hallPin and assigning it to lasthallState, which means that lasthallState really isn't the last hall state. It's the current hall pin reading. Try changing that to lasthallState = hallState;. I suspect the Serial.println() has used up enough time that the hallPin has changed again.