int oldSensVal = 1; //initialize sensor value int count = 0; //initialize count of magnet passes void setup() { Serial.begin(9600); //start serial communication } void loop() { int sensorValue = digitalRead(2); //read sensor value, save as 'sensorValue' if (sensorValue==0){ //if sensor value is 0, i.e. detects magnet Serial.print("magnet"); //..print 'magnet' if (sensorValue!=oldSensVal){ //if the sensor value has just changed count++; //count that as an additional count for magnet passed } } else{ //otherwise.. Serial.print(sensorValue); //print the sensor Value (0 or 1) } Serial.print("-"); Serial.println(count); //display the total count of magnet passes delay(10); //delay period (ms) oldSensVal = sensorValue; //set currentvalue as the previous value }