/* AnalogReadSerial Reads an analog input on pin 0, prints the result to the Serial Monitor. Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu). Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial */ unsigned long currentTime; unsigned long detectTime = 0; unsigned long elapsedTime = 0; int oldSensVal = 1; //initialize sensor value int count = 0; //initialize count of magnet passes bool stopped; void setup() { Serial.begin(9600); //start serial communication pinMode(3, OUTPUT); pinMode(4, OUTPUT); } void loop() { int sensorValue = digitalRead(2); //read sensor value, save as 'sensorValue' currentTime = millis(); if (sensorValue==0 && sensorValue!=oldSensVal){ //if sensor value is 0, i.e. detects magnet stopped=false; elapsedTime=currentTime-detectTime; detectTime=currentTime; count++; //count that as an additional count for magnet passed /* Serial.print("Time in MSec: "); Serial.print(currentTime); Serial.print(" .. "); Serial.print(count); Serial.print(" detection... and "); Serial.print(elapsedTime); Serial.println(" milliseconds passed since last detection."); Serial.print("This means: "); */ Serial.println(360000/elapsedTime); /* Serial.println(" degrees per second"); Serial.println("-----------------------------------"); */ digitalWrite(3,HIGH); digitalWrite(4,HIGH); } else if (sensorValue==0 && sensorValue==oldSensVal){ //otherwise.. digitalWrite(3,HIGH); digitalWrite(4,HIGH); } else{ digitalWrite(3,LOW); digitalWrite(4,LOW); } delay(10); //delay period (ms) oldSensVal = sensorValue; //set currentvalue as the previous value if ((currentTime-detectTime)>=800 && stopped==false){ Serial.println(0); stopped=true; } }